开发者

JavaScript undefined check

I often see JavaScript code where a function may take in an "options" object and use it like:

var name = typeof options.name !== 'undefined' ? options.name : "Bob";

This seems like it would be equivalen开发者_开发知识库t to the following:

var name = options.name || "Bob"; 

Now, I understand that in certain situations you may actually care that options.name is undefined vs null and this makes sense to me, but I often see this in situations where this distinction is not necessary.

I believe I have heard that people write code like this because of some bug in IE. Can someone elaborate please?


I am not aware of the bug in IE, but those statements aren't exactly equivalent:

  • The first one sets the name variable to the default "Bob" only when options.name is undefined.

  • The second one sets the name variable to "Bob" whenever options.name is falsy. This can be an empty string, the null value, a value of 0, the NaN value, the boolean value false, and also undefined.

For example, if options.name === 0, the first statement will set the name variable to 0, while the second statement will set it to "Bob".


I hope it will depend on what the developer actually intends to do rather than whatever convention they subscribe to. In a lot of cases, the shorter name = options.name || "Bob"; could end up giving you values you don't expect if you aren't aware of its actual behavior because it coerces a boolean value out of options.name. In other cases, other "falsy" values will be impossible (or nearly impossible): if the value is coming off a form element, for example, you don't really need to worry about undefined, null, false or 0 -- it should always be a string as long as the form element exists -- so what this check would do is ensure that the field isn't a blank string (though any white space would get through). Another common pattern similar to options.name || "Bob" is if (options.name) {...}, which has the same potential problems/benefits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜