JS — operator a||b or a ? a : b

blossom0417
2 min readSep 5, 2018

--

# pos = pos || 0;

this is known as “short circuiting”

a || b; // if both true, left value will print
// roughly equivalent to:
a ? a : b;

a && b; // if both true, right value will print
// roughly equivalent to:
a ? b : a;

The value produced by a && or || operator is not necessarily of type Boolean.

https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md#operators--and-

if both is true, left side will be printed out
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o4 = false || (3 == 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
o10 = 0 || 4 // 4

# pos = pos ? pos : contentElemsTotal;

  • Ternary Operator
if(pos){return pos;}else{return contentElemsTotal;}

# var voteable = (age < 18) ? “Too young”:”Old enough”;

var func1 = function( .. ) {
if (condition1) { return value1 }
else { return value2 }
}

var func2 = function( .. ) {
return condition1 ? value1 : value2
}

# a && b

  • true1 && true2 // true2 — 값이 둘 다 참이면 오른쪽 피연산자 출력
  • false1 && false2 // false1- 값이 둘 다 거짓이면 왼쪽 피연산자 출력
a5 = 'Cat' && 'Dog'      // t && t returns "Dog"
a6 = false && 'Cat' // f && t returns false
a7 = 'Cat' && false // t && f returns false
a8 = '' && false // f && f returns ""
a9 = false && '' // f && f returns false

if
(a == b) stop(); // Invoke stop() only if a == b
(a == b) && stop(); // This does the same thing

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND_()

#reference

https://javascript.info/logical-operators

--

--