Write Less and Achieve More with JavaScript ES6

492 VIEWS

JavaScript ES6, also known as EcamScript2015, has made JavaScript easier to work with and more intuitive. ES6 is a major update to JavaScript with features that focus on simplicity and readability. This article will present the major features of ES6 that allow users to construct better and cleaner code.

const and let

Before ES6, blocks served no function to variables as all variables were defined globally, or locally to a function, using the var keyword. However, const and let provide a means to declare and assign variables within the scope of a block and not to a function.

const is a new keyword in ES6 used to declare variables. The const keyword is more powerful than var because once declared, the variable cannot be reassigned a value. Hence the variable becomes immutable. Note that the value remains mutable, especially when the value is an object.

Use const when you have no intention of reassigning new values to the variable. For example, it’s highly recommended to use const in targeting selectors.

const heading = document.getElementById( 'heading1')

Using the code above, if you try to reassign it a new value, an error will be returned.

letis also a new way to declare variables that are block scoped. The let keyword can be reassigned and can take a new value, hence it declares a mutable variable.

ES5 Syntax

 
function scope(){
      var a = "Happy";
      {
        var a = "Sad";
      }
      {
        var a = 350;
      }
      return a;
}
console.log(scope());
 

The output of the code above would be 350 because the scope of a variable declared with var is either the enclosing function or, if declared outside a function, global. In this case, it’s the enclosing function.

ES6 Syntax

 
function scope(){
      let a = "Happy";
      {
        let a = "Sad";
      }
      {
        let a = 350;
      }
      return a;
}
console.log (scope());
 

The output of this code above would be ‘Happy’ because a variable declared with let is limited to a scope of a block. Since the first variable declared and the return statement are in the same block, that variable will be returned.

Arrow functions

An arrow function expression is an alternative way to write a function expression, making code more readable and structured.

ES5 Syntax

function myIdentity(name){
    return 'Hi ' + name + ', welcome';
}
console.log(myIdentity( 'Frederick'));
 

The output of the code above is :
Hi Frederick, welcome

ES6 Syntax

const myIdentity = name => 'Hi '+name + ', welcome';
console.log(myIdentity('Frederick'))
 

The output of the code above is :
Hi Frederick, welcome

As seen from the example above, both the ES5 and ES6 code produced the same result; however, with ES6, fewer lines of code were used. With ES6 Arrow function, keywords such as function, return, curly brackets {} and parenthesis () can be avoided in particular cases.

Multi-line Strings

When working with bulky text, multi-line strings are a nice convenience. With ES6, multi-line strings can be achieved by encapsulating the whole thing between backticks.

ES5 Syntax

 
 var x = 'This string \n'
 + 'is not a multi-line string \n'
console.log(x)
 

ES6 Syntax

var y = `this string,
            a multi-line string.
            I can have as many
            lines `
console.log(y)
 

Notice there’s no need for the newline character, nor any string concatenation.

Template Literals

Template literals do not require the use of plus (+) operator to concatenate strings, or when using a variable inside a string. Template literals allow you to plug variables into strings. Before ES6, string concatenation was used to achieve the same result.

Template literals are a new syntax to create strings, as they provide a means to embed expressions into strings through using the ${variable} syntax.

ES5 Syntax


function functionName (name,country){
return 'Hi, my name is ' + name + ', and I am from ' + country;
}
console.log(functionName('Frederick', 'Ghana'));

The output for the code is :
Hi, my name is Frederick, and I am from Ghana

ES6 Syntax

const code= (name,country) =>{
    return `Hi, my name is ${name}, and I am from ${country}`;
  }
  console.log(code('Frederick', 'Ghana'))
 

The output for the code is :
Hi, my name is Frederick, and I am from Ghana

Default parameters

Default parameters allow you to define a parameter in advance. Before ES6, default values needed to be defined; if not, the function will return undefined.

ES5 Syntax

function name( name, gender){
  	return 'My name is '+ name + ' and I am '+ gender
}
console.log(name('James'))
 

The code above returns undefined since the parameter gender was not defined.

ES6 Syntax

const name= ( name, gender= 'male') =>{
  	return `My name is ${name} and I am ${gender} `
} 
console.log(name('Frederick'))

The code above returns:
My name is Frederick and I am male.

Even though the gender argument was omitted, the code returns a value because the default parameter was defined.

Improved Object Literals

Before ES6, variables had to be restated in order to associate them with properties of an object. With ES6, the value of the object is associated with the variable name automatically.

ES5 Syntax

function showRecords ( name, age, sex){
      return {
        name: name,
        age: age,
        sex: sex
      }
 }
 console.log(showRecords('Frederick', 23, 'Male'));
 

ES6 Syntax

function showRecords ( name, age, sex){
      return {
        name,
        age,
        sex
      }
 }
console.log(showRecords('Frederick', 23, 'Male'));
 

Object Destructing

The destructuring assignment syntax is an expression used to assign properties from an object into distinct variables.

ES5 Syntax

 
var person = {
	name:'Fred',
	age: 20,
	country: 'ghana'
  }
 
  var personName = person.name;
  var personAge = person.age;
  var personCountry = person.country;
 
  console.log(personName + ' ' + personAge + ' ' + personCountry)
 

ES6 Syntax

 
const person = {
	name:'Fred',
	age: 20,
	country: 'ghana'
  }
 
//Example 1
  let{name, age, country} = person;
  console.log(name + ' ' + age + ' ' + country)
 
//Example 2
  let{name:personName, age:personAge, country:personCountry} = person;
  console.log(personName + ' ' + personAge + ' ' + personCountry)
 

With ES6, all it takes is a single line. Just put the values within curly brackets and assign them to the object to obtain the properties of the object.

In the case where you want to use different variable names, you may use a colon (:) as is used in the second example of the ES6 syntax.

Conclusion

I hope you found this article useful, and I hope now that you’ve been introduced to some of the key features, you’ll be able to make use of them in your coding.


Frederick Plange is a computer science major at Ashesi University, one of the top universities in Ghana aiming to develop ethical and entrepreneurial leaders to transform the nation. Frederick is a focused and goal driven individual that is passionate about technology and computers


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu