JavaScript OR (||) variable assignment explanation

Given this snippet of JavaScript... var a; var b = null; var c = undefined; var d = 4; var e = 'five'; var f = a || b || c || d || e; alert(f); // 4 Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly? My understanding is that variable `f` will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot. Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in `f` having a true boolean value, rather than the value of `d` itself.
Old question, but regarding PHP, there is a construct you can use: $f=$a or $f=$b or $f=$c; // etc. PHP has both the || operator and the or operator, which do the same job; however or is evaluated after assignment while || is evaluated before. This also give you the perlish style of $a=getSomething() or die('oops');

以上就是JavaScript OR (||) variable assignment explanation的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏