Comparing a variable with 1 is the same as comparing with true?

0

I have the following code:

    $(function() {
    var logado = _userdata["session_logged_in"];
    if (logado == 1) {
        $('#rankPersonalizado').after('Você está logado.');
    }
});

Here:

if (logado == 1) {

1 means that it is true . Specifying if the user is logged in.

If it has not already been specified, see the example below:

se (logado == sim) {
    
asked by anonymous 10.10.2015 / 16:48

1 answer

2

You give the semantics you want to the values you use. If you have control over the contents of the variable, you can even choose the data type you want.

So if you prefer that the information of logado is already a Boolean, true or false % can be used like this:

$(function() {
    var logado = _userdata["session_logged_in"];
    if (logado) {
        $('#rankPersonalizado').after('Você está logado.');
    }
});

If you will not use this local variable elsewhere in your code (you are not currently using it) and you want to simplify:

$(function() {
    if (_userdata["session_logged_in"]) {
        $('#rankPersonalizado').after('Você está logado.');
    }
});

If you do not have control over the value of this "global" variable that indicates whether the user is logged in , you can still transform to Boolean in other operations:

$(function() {
    var logado = _userdata["session_logged_in"] == 1;
    if (logado) {
        $('#rankPersonalizado').after('Você está logado.');
    }
});

This way the variable is unnecessary (if the code is not modified and the value is used elsewhere), but it can be useful to document what it means. Although it is for a more semantic name, it would be best to use _userdata["session_logged_in"] . But it's each one's style.

    
10.10.2015 / 17:23