JavaScript Arrays
Data Types: Arrays
An object is a keyed collection of values. What is an array in JavaScript?
View Answer:
let fruits = ['Apple', 'Orange', 'Plum'];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Orange
console.log(fruits[2]); // Plum
What type of elements can you store in an array?
View Answer:
// Storing integers
let intArray = [1, 2, 3, 4, 5];
// Storing strings
let strArray = ['hello', 'world'];
// Storing objects (like other arrays)
let objectArray = [[1, 2], [3, 4]];
What are the two syntaxes used to create an empty array in JavaScript?
View Answer:
let arr = new Array();
let arr = [];
How do you get the length of an array in JavaScript?
View Answer:
let fruits = ['Apple', 'Orange', 'Plum'];
console.log(fruits.length); // 3
What is the benefit of using a trailing comma in an array?
View Answer:
Without a trailing comma:
let arr = [
'item1',
'item2',
'item3' // No trailing comma here
];
If you want to add 'item4' to this array, you need to add a comma to the end of 'item3' and then add 'item4'. This changes two lines:
let arr = [
'item1',
'item2',
'item3', // Line changed to add comma
'item4' // New line added
];
With a trailing comma:
let arr = [
'item1',
'item2',
'item3', // Trailing comma here
];
Now, if you want to add 'item4', you only need to add the new line:
let arr = [
'item1',
'item2',
'item3',
'item4', // New line added, no previous line changed
];
In version control systems like Git, this will be shown as a single line added, rather than one line modified and one line added. This can make changes clearer and easier to review.
In JavaScript, what are the two data structures that arrays can mimic?
View Answer:
Stack:
let stack = [];
stack.push("a"); // ["a"]
stack.push("b"); // ["a", "b"]
stack.pop(); // ["a"]
Queue:
let queue = [];
queue.push("a"); // ["a"]
queue.push("b"); // ["a", "b"]
queue.shift(); // ["b"]
Can you explain the function and syntax of the array pop() method?
View Answer:
Syntax: arr.pop()
let fruits = ['Apple', 'Orange', 'Pear'];
console.log(fruits.pop()); // remove "Pear" and console.log it
console.log(fruits); // Apple, Orange
// Works with array like objects (required: length property)
var myFish = {
0: 'angel',
1: 'clown',
2: 'mandarin',
3: 'sturgeon',
length: 4,
};
var popped = Array.prototype.pop.call(myFish); //same syntax for using apply( )
console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3}
console.log(popped); // 'sturgeon'
Can you explain the function of the array push() method?
View Answer:
Syntax: arr.push(element1, element2)
// Pushing a single element
let fruits = ['Apple', 'Orange'];
fruits.push('Pear');
console.log(fruits); // Apple, Orange, Pear
// Pushing multiple elements
let sports = ['soccer', 'baseball'];
let total = sports.push('football', 'swimming');
console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4
Can you explain the function of the array shift() method?
View Answer:
Syntax: arr.shift()
let fruits = ['Apple', 'Orange', 'Pear'];
console.log(fruits.shift()); // remove Apple and console.log it
console.log(fruits); // Orange, Pear
How does the array unshift() method work?
View Answer:
Syntax: arr.unshift(element1[, ...[, elementN]])
let arr = [4, 5, 6];
arr.unshift(1, 2, 3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]
arr = [4, 5, 6]; // resetting the array
arr.unshift(1);
arr.unshift(2);
arr.unshift(3);
console.log(arr);
// [3, 2, 1, 4, 5, 6]
Why is an array a special kind of object?
View Answer:
// Array Like Object
let fruits = {
0: 'Apple',
1: 'Pear',
2: 'Banana',
length: 3,
};
// Array
let fruits2 = ['Apple', 'Pear', 'Banana'];
console.log(fruits[0]); // array-like object returns Apple
console.log(fruits2[0]); // array returns Apple
console.log(fruits.length); // length returns 3
let arrFruits = Array.from(fruits); // converts array-like object to an array
console.log(arrFruits.length); // length returns 3
console.log(arrFruits.pop()); // removes Banana
console.log(arrFruits.length); // length returns 2
What happens when you try to utilize an Array in JavaScript as an Object?
View Answer:
Examples: Misusing an array.
- Add a non-numeric property like arr.test = 5.
- Make holes, like add arr[0] and then arr[1000] (and nothing between them).
- Fill the array in the reverse order, like arr[1000], and arr[999].
Why is it faster to work with the end of an array than with its beginning?
View Answer:
Examples: The shift operation must do 3 things.
- Remove the element with the index 0.
- Move all elements to the left, renumber them in the index 1 to 0, from 2 to 1, and on to completion.
- Update the length property.
What are the three common ways to loop over an array?
View Answer:
// 1. for loop:
let arr = ['a', 'b', 'c'];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// 2. forEach() method:
let arr = ['a', 'b', 'c'];
arr.forEach(function(element) {
console.log(element);
});
// 3. for...of loop:
let arr = ['a', 'b', 'c'];
for (let element of arr) {
console.log(element);
}
Can you explain some of the drawbacks of using a for…in loop on arrays?
View Answer:
Examples:
- The for..in loop iterates across all attributes, not just the numerical ones. In the browser and other contexts, there exist so-called "array-like" objects that resemble arrays. They have length and index features, but they may also include non-numeric attributes and techniques that we do not typically require. The for..in loop, on the other hand, displays a list of them. As a result, if we need to deal with array-like objects, these "extra" properties may cause problems.
- The for..in loop gets optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it is still speedy, and the speed may only matter in bottlenecks. But still, we should be aware of the difference.
Can you explain the limitations related to the array length property?
View Answer:
var animals = ['cat', 'dog', , 'monkey']; // animals is sparse
// prints 4, but real number of elements is 3
console.log(animals.length);
var words = ['hello'];
//the highest index is 6
words[6] = 'welcome';
//prints 7, based on highest index
console.log(words.length);
var colors = ['blue', 'red', 'yellow', 'white', 'black'];
// prints 5
console.log(colors.length);
// remove the first element 'blue'.
// The array becomes sparse
delete colors[0];
// still prints 5, because the highest index 4 was not modified
console.log(colors.length);
A less common issue is array mutation when an element gets deleted from an array. The length is not updated with the new number of elements and returns the highest index.
What's the significant difference between an Array and an array literal?
View Answer:
let arr = new Array(3); // will it create an array of [3] ?
console.log(arr[0]); // returns undefined! no elements.
console.log(arr.length); // length 3
What's the drawback of using the Array constructor?
View Answer:
// Jere's a JavaScript example to demonstrate the potential confusion with the Array constructor:
let arr1 = new Array(5); // Creates an array of length 5, not containing the number 5
console.log(arr1); // Logs: [ <5 empty items> ]
let arr2 = [5]; // Creates an array containing the number 5
console.log(arr2); // Logs: [ 5 ]
let arr3 = new Array(5, 1); // Creates an array containing the numbers 5 and 1
console.log(arr3); // Logs: [ 5, 1 ]
Are there any rules governing the equality comparison of two Arrays?
View Answer:
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
let arr3 = arr1;
console.log(arr1 == arr2); // Logs: false, because arr1 and arr2 are different objects
console.log(arr1 === arr2); // Logs: false, for the same reason
console.log(arr1 == arr3); // Logs: true, because arr1 and arr3 are the same object
console.log(arr1 === arr3); // Logs: true, for the same reason
What kind of issues can we run into when comparing an Array literal to zero?
View Answer:
console.log([] == 0); // Logs: true
// Here's why:
// 1. The array literal [] is converted to a string.
// 2. An empty array converted to a string gives an empty string "".
// 3. An empty string "" is then coerced to a number for the comparison with 0, which gives 0.
// 4. Hence, [] == 0 turns into "" == 0, then into 0 == 0, which is true.
When should you use a for...of loop instead of a for loop with arrays?
View Answer:
Sure, here are JavaScript examples illustrating the difference:
for...of
loop (when you only care about values):
let arr = ['a', 'b', 'c'];
for (let value of arr) {
console.log(value); // Logs: 'a', 'b', 'c'
}
for
loop (when you need to access or manipulate the index):
let arr = ['a', 'b', 'c'];
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]); // Logs: '0 a', '1 b', '2 c'
}
In the for...of
example, we simply iterate over the values in the array. In the for
loop example, we have access to each index (i
), and we can do something with it if needed.