admin管理员组

文章数量:1291139

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 equivalent 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 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 equivalent 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?

Share Improve this question edited Sep 2, 2010 at 0:13 Daniel Vassallo 345k72 gold badges512 silver badges446 bronze badges asked Sep 1, 2010 at 23:53 Bain MarkevBain Markev 2,9955 gold badges30 silver badges28 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

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 ing 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 mon pattern similar to options.name || "Bob" is if (options.name) {...}, which has the same potential problems/benefits.

本文标签: internet explorerJavaScript undefined checkStack Overflow