10

I happened to know the following code

Here is the code, and very simple:

var test = 0 || -1 ;
console.log(test);

then the output in the console is -1

and somehow i am really new into the javascript,

all i think of is that the 0 stands for Boolean False in JS ,and so || operator seems to ignore the 0 and assign the value -1 to the variable

so am i right ? i just want a confirm

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Lien
  • 505
  • 1
  • 6
  • 16

2 Answers2

18
  • ||expr1 || expr2 (Logical OR)

    Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false..

  • &&expr1 && expr2 (Logical AND)

    Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

All values in Javascript are either "truthy" or "falsy".
The following values are equivalent to false in conditional statements:

  • false
  • null
  • undefined
  • The empty string "" (\ '')
  • The number 0
  • The number NaN

All other values are equivalent to true.


So... var test = 0 || -1 ; returns -1.

If it was var test = 0 || false || undefined || "" || 2 || -1 it would return 2


Logical operator on MDN

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • In [Practical Node.js](http://www.apress.com/9781430265955) there is the following code: `var user =function (ops) { return { firstName: ops.name || 'John', lastName: ops.name || 'Doe', email: ops.email || 'test@test.com', name:function () {return this .firstName +this .lastName}}}` -- So, I'm guessing it assigns the first values if they're "truthy" (defined) else the second values are defaults? – Fuhrmanator Sep 23 '14 at 13:56
  • @Fuhrmanator Yes that is correct. || and && do not (necessarily) return boolean values. They can be better described as operand selector operators. In case of || if the first operand can be coerced to true, the first operand is returned, else the second operand is returned. The && has the opposite behavior. – Aditya Prasoon Oct 19 '20 at 12:59
3

You can use Nullish coalescing operator (??)

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Only null and undefined will be falsey. 0 will be considered true. But take care: an empty string will be considered true too!

console.log('0 ?? 1  ->', 0 ?? 1) // expected output: 0
console.log('null ?? 1  -> ', null ?? 1) // expected output: 1
console.log('undefined ?? 1  ->', undefined ?? 1) // expected output: 1
console.log('"" ?? 1  ->', "" ?? 1) // expected output: ""
Meffe
  • 61
  • 8