Last Updated: February 25, 2016
·
897
· peterssonjesper

window.undefined is writable, use void(0)

The variable window.undefined is writable in a number of commonly used browsers. This can create confusion, but there is a simple way to get around it.

void(0) always returns the primitive value of undefined independently of what window.undefined is set to.

Note that this may affect the performance a bit since another function call has to be made. However, in most cases this can be neglected.

3 Responses
Add your response

You can also wrap your code in an IIFE and create a local undefined.

(function(window, undefined){
    alert( typeof undefined ); // 'undefined'
}(window)),
over 1 year ago ·

@kevincennis yeah that's how jQuery does it!

over 1 year ago ·

I think is more readable just to compare undefined as string

typeof somevar === "undefined"

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside