JavaScript undefined check

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

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

It seems to be equivalent to the following:

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

Now I understand that in some situations it may really be interesting for you that options.name is undefined vs null , and this makes sense to me, but I often see this in situations where this difference is not required.

I believe that I heard that people write such code due to some error in IE. Can someone clarify please?

+7
javascript internet-explorer undefined
source share
2 answers

I do not know about the error in IE, but these statements are not quite equivalent:

  • The first sets the name variable to the default value of "Bob" only if options.name is undefined .

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

For example, if options.name === 0 , the first statement sets the name variable to 0 , and the second statement sets it to "Bob" . "Bob"

+6
source share

I hope that this will depend on what the developer is actually going to do, and not on what they subscribe to. In many cases, a shorter name = options.name || "Bob"; name = options.name || "Bob"; may result in you not getting values ​​you don't expect unless you know its actual behavior, because it takes a boolean from options.name . In other cases, other "fake" values ​​will be impossible (or almost impossible): if the value comes off the form element, for example, you do not need to worry about undefined , null , false or 0 - it should always be a string while the form element exists , therefore, this check should ensure that the field is not an empty string (although any free space will pass). Another common pattern similar to options.name || "Bob" options.name || "Bob" , is if (options.name) {...} , which has the same potential problems / benefits.

+2
source share

All Articles