Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between empty items in a JavaScript array and undefined? [duplicate]

Consider the following JavaScript code (in a node REPL):

> let a = new Array(10)
undefined
> a
[ <10 empty items> ]
> a.map(e => 1)
[ <10 empty items> ]
> let b = new Array(10).fill(undefined)
undefined
> b
[ undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined,
  undefined ]
> b.map(e => 1)
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
> 

When I create an empty array, I'll get 'empty items' which seem to behave differently from undefined. Can someone explain what is the difference?

like image 799
Wickoo Avatar asked May 14 '18 08:05

Wickoo


People also ask

What does empty array mean in JavaScript?

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

Does undefined mean empty?

The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value. On the other hand, 'null' refers to a non-existent object, which basically means 'empty' or 'nothing'.

Does empty array equal false?

Empty arrays are true but they're also equal to false.

Why empty objects are not equal in JavaScript?

Objects are compared by their identity or their reference instead of the values inside them. Since two empty objects are 2 separate objects in memory, they are not equal. Arrays are objects in javascript, so same rules apply to them as well.


1 Answers

That's because undefined is a value, while when you create an array for example like this:

var array = [];
array.length = 10;
console.log(array);
>(10) [empty × 10] // in google chrome

10 empty slots are created. The empty slot is different from the undefined value, and the most important difference is that the empty slot is not Enumerable.

var mappedArray = array.map(x => 1);
console.log(mappedArray);
>(10) [empty × 10] // in google chrome

Since map function enumerates the values in the orriginal array and returns the array of the same length, it has no effect on the array of 10 empty slots.

Note that empty slots are named differently in different browsers.

like image 144
A. Milosavljević Avatar answered Oct 07 '22 01:10

A. Milosavljević