The order of operators in JavaScript (||, &&)

I read the source code of Underscore.js, then something confused me:

// Its code, check the passed-in parameter obj 
_.isObject = function(obj) {
  var type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

I am confused by the operator order of expression.

I think operator precedence in

return type === 'function' || type === 'object' && !!obj;

will be from leftto right; I mean:

return (type === 'function' ) || ( type === 'object' && !!obj);

if typeequal to functionreturn true; work differently type === 'object' && !!obj; if typeequal to objectreturn !!obj, same as Boolean(obj); else return false;

I made some examples:

var a = alert(1) || alert(2) && alert(3);
alert(a); //result : 1, 2 undefined;


var a = alert(1) || alert(2) && 0;
alert(a); //result : 1, 2 undefined;

what confused me:

  • Why !!objshould exist? if we delete !!obj, also run the code.

  • operator order of this code? I know that the statement is &&higher than ||, so I think the !!objeffect is when obj is null, but when I train, this is not what I want;

+4
3

false, null. , , - , null - , . - null (, null[propName]) .

console.log(typeof null);

type === 'function' || type === 'object' && !!obj; :

  • type === 'function' - if this is true the expression will return true`
  • type === 'object' - false, false
  • !!obj - null false, true

:

step(false, 1) || step(true, 2) && step(true, 3)

function step(ret, step) {
  console.log(step);
  
  return ret;
}

!!, booleans. , true, !!{} === true, - false, !!null === false.

+4

!!obj

, - typeof null is object.

+1

-, , && , ||, - a && b || c c || a && b. , , a && b || c (a && b) || c. , , .

Regarding your actual question - in javascript,, typeof null === "object"so part of the expression && !!objshould protect against values nullevaluating true.

0
source

Source: https://habr.com/ru/post/1662611/


All Articles