I've just executed the following in console:
typeof false || undefined // "boolean"
While I expected it to return "undefined", since
typeof undefined // "undefined"
Why did it return "boolean"? Isn't the OR
operator supposed to return the last argument if previous evaluated to falsey values? So that false || undefined
false || undefined
returns undefined
and typeof
is executed against undefined
?
You're not observing operator precedence!
> typeof false || boolean // (typeof false) || boolean
"boolean"
> typeof (false || boolean)
"undefined"
The OR
operator returns the left argument as long as it isn't falsy.
In your example, we've got this:
(typeof false) || undefined
typeof false
returns "boolean"
, which isn't falsy, so it is returned rather than undefined
.
Consider the code :
typeof false || undefined
typeof false
will return "boolean" , so it will become "boolean" || undefined
"boolean" || undefined
The final output will be "boolean"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.