Summary: in this tutorial, you’ll learn about the JavaScript undefined
and how to handle it effectively.
If you have been working with other programming languages such as Java or C#, you may find that these languages have the null
value.
JavaScript also has the null
value. In addition, it has the undefined
value. And both null
and undefined
values represent empty values in JavaScript.
What is undefined
The undefined
is a primitive type in JavaScript. So the undefined
is a type. And the undefined
type has exactly one value that is undefined
.
JavaScript uses the undefined
value in the following situations.
1) Accessing an uninitialized variable
When you declare a variable and don’t initialize it to a value, the variable will have a value of undefined.
For example:
let counter;
console.log(counter); // undefined
Code language: JavaScript (javascript)
It’s a good practice to always initialize a variable whenever possible. In this example, you can initialize the counter
variable to zero, like this:
let counter = 0;
console.log(counter); // 0
Code language: JavaScript (javascript)
2) Accessing a non-existing property of an object
If you access a non-existing property of an object, you’ll get undefined
. For example:
let counter = {
current: 0
};
console.log(counter.max); // undefined
Code language: JavaScript (javascript)
In this example, the counter
object has one property current
. Accessing the max
property that doesn’t exist on the counter
object returns undefined
.
It’s good practice to check if the property exists before accessing it. JavaScript provides you with some ways to do so.
And the most common way to verify whether the object has a property is to use the in
operator:
'propertyName' in objectName
Code language: JavaScript (javascript)
Note that you need to surround the property name of the object with single or double-quotes.
The following example uses the in
operator to check if the max
property exists on the counter
object before accessing it:
let counter = {
current: 0
};
if('max' in counter) {
console.log(counter.max);
}
Code language: JavaScript (javascript)
If you want to assign a default value when the property of an object doesn’t exist, you can use the nullish coalescing operator (??
):
const propValue = object.propName ?? defaultValue;
Code language: JavaScript (javascript)
In this syntax, the nullish coalesing operator (??
) returns the defaultValue
if the object.propName
is undefined
or null
.
Note that the nullish coalescing operator has been available since ECMAScript 2020.
let counter = { current: 0 };
const max = counter.max ?? 100;
Code language: JavaScript (javascript)
3) Function parameters
When you call a function with a number of parameters, you often pass the same number of arguments. For example:
const formatCurrency = (amount, currency) => {
return currency === '$' ?
`$${amount}`: `${amount} ${currency}`;
}
Code language: JavaScript (javascript)
The formatCurrency()
function has two parameters. When calling it, you can pass two arguments like this:
formatCurrency(100,'$'); // $100
Code language: JavaScript (javascript)
And it returned $100
as expected.
But when you call the formatCurrency()
function and don’t pass all the arguments, the parameters inside the function becomes undefined
. For example:
formatCurrency(100); // 100 undefined
Code language: JavaScript (javascript)
To avoid this situation, you can set a default value for the function parameters like this:
const formatCurrency = (amount, currency = '$') => {
return currency === '$' ?
`$${amount}`: `${amount} ${currency}`;
}
Code language: JavaScript (javascript)
And when calling it without passing the second argument, you’ll get a proper value:
formatCurrency(100); // $100
Code language: JavaScript (javascript)
4) Functions return a value
A function that doesn’t have a return
statement implicitly returns undefined
. For example:
const log = (message) => {
const time = (new Date()).toLocaleTimeString();
console.log(`${time}: ${message}`);
};
const result = log('Hi');
console.log(result); // undefined
Code language: JavaScript (javascript)
Likewise, when a function has a return
statement without an expression, it also returns undefined
. For example:
const add = (a,b) => {
const result = a + b;
return;
}
let result = add(10,20);
console.log(result); // undefined
Code language: JavaScript (javascript)
Consider the following example:
const add = (a,b) => {
return
a + b;
};
let result = add(10,20);
console.log(result); // undefined
Code language: JavaScript (javascript)
The add()
function returns undefined
. It should have returned 30 instead.
The problem is that when you create a new line between the return
keyword and the returned expression ( a + b
), Javascript compiler automatically inserts a semicolon (;) before the new line. This feature is called automatic semicolon insertion (ASI) in JavaScript.
The add()
function will look like the following to the JavaScript compiler:
const add = (a,b) => {
return;
a + b;
};
Code language: JavaScript (javascript)
That’s why you get the undefined
as the return result.
5) Accessing out-of-bounds array elements
When you access an array element that is out-of-bounds, you’ll get the undefined
value. For example:
const colors = ['red', 'green', 'blue'];
console.log(colors[3]); // undefined
Code language: JavaScript (javascript)
In this example, the colors
array doesn’t have any element at index 3. Therefore, the colors[3]
returns undefined
.
Summary
- The
undefined
is a primitive type that has a single valueundefined
. - Accessing an uninitialized variable returns
undefined
. - Accessing a non-existing property of an object returns
undefined
. - Accessing a out-of-bounds array element returns
undefined
. - A function without a
return
statement or with areturn
statement but without an expression returnsundefined
.