JavaScript Collections - Iterations and Destructuring
Quick revision/Notes
Iteration
let x = [1, 'b', a => a + 1];
x.length = 6;
for(let i = 0; i<x.length; i++){
console.log(`x: ${x[i]} of type ${typeof(x[i])}`);
}
Output:
in
iteration
The in
keyword skips the undefined entries
//i here takes the index values
for(const i in x){
console.log(`x: ${x[i]} of type ${typeof(x[i])}`);
}
Output:
of
iteration
The of
keyword also skips the undefined entries
//i here takes the element values
for(const i of x){
console.log(`x: ${i} of type ${typeof(i)}`);
}
Output:
Are objects iterable?
No, unless they implement the iterable protocol
Create an array with holes
Spread ...
The spread operator ...
allows an iterable like array or string to be expanded in places where zero or more arguments (in functions) or elements (in arrays) are expected.
let x = [1,3,4];
let y = [0,3, ...x, 5];
console.log(x);
console.log(y);
Output:
Iteration and Transformation
find()
: This method returns the value of the first element in the provided array that satisfies the input condition else it returns undefined
.
filter()
: This method creates a new array with all the elements that pass the given condition it is provided with.
map()
: This method creates a new array populated with the results of calling a provided function on every element in the calling array.
reduce()
: This method executes a user-supplied 'reducer' callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.
The final result of running the reducer across all the elements of the array is a single value.
sort()
: It sorts the elements of the array and returns the sorted array. Default sorting is ascending
Destructuring
let x = [1,2,3,4];
let [a,b] = x;
console.log(x);
console.log(a);
console.log(b);
Object Destructuring
const person = {
firstName: 'Asad',
lastName: 'Sayeed',
age: 21,
city: 'Hyderabad'
};
const {firstName: fn, city: c} = person;
console.log(fn);
console.log(c);
const {lastName, age} = person;
console.log(lastName);
console.log(age);
Here we are destructuring the object and take various keys and put their values in some variables.
Another way to destructure
const {firstName, ...rem} = person;
console.log(firstName);
console.log(rem);
That's it for now folks! Hope you liked it :)