Language: EN

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

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

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 (or valid, or any) value.

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 that it has no value. It is used to represent the intentional absence of a value.

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

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 declared variable that has not yet been initialized, its value is undefined.

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

Non-existent Properties

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

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

Functions without return

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

function myFunction() {}

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

Unprovided Arguments

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

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

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

This is undefined

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 that it has no value.

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

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