- JavaScript undefined
- What is undefined
- 1) Accessing an uninitialized variable
- 2) Accessing a non-existing property of an object
- 3) Function parameters
- 4) Functions return a value
- 5) Accessing out-of-bounds array elements
- Summary
- Javascript undefined value in array
- # Table of Contents
- # Check if an Array contains Undefined in JavaScript
- # Check if an Array contains Undefined using Array.some()
- # Checking for undefined values that are not empty elements
- # Check if an Array contains Empty Elements in JavaScript
- # Checking only for empty elements, not undefined
- # Checking only for empty elements, not undefined using indexOf
- # Additional Resources
JavaScript undefined
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 === '$' ? `$$ `: `$ $ `; >
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 === '$' ? `$$ `: `$ $ `; >
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(`$ : $ `); >; 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 value undefined .
- 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 a return statement but without an expression returns undefined .
Javascript undefined value in array
Last updated: Jan 8, 2023
Reading time · 4 min
# Table of Contents
# Check if an Array contains Undefined in JavaScript
Use the Array.includes() method to check if an array contains undefined values.
The includes method will return true if the array contains at least one undefined value and false otherwise.
Copied!function containsUndefined(arr) return arr.includes(undefined); > console.log(containsUndefined([1, undefined])); // 👉️ true console.log(containsUndefined([1, 2])); // 👉️ false
The function takes an array and returns true if the array contains at least one undefined value.
The Array.includes() method takes a value and checks for its existence in the array.
Copied!// 👇️ true console.log([1, undefined, 3].includes(undefined)); // 👇️ false console.log([1, 2, 3].includes(undefined));
Note that this approach would also work if there is an empty element in the array.
Copied!function containsUndefined(arr) return arr.includes(undefined); > console.log(containsUndefined([, 2])); // 👉️ true console.log(containsUndefined([])); // 👉️ false
We skipped the first element in the array using a comma, however, it still counts as an undefined value.
An alternative approach is to use the Array.some() method.
# Check if an Array contains Undefined using Array.some()
This is a three-step process:
- Use the Array.some() method to iterate over the array.
- Compare each array element to undefined and return the result.
- If the array contains at least one undefined value, the some() method will return true .
Copied!function containsUndefined(arr) return arr.some(element => element === undefined); > console.log(containsUndefined([1, undefined])); // 👉️ true console.log(containsUndefined([1, 2])); // 👉️ false
The function we passed to the Array.some() method gets called with each element of the array.
If at least one invocation of the callback function returns a truthy value, the some() method returns true , otherwise, false is returned.
On each iteration, we check if the current array element is equal to undefined using the strict equality (===) operator.
If the condition is met at least once, the some() method will return true .
This approach also works if the array contains empty elements.
Copied!function containsUndefined(arr) return arr.some(element => element === undefined); > console.log(containsUndefined([, undefined])); // 👉️ true console.log(containsUndefined([])); // 👉️ false
# Checking for undefined values that are not empty elements
If you need to check if the array contains undefined values that are not empty elements, use the indexOf() method.
Copied!const arr = [1, undefined, 3]; if (arr.indexOf(undefined) > -1) // 👇️ this runs console.log('The array contains undefined values'); > else console.log("The array doesn't contain undefined values"); >
The if block will only run if the array contains undefined values that are not empty elements.
The Array.includes() method returns true if the array contains empty elements or undefined values (or both).
Copied!const arr = [1, , 3]; console.log(arr.includes(undefined)); // 👉️ true
The array doesn’t contain any undefined values but has an empty element, so the includes() method returns true .
# Check if an Array contains Empty Elements in JavaScript
Use the Array.includes() method to check if an array contains empty elements.
The Array.includes() method will return true if the array contains empty elements and false otherwise.
Copied!const arr = [1, , 3]; console.log(arr[1]); // 👉️ undefined console.log(arr.includes(undefined)); // 👉️ true if (arr.includes(undefined)) console.log(`✅ array contains an empty element(s) or undefined value(s)`); > else console.log(`⛔️ array DOESN'T contain an empty element or undefined value`); >
We have an empty element in the array at index 1 . If we try to access the element, we get a value of undefined back.
Copied!const arr = [1, , 3]; console.log(arr[1]); // 👉️ undefined
We used the Array.includes() method to check if the array contains undefined values.
Note that this check would also pass if the array contains an element with a value of undefined .
Copied!const arr = [1, undefined , 3]; console.log(arr.includes(undefined)); // 👉️ true
# Checking only for empty elements, not undefined
If you need to make sure the array contains an empty element and not undefined values, use this approach instead.
Copied!function containsEmptyElements(arr) return Object.values(arr).length !== arr.length; > // 👇️ true console.log(containsEmptyElements([1, 2, , 4])); // 👇️ false console.log(containsEmptyElements([1, 2, undefined, 4]));
We passed the array to the Object.values() method.
Copied!// [ 1, 2, 4 ] console.log(Object.values([1, 2, , 4])); // [ 1, 2, undefined, 4 ] console.log(Object.values([1, 2, undefined, 4]));
Notice that empty elements get removed in the call to Object.values() but undefined values don’t.
If the length of the array the Object.values() method returns is not equal to the length of the array, then the array contains empty elements.
# Checking only for empty elements, not undefined using indexOf
You can also use the Array.indexOf() method to check if the array contains empty elements.
Copied!function containsEmptyElements(arr) return arr.indexOf(undefined) === -1 && arr.includes(undefined); > const arr = [1, 2, , 4]; console.log(containsEmptyElements(arr)); // 👉️ true if (containsEmptyElements(arr)) // 👇️ this runs console.log('✅ The array contains empty element(s)'); > else console.log("⛔️ The array DOESN'T contain empty elements"); >
We used the logical AND (&&) operator to chain multiple conditions.
The if statement checks if the Array.indexOf method returns -1 and the array contains undefined values.
This check would only succeed if the array has one or more empty elements.
The Array.indexOf() method returns -1 only when it doesn’t find the supplied value.
The includes() method treats empty array elements as undefined , however, empty elements don’t actually have a value of undefined .
This is why the indexOf method doesn’t find an element with the value of undefined in the array.
If both of the conditions are met, the array contains one or more empty elements.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.