Undefined Value in JavaScript

Is there ever a good reason to use undefined?

No, not really. It’s often confused with null and the string value “undefined” returned by the typeof operator.

Essentially, variables that are not initialized have a value of undefined. When you set a variable to null, you indicate that it will eventually contain an object.


// Bad. The account variable is not initialized.
let account;
console.log(account === undefined); // Evaluates to true.

// Bad. The accountTwo variable is not declared.
let accountOne;
console.log(typeof accountOne); // Evaluates to undefined.
console.log(typeof accountTwo); // Evaluates to undefined.

// Good. The account variable is initialized to null.
let account = null;
console.log(account === null); // Evaluates to true.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s