JavaScript variable with pipeline -
this question has reply here:
what “options = options || {}” mean in javascript? [duplicate] 5 answersi have found code in javascript creating object. have no thought below code does.
var = || {};
an explanation appreciated.
the first step here understand becomes this:
var a; = || {};
...and var a
no-op if a
variable has been declared in current scope.
so first part (var a
) makes sure a
exists variable if doesn't already.
the sec part says: if a
has "truthy" value, maintain (don't alter it). if has "falsey" value, assign {}
a
.
the "falsey" values 0
, nan
, null
, undefined
, ""
, , of course, false
. truthy values others.
this works because of javascript's curiously-powerful ||
(logical or) operator which, unlike other languages, not result in true
or false
; instead, evaluates left-hand operand and, if that's truthy, takes value result; otherwise, evaluates right-hand operand , uses result.
javascript
No comments:
Post a Comment