Is comparing a variable to 1 the same as comparing it to true?

Asked

Viewed 137 times

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 not yet specific, see the example below:

se (logado == sim) {
  • 1

    It is not possible to understand what you are wanting. What is the data that can be stored in _userdata["session_logged_in"] . È 0 or 1? Has true or false? Has "sim" or "não". Something else? What do you want to do differently? Why?

  • Rephrase the question.

  • @bigown basically I would like to know what was 0 and 1.

  • 1

    You don’t know what you want, what you’re saying doesn’t make sense. Detail is "knowing what was 0 and 1". Describe step by step what you want. And answer what I asked before.

  • Right. Note this: var logged in = _userdata["session_logged_in"]; is declaring that the variable logged in means the user is logged in. Imagine that I want to do otherwise, I would have to do: if (logged in == 0); right? 0 would mean false and 1 would mean true?

  • Yeah, that’s all you wanna know?

  • That’s exactly what.

  • maybe your question should be "comparing a variable to 1 is the same as comparing it to true?"

  • Edited. :) Thank you!

Show 4 more comments

1 answer

2


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

So if you prefer that information from logado is already a boolean, saved true or false in _userdata["session_logged_in"] Then you can use it like this:

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

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

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

If you have no control over the value of this "global" variable that indicates if the user is logged, can still turn into boolean in other operations:

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

I put in the Github for future reference.

This form is unnecessary (if the code is not modified and the value is used elsewhere), but it can be useful to document what that means. Although if you’re going for a more semantic name, you’d better use estahLogado. But it’s everyone’s style.

  • Thank you for clarifying my question, I am grateful! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.