Do you know ES6 - Part 2
Mohamed Khaled Yousef
Posted on March 31, 2019
Before you start reading this part, We have discussed some of ES6 features here
As we discussed before, ES6 is JS.
ES6 is about the next generation of Javascript. In general, ES6 allows us to write clean and robust react apps and this help us to do more powerful things.
Content:
- Array functions
- Template literals
- Object literals
- For Of
Array functions
There are a lot of functions we can do on array, Such as map, concat, join, splice and there are many of these methods. All these methods aren't ES6 but normal js.
map is built-in array method that return a real new array.
const numbers = [1,2,3];
const doubleNumbers = numbers.map((num) => {
return num*2;
});
console.log(numbers); //[1, 2, 3]
console.log(doubleNumbers); //[2, 4, 6]
concat is a method that joins two or more arrays and returns a new array with the values of the joined arrays
const myName = ["Mohamed", "Khaled"];
const myInfo1 = ["Computer", "Science", "Student"];
const myInfo2 = ["Front End Developer"];
const concatTwoArray = (arr1,arr2,arr3) => arr1.concat(arr2,arr3);
console.log(concatTwoArray(myName,myInfo1,myInfo2));
join is a method that joins the elements of an array into a string and returns the final string.
The final string will be separated by a specified separator such as the default separator which is comma (,), bar (|), dash (-), space or whatever separator.
let fruits = ["Mohamed", "Khaled", "Yousef", "Mohamed", "Ali"];
let energy1 = fruits.join();
let energy2 = fruits.join(" ");
let energy3 = fruits.join("|");
let energy4 = fruits.join(" and ");
console.log(energy1, energy2, energy3, energy4);
splice method is that adds elements to an array and removes elements from an array, and returns the final element.
In the next example, We remove one element from index 2 (Third element). Then we remove 3 elements from index and add 2 elements [Computer and Science]
let names = ["Mohamed", "Khaled", "Yousef", "Mohamed", "Ali"];
names.splice(2, 1);
console.log(names);
names.splice(2, 3, "Computer", "Science");
console.log(names);
Template literals
Before we define what is Template literals lets remember that in normal JS to concatenate strings together, It was by using the string concatenation operator ( + ). Also you can use the string's concat() method.
const my_name = 'Mohamed';
const message0 = 'My name is ' + my_name;
console.log(message0);
In fact it isn't good practice to use + operator to concatenate strings because it gets more complicated when you need to build multi-line strings.
const fstName1 = 'Mohamed', lastName1 = 'Khaled';
const message1 = 'My name is ' + fstName1 + '.\n\n' + 'My last name is ' + lastName1;
console.log(message1);
So Template Literals solve the multi-line strings problem.
Template literals are string literals that include embedded expressions.
Denoted with backticks () instead of single quotes ('') or double quotes (""). Template literals can contain placeholders which are represented using ${expression}. This makes it much easier to build strings.
By using template literals, you can drop the quotes along with the string concatenation operator. In general, Template Literals is used for easier string interpolation.
const my_Name = 'Mohamed';
const message1 = `My name is ${my_Name}`;
console.log(message1);
Also, you can reference the object's properties inside expressions.
const myName = {
name: 'Mohamed',
age: 23
};
const myFather = {
name: 'Khaled'
}
let message2 = 'My name is ' + myName.name + '. I am ' + myName.age + ' years old' + ' and my father name is ' + myFather.name;
console.log(message2);
let message3 = `My name is ${myName.name}. I am ${myName.age} years old and my father name is ${myFather.name}`;
console.log(message3);
What about the multi-line example from before?
const fstName = 'Mohamed', lastName = 'Khaled';
const message0 = `My name is ${fstName},
My last name is ${lastName}`;
console.log(message0);
Destructuring Arrays and Template Literals
Cool, I think you remember the Destructuring Arrays from Part 1 .
Here I print my name in one line and multi-line
const names = ['Ahmed', 'Mohamed', 'Ali', 'Sarah', 'Khaled', 'John', 'Adel', 'Yousef'];
const [,First, , ,Second, , , Third] = names;
let myName = `My name is ${First} ${Second} ${Third}`;
console.log(myName);
myName = `My name is
1. ${First}
2. ${Second}
3. ${Third}`;
console.log(myName);
Object literals shorthand
One of ES6 features is to remove repetition to makes the syntax easier to read and more concise.
For example, when we write an object and assign the property names as the variable names such as first: first, second: second.
//Normal JS Object
let first = 'Mohamed';
let second = 'Khaled';
let third = 'Yousef';
const myName = {
first: first,
second: second,
third: third
};
console.log(myName);
Object literal shorthand for initializing properties
In fact we don't need this repetition so we can remove the duplicate variables names from object properties
let first = 'Mohamed';
let second = 'Khaled';
let third = 'Yousef';
const myName = {
first,
second,
third
};
console.log(myName);
The same in normal JS when we create methods in the object
In the next example, We create an anonymous function in our object and assigned it to the property writeMyName and the same with mul function
let first = 'Mohamed';
let second = 'Khaled';
let third = 'Yousef';
let fs = 5, sec = 7;
const myName = {
first: first,
second: second,
third: third,
fs: fs,
sec: sec,
writeMyName: function(x,y,z) {
return first.concat(second,third);
},
mul: function(a,b) {
return fs*sec;
}
};
console.log(myName.writeMyName());
console.log(myName.mul());
Object literal shorthand for writing methods
In ES6, We don't need to the function keyword to define a method
let first = 'Mohamed';
let second = 'Khaled';
let third = 'Yousef';
let fs = 5, sec = 7;
const myName = {
first: first,
second: second,
third: third,
fs: fs,
sec: sec,
writeMyName(x,y,z) {
return first.concat(second,third);
},
mul(a,b) {
return fs*sec;
}
};
console.log(myName.writeMyName());
console.log(myName.mul());
The for...of loop
The for...of loop is one of looping types that used to iterate
Types of for loops such as for loop, the for..in loop, forEach loop and for..of loop.
Lets remind all loop types:
The for loop
The problem is that JS has to look up the length of the array on every iteration. This means Js has to keep counting the length of the array and the exit condition.
In this example, we’re using the variable i as a counter to keep track of the loop and to access values in the array. We’re also using numbers.length to determine the exit condition for the loop.
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
The for...in loop
The for...in loop improves upon the problem of the for loop by eliminating the counting logic and exit condition.
But, you still have to deal with the issue of using an index to access the values of the array.
const numbers = [1, 2, 3, 4, 5];
for (const index in numbers) {
console.log(numbers[index]);
}
The forEach
Is actually an array method, so it can only be used exclusively with arrays.
const numbers = ['One', 'Two', 'Three', 'Four'];
numbers.forEach(function(num) {
console.log(num);
});
const doubleNumbers = [1, 2, 3, 4];
doubleNumbers.forEach((num) => { console.log(num*2); });
The For...of loop
Now, What about the For...of Loop
For...of Loop is the most concise version of all the for loops because its used to loop over any type of data that is iterable objects.
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
console.log(num);
}
Also, You can stop or break a for..of loop at anytime.
In the next example, We print even numbers
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of numbers) {
if (num % 2 === 1) {
continue;
}
console.log(num);
}
Finally, lets use for...of loop that loops through each day in the days array
and capitalizes the first letter of the day
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
const capitalize = st => st.charAt(0).toUpperCase().concat(st.slice(1));
for (const day of days) {
console.log(capitalize(day));
}
Finally … Here is the repo, You can find all source code.
Posted on March 31, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.