//Breaks up the supplied array into arrays of the specified size and return it.
chunk(array,size=1){
let arrayChunks = [];
for(let i=0;i<array.length;i+=size){
let arrayChunk = array.slice(i,i+size);
arrayChunks.push(arrayChunk);
}
console.log(arrayChunks[1].length);
return arrayChunks;
}
When I test this code, some cases make me confused about undefined
.
For example,
//case 1:
let arr = [1,2,3,4,5];
let chunkArr = chunk(arr,3); // [[1, 2, 3], [4, 5]]
console.log(chunkArr[1][2]); //undefined.
console.log(chunkArr[1].length); //2
//case 2:
let arr= [1,2,3,4,5];
arr[4] = undefined;
console.log(arr.length); //5
arr[5] = undefined;
console.log(arr.length, arr[6]); //6, undefined
Q1.
I learned that variables that have not been initialized store the primitive data type undefined
. So console.log(chunkArr[1][2]);
prints undefined
. But why chunk(arr,3)
returns [[1, 2, 3], [4, 5]] instead of [[1, 2, 3], [4, 5, undefined]]?
Q2.
In case 2: JS engine counts arr[5] that has undefined
value. But arr[6] isn’t counted length of an array even though it has ‘undefined’ too. What is difference? How the engine distinguish that?
Practice JavaScript Syntax: Arrays, Loops, Objects, Iterators | Codecademy