DEV Community

loading...

Es6 Awesomeness (Part I)

ogwurujohnson profile image Johnson Ogwuru ・4 min read

The sixth edition of ECMAScript standards, known as Es6 adds significant new syntax for writing complex applications, including classes and modules. Some of this new syntax and concepts we would discuss in a 3 part documentation of my learning, making them as possibly simple as i can.

For this part, we would be looking at the following concepts and syntax:

  1. Template Strings
  2. Let & Constants
  3. For..of
  4. Arrow Functions
  5. Spread Operator

1. Template Strings:
Es6 has two new kinds of literals: template literals and tagged template literals. The template literal allows to use multiple line strings and expressions.
`
Template literals
are enclosed by the back-tick instead of the double or single quotes and expressions can be indicated by the dollar sign and curly braces ${..}. Below are example of template literals at work;

const firstname = 'johnson';
console.log(`Hello ${firstname},
How are you?`);
Enter fullscreen mode Exit fullscreen mode

The above code is equivalent to the below Es5 standard code;

var firstname = "Johnson";
console.log('Hello '+firstname+', \n How are you?');
Enter fullscreen mode Exit fullscreen mode

Comparing the two codes snippets we have to agree that Es6 simplified a lot for us. Below is another example showing Es6 template literal in action.

const  currentYear = 2018;  
let DOB = 1980;

console.log(`Subtracting your DOB ${DOB} from the current year, 
your are ${currentYear-DOB}years old`);
Enter fullscreen mode Exit fullscreen mode

Tagged Template Literals;

let a = 1;
let b = 2;

let yourString = function(strArray, ...val){
    console.log(strArray);
    console.log(val);
}

yourString `Hello ${a},${b} world man ${a+b}`;
Enter fullscreen mode Exit fullscreen mode

Tagged Template Literal, is a more advanced form of template literals. With them you are able to modify the output of template literals using a function. The first argument contains an array of string literals ("Hello","world","man" and "" in the above example). The second and each argument after the first one, are the values of the processed (or sometimes called cooked) substitution expressions("1","2","3") in the end your function returns your manipulated string.

Some other string functions in Es6 are, include,startsWith,endsWith, i would explain them just with examples of how they are used, so you could personally copy and run them on your console.

var stringWord = "Hello World";
stringWord.startsWith("Hell");

var stringWord = "Hello world";
stringWord.endsWith("rld");
Enter fullscreen mode Exit fullscreen mode

Running the above different codes return the Boolean value true.

var anyArray = [1,2,4];
anyArray.includes(1);
Enter fullscreen mode Exit fullscreen mode

2. Let & Constants:

Let:
The let statement declares a block scope local variable and not function level scope like var.

let year = 2018;
let dob = 1970;


function calcAge(){
    let age = year-dob;
    if (age > 19){
        let age = "You re young";
        console.log(age);
    }
    console.log(age);
}

calcAge();
Enter fullscreen mode Exit fullscreen mode

Redeclaring the same variable within a the same function or block scope raises a SyntaxError, and also you can not use a variable outside of its scope; like say trying to access age outside of the calcAge function would return an undeclared variable Error.

Constants:

const works like let, but the variable you declare must be immediately initialized, with a value that can't be changed afterwards. The const declaration creates a read-only reference to a value. Remember the value of a constant cannot change through re-assignment, and it cant be re-declared.

Having const PI = 3.14 trying to reassign PI, say PI = 3.12 would return an uncaught type error. Just like let, const cant be accessed outside of its scope, lets take an example to illustrate this and please try to run this code yourself to understand better.

   const PI = 3.14;
   function fun(){
        const PI = 3.121;
        if(true){
            const PI = 3.416;
            console.log(PI)
        }
        console.log(PI);
    }
    console.log(PI);
    fun();
Enter fullscreen mode Exit fullscreen mode

3. For..of:
for-of is a new loop in Es6 that replaces both for-in and forEach() and supports the new iteration protocol.The syntax is highlighted below;

for(variable of iterable){
    statement
}
Enter fullscreen mode Exit fullscreen mode

Iterating over an Array;

let values = [1,34,20];
for (let value of values){
    console.log(value);
}
Enter fullscreen mode Exit fullscreen mode

Iterating over a string;

let color = "red";
for(let item of color){
    console.log(item);
}
Enter fullscreen mode Exit fullscreen mode

4. Arrow Function:

Arrow functions are always anonymous. The examples are below:

Function without any parameters:

var intro = () => "Welcome";
Enter fullscreen mode Exit fullscreen mode

The above code is equivalent of the below:

var intro = function(){
    return "welcome";
}
Enter fullscreen mode Exit fullscreen mode

Function with 1 parameter:

var multiplyBy2 = value1 => value1 * 2;
console.log(multiplyBy2(4));
Enter fullscreen mode Exit fullscreen mode

The above code is equivalent of the below:

var multiplyBy2 = function(value1){
    return value1 * 2;
}
console.log(multiplyBy2(4));
Enter fullscreen mode Exit fullscreen mode

Function with more than 1 parameter:

var addBy = (value1,value2) => value1 + value2;
console.log(addBy(10,30));
Enter fullscreen mode Exit fullscreen mode

5. Spread operator:
The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple variables (for destructuring assignments) are expected.

Example:
Common usage of array as arguments to a function is as below:

function myFunctions(x,y,z){
    console.log(x);
    console.log(y);
    console.log(z);
}
var args = [0,1,2];
myFunctions(args);
Enter fullscreen mode Exit fullscreen mode

With Es6 spread you can now write the above as:

function myFunctions(x,y,z){
    console.log(x);
    console.log(y);
    console.log(z);
}

myFunctions(...args);
Enter fullscreen mode Exit fullscreen mode

This is it for today guys.

Discussion (5)

Collapse
tensaga profile image
TENsaga • Edited

Is there another method for iterating over keys/values up the prototype chain? Property c is added to the prototype after initiating and is accessible on o with for...in:

Carbon

Collapse
ashinzekene profile image
Ashinze Ekene

I doubt there is

Collapse
ogwurujohnson profile image
Johnson Ogwuru Author • Edited

sincerely i don't think or lemme say i don't know if there is. But i would research about it, if there is. I would update this reply here with which method.

Collapse
rhartzell profile image
Rod Hartzell

Outstanding. Thank you sir.

Collapse
ogwurujohnson profile image
Johnson Ogwuru Author

Happy you enjoyed it.

Forem Open with the Forem app