最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - A = b || "foo"; complains that 'b' is undefined and does not assign a to &quo

programmeradmin5浏览0评论

In my JavaScript code, and in Chrome dev tools I write:

a = b || "foo";

And get this error:

ReferenceError: b is not defined

And a is not set to "foo". I know this is a valid pattern in JavaScript. What am I missing?

In my JavaScript code, and in Chrome dev tools I write:

a = b || "foo";

And get this error:

ReferenceError: b is not defined

And a is not set to "foo". I know this is a valid pattern in JavaScript. What am I missing?

Share Improve this question edited Apr 30, 2014 at 4:27 Peter O. 32.9k14 gold badges84 silver badges97 bronze badges asked Apr 29, 2014 at 14:39 Daniel WilliamsDaniel Williams 9,32416 gold badges78 silver badges117 bronze badges 6
  • 2 "Have I not had enough coffee?" How can we know... Do you have such feeling? Than drink some more. – nicael Commented Apr 29, 2014 at 14:41
  • var a = window.b || "foo";.. if b is global variable.. – Mr_Green Commented Apr 29, 2014 at 14:47
  • @Mr_Green And if the variable is in another scope ? – Denys Séguret Commented Apr 29, 2014 at 14:47
  • @dystroy may be this.b.. :| – Mr_Green Commented Apr 29, 2014 at 14:48
  • @Mr_Green You want to thing again about this one... – Denys Séguret Commented Apr 29, 2014 at 14:50
 |  Show 1 more ment

2 Answers 2

Reset to default 11

Your pattern is OK if the value of b is undefined.

If the variable b might be not defined, it's an error to try to read it so it's a little more plicated :

a = typeof b!=="undefined" ? b : "foo";

Be careful with b||something even when you know the variable is defined (which is the most mon case) : Most often you want to provide a default value to replace undefined, not prevent the caller to pass 0 or "" so it's usually safer to do b!==undefined ? b : "foo".

That is not a valid pattern in JavaScript. It is only valid in a context where b exists, for example

function test(b) {
    var a = b || "foo";
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论