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

安稳与你 提交于 2019-12-05 12:02:54

They want to return false if the object is null. Usually when we need to know if something is an object, null is not what we're looking for. That's because trying to access null's properties (null[propName] for example) would throw an error.

console.log(typeof null);

The order of execution for the expression type === 'function' || type === 'object' && !!obj; is from left to right:

  1. type === 'function' - if this istruethe expression will return true` without computing the rest
  2. type === 'object' - if this is false the expression will return false without computing the last part
  3. !!obj - null would return false, any other object would return true

The snippet demonstrates the flow:

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

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

Using !! we can cast values to booleans - So truthy values would be converted to true, for example !!{} === true, and falsy ones to false, for example !!null === false.

Nina Scholz

The last

!!obj

forces the return value to a boolean value and yes, it is necessary because of typeof null is object.

Firstly, the expression is not read left to right, && has a slightly higher precedence than ||, so it can be written either way -- a && b || c is identical to c || a && b. Operator precedence determines where parenthises should go in the expression, so a && b || c would be (a && b) || c. It's only within expressions where every operator has the same precedence that the operators are evaluated from left to right.

Regarding you're actual question -- in javascript, typeof null === "object", so the && !!obj part of the expression is to guard against null values evaluating to true.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!