Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is "undefined x 1" in JavaScript?
The "undefined x 1" notation is not a JavaScript feature but Chrome's way of displaying sparse arrays with uninitialized elements. Instead of showing every undefined value, Chrome uses compact notation for better readability.
What Creates "undefined x n"
When you create an array with the Array() constructor or have gaps in array indexes, Chrome displays uninitialized slots as "undefined x count":
console.log(Array(5));
[undefined × 5]
Sparse Arrays Example
Arrays with missing indexes also show this notation:
let arr = [1, , , 4]; // Missing elements at index 1 and 2 console.log(arr); console.log(arr.length);
[1, undefined × 2, 4] 4
Difference from Explicit undefined
There's a difference between uninitialized slots and explicitly set undefined values:
let sparse = Array(3); // Uninitialized slots
let explicit = [undefined, undefined, undefined]; // Explicit undefined
console.log("Sparse array:");
console.log(sparse);
console.log("Explicit undefined:");
console.log(explicit);
Sparse array: [undefined × 3] Explicit undefined: [undefined, undefined, undefined]
Behavior with Array Methods
Uninitialized slots behave differently with array methods:
let sparse = Array(3);
let explicit = [undefined, undefined, undefined];
console.log("Sparse forEach count:");
let sparseCount = 0;
sparse.forEach(() => sparseCount++);
console.log(sparseCount);
console.log("Explicit forEach count:");
let explicitCount = 0;
explicit.forEach(() => explicitCount++);
console.log(explicitCount);
Sparse forEach count: 0 Explicit forEach count: 3
Conclusion
Chrome's "undefined x n" notation improves readability for sparse arrays. Remember that uninitialized slots behave differently from explicit undefined values in array operations.
