Precedence: Logical or vs. Ternary operator

时光总嘲笑我的痴心妄想 提交于 2019-11-28 12:59:27

Yes, the || operator has higher precedence than the conditional ?: operator. This means that it is executed first. From the page you link:

Operator precedence determines the order in which operators are evaluated. Operators with higher precedence are evaluated first. (MDN)enter link description here

Let's have a look at all the operations here:

step = step || (start < end) ? 1:-1;

The operator with the highest precedence is the () grouping operation. Here it results in false:

step = step || false ? 1 : -1;

The next highest precedence is the logical OR operator. step is truthy, so it results in step.

step = step ? 1 : -1;

Now we do the ternary operation, which is the only one left. Again, step is truthy, so the first of the options is executed.

step = 1;

JavaScript is loosely typed which means that whenever an operator or statement is expecting a particular data-type, JavaScript will automatically convert the data to that type.

Let's see some scenarios how it converts to other type

example 1.

if() statement expects a boolean value, therefore whatever you define in the brackets will be converted to a boolean.

JavaScript values are often referred to as being "truthy" or "falsey", according to what the result of such a conversion would be (i.e. true or false).

Remember if a value is truthy unless it’s known to be falsey.

Fortunately there are only six falsey -

  1. false (of course!)
  2. undefined
  3. null
  4. 0 (numeric zero)
  5. "" (empty string)
  6. NaN (Not A Number)

example 2.

var x = zoo || star ;

If zoo evaluates to true then the value of zoo is returned, otherwise the value of star is returned

example 3.

var str = '1' || '2';

'1' is not falsey so '1' will be returned result : str = '1';

example 4.

var str = '1' || (true) ? '2' : '3';

first of all precedence of ||(Logical OR) operator is greater than ?(Conditional) operator

so first ( '1' || (true) ) will be evaluated first

'1' is not falsey so '1' will be returned

Intermediate result : str = '1' ?' 2' : '3'

'1' is not truthy so '2' will be returned

Final result : str = '2'

example 5.

var str = '1' || (false) ? '2' : '3';

first of all precedence of ||(Logical OR) operator is greater than ?(Conditional) operator

so first ( '1' || (false) ) will be evaluated first

'1' is not falsey so '1' will be returned

Intermediate result : str = '1' ?' 2' : '3'

'1' is not truthy so '2' will be returned

Final result : str = '2'

Now it will be very easy to figure out in your scenario :)

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