-2

I am making sense of an old project that was thrown on me on job. Stumbled upon the following piece (given these two variables were declared somewhere before):

someVar = 234 && !anotherVar;

Is it just a mistake or some fancy ninja move?

shal
  • 2,854
  • 4
  • 20
  • 31
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators – Maxx Sep 12 '16 at 10:34
  • Do you understand `if (234 && !anotherVar)`? Then what don't you understand about this? – deceze Sep 12 '16 at 10:36
  • @deceze it's not the same – Maxx Sep 12 '16 at 10:36
  • 2
    @Maxx How's it different? – deceze Sep 12 '16 at 10:36
  • 1
    @deceze `if (234 && !anotherVar)` executes code by condition and `234 && !anotherVar` returns value. in this example `someVar` will be equal `!anotherVar`, because `Boolean(234)` is `true` – Maxx Sep 12 '16 at 10:39
  • @Maxx Obviously so. Obviously this is not an `if` statement. I'm asking the OP whether they understand the `234 && !anotherVar` *in* `if (234 && !anotherVar)`… – deceze Sep 12 '16 at 10:42
  • I understand it, I don't understand why did he put it here? Does the statement after && affect the assignment in the left part? Why did he put it here, if the left part will be evaluated anyway? – shal Sep 12 '16 at 10:55
  • We don't know why a particular developer writes a particular piece of code. If the left hand side is indeed `234`, hardcoded, then it's indeed pretty darn pointless and the whole thing could be abbreviated to `someVar = !anotherVar`. – deceze Sep 12 '16 at 10:56
  • Possible duplicate of [Why don't logical operators (&& and ||) always return a boolean result?](http://stackoverflow.com/questions/5417969/why-dont-logical-operators-and-always-return-a-boolean-result) – shal Sep 12 '16 at 11:05

1 Answers1

0

&& is logical AND

It expects two arguments and returns:

First term that evaluates to false (is false-y).

Last term otherwise (if no term evaluates to false)

Here are some examples:

0 && false          0 (both are false-y, but 0 is the first) 
true && > false     false (second one is false-y) 
true && true        true> (both are true-y) 
true && 20          20 (both are true-y) 

This definition completely conforms to the definition of logical and from the field of mathematics.

Read More @ Good Explanation of & vs &&

Community
  • 1
  • 1
  • I know perfectly what i&& is. I'll refine the question. – shal Sep 12 '16 at 10:55
  • @shal look at the highlighted text. Im not saying you dont know what && is, its rather a more extensive explanation of what && does in certain scenarios. In this case, "Last term otherwise" is happening. – Don Bhrayan Singh Sep 13 '16 at 02:29
  • Ok, I just realized how stupid this question is, but I can't delete it. What a shame... Thank you for your patience! – shal Sep 14 '16 at 06:21