Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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() ?

like image 212
patrick Avatar asked May 09 '11 19:05

patrick


1 Answers

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 = ....

like image 150
Raynos Avatar answered Nov 02 '22 22:11

Raynos