uso-de-null-y-undefined-en-javascript

What is null and undefined in JavaScript and how to use them

  • 2 min

In Javascript, variables are containers we use to store values. Two ‘special’ ones that we will encounter more frequently are undefined and null.

Both have similarities, in the sense that they are used to indicate that a variable does not have a meaningful value (or a valid one, or any value at all).

However, they have different meanings and uses:

  • undefined: It is the value automatically assigned to a variable that has been declared but not initialized.

  • null: It is a value explicitly assigned to a variable to indicate it has no value. It is used to represent the intentional absence of a value.

That is, as we see, the difference between one and the other is that undefined is automatic, and null is explicit.

The undefined Value

undefined is a primitive value in JavaScript. It is used to indicate that a variable has been declared, but has not been initialized with a value.

Where we will encounter undefined

Uninitialized Variables

If we try to access a variable that has been declared but not yet initialized, its value is undefined.

let x;
console.log(x); // undefined
Copied!

Non-existent Properties

If we try to access a property that does not exist in an object, the result is undefined.

let obj = {};
console.log(obj.nonExistentProperty); // undefined
Copied!

Functions without return

Functions that do not have a return statement implicitly return undefined.

function myFunction() {}

console.log(myFunction()); // undefined
Copied!

Arguments not provided

If an argument is not provided when calling a function, its value is undefined.

function greet(name) {
   console.log(name);
}
greet(); // undefined
Copied!

In summary, we will have undefined every time we try to access something that is not there (or not yet there). javascript-undefined-travolta

This is undefined

The null Value

null is a primitive value used to intentionally indicate the absence of a value. Unlike undefined, which is generally assigned automatically, null is explicitly assigned by the programmer.

Where we will encounter null

Explicit Assignment

In this case, x is explicitly initialized with null, indicating it has no value.

let x = null;
console.log(x); // null
Copied!

Empty Objects

Using null in object properties can be a way to indicate that no value has been assigned to that property.

let obj = { property: null };

console.log(obj.property); // null
Copied!