Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: undefined !== undefined?

Tags:

javascript

NOTE: As per ECMAScript5.1, section 15.1.1.3, window.undefined is read-only.

  • Modern browsers implement this correctly. for example: Safari 5.1, Firefox 7, Chrome 20, etc.
  • Undefined is still changeable in: Chrome 14, ...

When I recently integrated Facebook Connect with Tersus, I initially received the error messages Invalid Enumeration Value and Handler already exists when trying to call Facebook API functions.

It turned out that the cause of the problem was

object.x === undefined 

returning false when there is no property 'x' in 'object'.

I worked around the problem by replacing strict equality with regular equality in two Facebook functions:

FB.Sys.isUndefined = function(o) { return o == undefined;}; FB.Sys.containsKey = function(d, key) { return d[key] != undefined;}; 

This made things work for me, but seems to hint at some sort of collision between Facebook's JavaScript code and my own.

What could cause this?

Hint: It is well documented that undefined == null while undefined !== null. This is not the issue here. The question is how comes we get undefined !== undefined.

like image 254
Youval Bronicki Avatar asked Apr 22 '09 12:04

Youval Bronicki


People also ask

Is undefined == undefined JavaScript?

The object. x === undefined should return true if x is unknown property. If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

Why is type of undefined undefined in JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Why undefined === undefined is false?

So undefined really means undefined. Not False, not True, not 0, not empty string. So when you compare undefined to anything, the result is always false, it is not equal to that.


1 Answers

The problem is that undefined compared to null using == gives true. The common check for undefined is therefore done like this:

typeof x == "undefined" 

this ensures the type of the variable is really undefined.

like image 88
Wolfram Kriesing Avatar answered Oct 10 '22 02:10

Wolfram Kriesing