简体   繁体   中英

explicit typeof == “undefined” check vs just checking for its existence?

assuming x is an object... Is there any benefit of doing:

 if (typeof x.foo != "undefined")

vs. doing

 if (x.foo)

?

This question came up as I was reading this blog post: http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

In his example, he does:

function EventTarget(){
  this._listeners = {};
}

EventTarget.prototype = {

  constructor: EventTarget,

  addListener: function(type, listener){
    if (typeof this._listeners[type] == "undefined"){
        this._listeners[type] = [];
    }

    this._listeners[type].push(listener);

In this case this._listeners[type] will never be anything except an array-- so is it not true that it would be cleaner in this case to just do

addListener: function(type, listener){
    if (!this._listeners[type]){
        this._listeners[type] = [];
    }

    this._listeners[type].push(listener);

?

Also, as a side question, I don't get why he's doing:

EventTarget.prototype = {

  constructor: EventTarget

Isn't the constructor by default already set to EventTarget ('this') when you call new EventTarget() ?

Watch out for truthy values .

if (x.foo) will not run if x.foo is

  • false
  • null
  • undefined
  • ""
  • 0
  • NaN

Where as if (typeof x.foo !== "undefined") { only checks for whether the value is undefined

Alternative checks would be

if (x.foo !== undefined) { and if (x.foo !== void 0) {

Do be wary that undefined can be overwritten as a local variable

undefined = true is a valid statement and will break all your code. Of course you will never see this code in production so you don't really have to shield against it, it's just something to be wary of.

I personally tend to use

if (x.foo != null) {
    ...
}

a lot which checks for both null and undefined .

[[Edit]]

In your specific example it's either an Array or undefined so !foo is safe. personally I prefer to check specifically for undefined so that users know I only expect it to run when it's undefined rather then when it's null or false or "" . This makes the code more explicit / self documenting.

As to

EventTarget.prototype = {

  constructor: EventTarget

If you overwrite EventTarget.prototype with a new object then the EventTarget.prototype.constructor property is lost and needs to be set again.

You do not need to set .constructor again if you just extend the prototype by calling EventTarget.prototype.method = ... .

The first explicitly checks that x.foo is undefined , whereas if (x.foo) is checking to see if x.foo is truthy.

http://11heavens.com/falsy-and-truthy-in-javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM