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?
That's because Array(10) doesn't populate the array. But it just set the length property to 10 .So, the array created using Array constructor is simply an object with a length property, but with no items populated.
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?
That's because Array(10) doesn't populate the array. But it just set the length property to 10 .So, the array created using Array constructor is simply an object with a length property, but with no items populated.
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.
Arrays are objects. That means that your array
[undefined,undefined,undefined,empty,4]
could be written as such an object:
{
0: undefined,
1: undefined,
2: undefined,
// 3 doesnt exist at all
4: 4,
length: 5,
}
So undefined is actually a slot that exists and holds a value while 3 is not even a key-value pair. As accessing a non existing key results in undefined there is no real world difference:
array[2] // undefined
array[3] // undefined
But iterating over an array with map and others will skip empty ones, so then you should use .fill before iterating.
The only way to detect a difference is to check if the key exists:
2 in array // true
3 in array // false
To turn empty to undefined you could set the key:
array[3] = undefined;
and to turn undefined into empty you have to remove the key:
delete array[3]
however that rarely matters.
empty is not a type. It is just a way of describing that there is nothing there. It isn't undefined or null. It is the complete lack of a value. You'll only see that when it tries to show you a representation of the array. If you actually look in those indices, it will return undefined.
How can I verify if an array is empty or undefined?
What's the difference between undefined and empty value in JS?
javascript object/array undefined vs empty - Stack Overflow
javascript - What's the difference between 'empty x 2' array and [undefined, undefined]? - Stack Overflow
When you read a property which doesn’t exist you get the value undefined. That’s standard JS.
When you log a whole array, you aren’t reading the property explicitly, so the console helpfully distinguishes between “has no value” and “explicitly has the undefined value”.
The word empty is added by the console interface of the browser.
The correct state of an unassigned array element is undefined - and this is given to you by JS when you try to access it. Besides this, the interpretation of unassigned array elements is subjected to the system which interprets it.
Here are some examples:
let arr = new Array(2);
console.log(arr[0]); //undefined
console.log(arr); //In SO - [undefined, undefined]. In browser [empty x 2]
console.log(JSON.stringify(arr)); // [null, null]
let array = new Array(4);
array[3] === undefined //true
console.log(array) // [ <4 empty items> ]
array.push(undefined)
console.log(array) // [ <4 empty items>, undefined ]
main difference would be forEach and map properties
Array(2).map(()=>"value") will not do anything
[undefined,undefined].map(()=>"value") will map
The empty values aren't iterable:
var arr = new Array(5)
arr.forEach(()=> console.log('hello'))
var arr2 = [...arr]
arr2.forEach(()=> console.log('world'))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Intro to sparse arrays
First a clarification what you've created is called a sparse array. To put it simply, sparse arrays are similar to normal arrays but not all of their indexes have data. In some cases, like JavaScript, this leads to slightly more significant handling of them. Other languages simply have a normal array of fixed length with some values that are "zero" in some sense (depends on what value can signify "nothing" for a specific array - might be 0 or null or "", etc).
Empty slots
The empty slot in a sparse array is exactly what it sounds like - slot that is not filled with data. JavaScript arrays unlike most other implementations, are not fixed size and can even have some indexes simply missing. For example:
const arr = []; // empty array
arr[0] = "hello"; // index 0 filled
arr[2] = "world"; // index 2 filled
You will get an array with no index 1. It's not null, nor it's empty, it's not there. This is the same behaviour you get when you have an object without a property:
const person = {foo: "hello"};
You have an object with a property foo but it doesn't have, for example, a bar property. Exactly the same as how the array before doesn't have index 1.
The only way JavaScript represents a "value not found" is with undefined, however that conflates
- "the property exists and the value assigned to it is
undefined" - "the property does not exist at all"
Here as an example:
const person1 = { name: "Alice", age: undefined };
const person2 = { name: "Bob" };
console.log("person1.age", person1.age);
console.log("person2.age", person2.age);
console.log("person1.hasOwnProperty('age')", person1.hasOwnProperty('age'));
console.log("person2.hasOwnProperty('age')", person2.hasOwnProperty('age'));
You get undefined when trying to resolve age in either case, however the reasons are different.
Since arrays in JavaScript are objects, you get the same behaviour:
const arr = []; // empty array
arr[0] = "hello"; // index 0 filled
arr[2] = "world"; // index 2 filled
console.log("arr[1]", arr[1]);
console.log("arr.hasOwnProperty(1)", arr.hasOwnProperty(1));
Why it matters
Sparse arrays get a different treatment in JavaScript. Namely, array methods that iterate the collection of items will only go through the filled slots and would omit the empty slots. Here is an example:
const sparseArray = []; // empty array
sparseArray[0] = "hello"; // index 0 filled
sparseArray[2] = "world"; // index 2 filled
const arr1 = sparseArray.map(word => word.toUpperCase());
console.log(arr1); //["HELLO", empty, "WORLD"]
const denseArray = []; // empty array
denseArray[0] = "hello"; // index 0 filled
denseArray[1] = undefined; // index 1 filled
denseArray[2] = "world"; // index 2 filled
const arr2 = denseArray.map(word => word.toUpperCase()); //error
console.log(arr2);
As you can see, iterating a sparse array is fine, but if you have an explicit undefined, in the array, then word => word.toUpperCase() will fail because word is undefined.
Sparse arrays are useful if you have numerically indexed data that you want to run .filter, .find, .map, .forEach and so on. Let's illustrate again:
//some collection of records indexed by ID
const people = [];
people[17] = { id: 17, name: "Alice", job: "accountant" , hasPet: true };
people[67] = { id: 67, name: "Bob" , job: "bank teller", hasPet: false };
people[3] = { id: 3 , name: "Carol", job: "clerk" , hasPet: false };
people[31] = { id: 31, name: "Dave" , job: "developer" , hasPet: true };
/* some code that fetches records */
const userChoice = 31;
console.log(people[userChoice]);
/* some code that transforms records */
people
.map(person => `Hi, I am ${person.name} and I am a ${person.job}.`)
.forEach(introduction => console.log(introduction));
/* different code that works with records */
const petOwners = people
.filter(person => person.hasPet)
.map(person => person.name);
console.log("Current pet owners:", petOwners)
its just what it is empty its neither undefined or null
const a = [,,,,] is same as const a = new Array(4)
here a is an array with no elements populated and with only length property
do this, let arr1 = new array() and then console.log(arr1.length) you'll get 0 as output. and if you do console.log(arr1) you'll get [ <4 empty items> ]
if you change the length property of arr1 like this arr1.length = 4 you will have an empty array with it's length property = 4, but no items are populated so those slot will be empty and if you do console.log(typeof(arr1[0]) you get undefined only because there is no other possible types to show. And no methods of Array will be applied with an array with empty elements
so,
Empty array means an array with length property and with unpopulated slots
this is different from arrays with undefined because in JS undefined is a type and you can execute and have results by calling all array methods on it, whereas an array with empty elememts have no type and no array methods can be applied on it.