Thursday, December 22, 2016

JavaScript Evolution ECMAScript 6 - New Additional to Array

Assigning From Array to Local Variables

Typically we access array elements using index.
let users = ["Sam", "Tyler", "Brook"];
let a = users[0];
let b = users[1];
let c = users[2];
In ES2015, new implement in Array destructuring allows us to write less code.
let users = ["Sam", "Tyler", "Brook"];
let [a, b, c] = users;
If there is any value that not interested in, we can discard.
let users = ["Sam", "Tyler", "Brook"];
let [a, ,b] = users;
We can combine destructuring with rest parameters to group values into other Array.
let users = ["Sam", "Tyler", "Brook"];
let [first, ...rest] = users;
console.log(first); // Return "Sam".
console.log(rest); // Return a new Array ["Tyler", "Brook"]

Using for...of to loop over Array

The for...of statement iterates over property values, and it's a better way to loop over arrays and other iterate objects.

Here is the typical way we loop thru array using index.
let names = ["Sam", "Tyler", "Brook"];
for (let index in names) {
  console.log (names[index]);
}
Now, using for...of, we don't use the index.
let names = ["Sam", "Tyler", "Brook"];
for (let name of names) {
  console.log(name);
}

Finding an Element in an Array

Array find returns the first element in the Array that satisfies a provided testing function.
let users = [
  {login: "Sam", admin: false},
  {login: "Brook", admin: true},
  {login: "Tyler", admin: true}
];
let admin = users.find( (user) => {
  return user.admin;
});
console.log(admin); // Return {login: "Brook", admin: true}

No comments:

Post a Comment