Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you assign undefined in JavaScript?

Tags:

javascript

Consider the following code:

var x = undefined;

It's a self-contradicting line of code. Is x defined or not? Do implementations of JavaScript remove the variable x from memory, or do they assign it the value undefined?

like image 258
JSideris Avatar asked Apr 12 '15 23:04

JSideris


People also ask

What does undefined do in JavaScript?

The undefined property indicates that a variable has not been assigned a value, or not declared at all.

What happens when you add undefined?

Adding numbers to undefined results in NaN (not-a-number), which won't get you anywhere.

Should you assign undefined?

Undefined indicates a very specific use case. It means that the value is not initialized, and you don't know what the value is. The problem is you would not want to get "undefined" as an output while working with your code unless it indicates a problem that is tied up to the lack of assignment.

Should you use undefined in JavaScript?

TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference.


1 Answers

There's a difference between a variable being undeclared and being undefined:

var x;     //x is equal to *undefined*
alert(y);  //error, y is undeclared

This isn't self-contradicting, but it is redundant:

var x = undefined;

Think of undefined as simply the value a variable has when it hasn't been initialized – or the value an object property has when it hasn't been initialized or declared.

like image 53
Rick Hitchcock Avatar answered Oct 15 '22 22:10

Rick Hitchcock