ES6 Features and Syntax


ECMAScript 6, also known as ES6 or ECMAScript 2015, is the latest version of the ECMAScript language specification. It was released in 2015 and introduced many new features and syntax improvements to JavaScript, making it easier to write and maintain complex applications.

In this tutorial, we'll take a look at some of the most important ES6 features and syntax improvements, and how they can make your code more efficient and easier to read.

Let and Const

ES6 introduces two new declarations for variables: let and const. The let declaration is similar to the var declaration, but it has a block scope rather than a function scope. This means that variables declared with let are only accessible within the block in which they are defined.

The const declaration is similar to the let declaration, but it creates a read-only reference to a value. This means that the value of a const variable cannot be reassigned, but it can still be mutable (i.e., the value can be modified).

Syntax

The syntax for declaring a variable with the let keyword in JavaScript is as follows −

let variableName = value;

The syntax for declaring a variable with the const keyword is similar, but with the const keyword instead of let −

const variableName = value;

Example

Here's an example of how let and const can be used −

<html>
<body>
   <p id="demo"></p>
   <p id="demo1"></p>
   <script>
      // Declare a variable with `let`
      let userName = 'John';

      // Use `let` to reassign the value of the variable
      userName = 'Jane';

      document.getElementById("demo").innerHTML = userName;

      // Declare a constant with `const`
      const numStars = 100;

      // Attempting to reassign a constant throws an error
      try {
         numStars = 50;
      } catch (err) {
         document.getElementById("demo1").innerHTML = err;
      }
   </script>
</body>
</html>

This code is a simple HTML page with a script that demonstrates the difference between declaring a variable with let and declaring a constant with const in JavaScript. The script declares a variable userName with let and assigns it the value 'John', then reassigns the value to 'Jane'. It also declares a constant numStars with const and assigns it the value 100, but attempting to reassign the value of numStars throws a TypeError exception because it is a constant. The values of userName and the error message are displayed in the page.

Arrow Functions

ES6 introduces a new syntax for defining functions called arrow functions. Arrow functions are shorter and more concise than traditional function expressions, and they do not have their own value.

Syntax

The basic syntax for an arrow function is as follows −

(parameters) => { statements }

Example

Here's an example of how arrow functions can be used −

<html>
<body>
   <h2>An Arrow Function Example</h2>
   <p id="demo"></p>
   <script>
      const greet = name => `Hello, ${name}!`;
      document.getElementById("demo").innerHTML = greet('John');
   </script>
</body>
</html>

In this example, the script defines an arrow function greet that takes a single argument name and returns a string that greets the person with their name. The function is then called with the argument 'John' and the returned string is displayed in the element with the demo ID.

Enhanced Object Literals

ES6 introduces several enhancements to object literals, making it easier to create and manipulate objects.

One of the most useful enhancements is the ability to use shorthand notation for defining object properties and methods. Instead of using the full name: value syntax, you can use the shorthand name syntax if the property name is the same as the variable name.

Syntax

let property1 = "value1",
   property2 = "value2";
let obj = {
   property1,
   property2,
   [property3]: "value3"
}

Example

Here's an example of how shorthand notation can be used −

<html>
<body>
   <h2>An Enhanced Object Literals Example</h2>
   <p id="demo"></p>
   <script>
      const name = 'John';
      const age = 30;
      const user = {
         name,
         age,
         greet() {
            return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
         }
      };
      document.getElementById("demo").innerHTML = user.greet();
   </script>
</body>
</html>

In this example, the script uses Enhanced Object Literals to define an object user with properties name, age, and a method greet. The name and age properties are declared using the shorthand syntax, which allows the property names to be inferred from the variables with the same names. The greet method uses the value of the name and age properties to return a string that introduces the user. The greet method is then called and the returned string is displayed in the element with the demo ID.

ES6 also introduces the ability to use computed property names in object literals. This allows you to define an object property or method with a dynamic name, using an expression inside square brackets.

Example

Here's an example of how computed property names can be used −

<html>
<head>
   <title>Example</title>
</head>
<body>
   <p id="demo"></p>
   <script>
      let name = 'John';
      let age = 30;

      // using computed property names
      let person = {
         ['first' + 'Name']: name,
         ['age' + (age > 18 ? 'Old' : 'Young')]: age,
         greet() {
               
            document.getElementById("demo").innerHTML= `Hello, my name is ${this.firstName} and I am ${this.ageOld} years old.`
         }
      };
      person.greet(); // logs "Hello, my name is John and I am 30 years old."
   </script>
</body>
</html>

In this example, we use computed property names to define the `firstName` and `ageOld` properties of the `person` object. The `firstName` property is defined by concatenating the strings 'first' and 'Name', and the `ageOld` property is defined by evaluating an expression that determines whether the person is older or younger than 18 years.

Template Literals

ES6 introduces a new syntax for defining strings called template literals. Template literals are enclosed by backticks (```) and can contain placeholders for dynamic values, using the `${expression}` syntax.

Example

Here's an example of how template literals can be used −

<html>
<head>
   <title>Example</title>
</head>
<body>
   <p id="demo"></p>
   <script>
      let name = 'John';
      let age = 30;

      // using computed property names
      let person = {
         ['first' + 'Name']: name,
         ['age' + (age > 18 ? 'Old' : 'Young')]: age,
         greet() {
               
            document.getElementById("demo").innerHTML= `Hello, my name is ${this.firstName} and I am ${this.ageOld} years old.`
         }
      };

      person.greet(); // logs "Hello, my name is John and I am 30 years old."
   </script>
</body>
</html>

In this example, we define a greeting string using traditional string concatenation and then using a template literal. The template literal is shorter and easier to read, and it allows us to interpolate dynamic values directly into the string.

Destructuring

ES6 introduces destructuring, a syntax that allows you to extract values from arrays and objects into variables. This can make it easier to work with data structures and reduce the amount of code needed to access and manipulate values.

Syntax

Here is the syntax for object destructuring −

let [var1, var2, ...rest] = array;

Example

Here's an example of how destructuring can be used with arrays −

<html>
<head>
   <title>Destructuring Example</title>
</head>
<body>
   <p id="output"></p>
   <script>
      let numbers = [1, 2, 3, 4, 5];

      // destructuring
      let [a, b, c] = numbers;

      // use innerHTML to display the values of a, b, and c
      document.getElementById("output").innerHTML = `${a}, ${b}, ${c}`;
   </script>
</body>
</html>

In this example, we extract the first three elements of the `numbers` array into separate variables using destructuring. This is equivalent to using traditional array access, but it is shorter and easier to read.

Example

We can also use destructuring with objects −

<html>
<head>
   <title>Destructuring Example</title>
</head>
<body>
<p id="output"></p>
   <script>
      let person = {
         name: 'John',
         age: 30,
         gender: 'male'
      };

      // destructuring
      let { name, age, gender } = person;
      document.getElementById("output").innerHTML = `${name}, ${age}, ${gender}`;
   </script>
</body>
</html>

In this example, we extract the properties of the `person` object into separate variables using destructuring. This is equivalent to using traditional object access, but it is shorter and easier to read.

Rest and Spread Operators

ES6 introduces the rest operator (`...`) and the spread operator (`...`), which allow you to work with arrays and objects in a more flexible way.

The rest operator is used to capture multiple values into an array, and the spread operator is used to expand an array or object into separate values.

Example

Here's an example of how the rest operator can be used −

<html>
<head>
   <title>Rest Operator Example</title>
</head>
<body>
   <p id="output"></p>
   <script>
      function sum(...numbers) {
         let result = 0;
         for (let number of numbers) {
            result += number;
         }
         return result;
      }
      let res=sum(1, 2, 3, 4, 5)
      document.getElementById("output").innerHTML=res;// logs 15
   </script>
</body>
</html>

In this example, we define a `sum` function that uses the rest operator to capture multiple arguments into an array called `numbers`. We then use a for-of loop to iterate over the `numbers` array and compute the sum of all the elements.

Example

Here's an example of how the spread operator can be used −

<html>
<head>
   <title>Spread Operator Example</title>
</head>
<body>
   <p id="output"></p>
   <p id="output1"></p>
   <p id="output2"></p>
   <script>
      let numbers = [1, 2, 3];
      let numbers2 = [4, 5, 6];

      // using the spread operator to concatenate arrays
      let allNumbers = [...numbers, ...numbers2];
      document.getElementById("output").innerHTML=allNumbers;
       

      // using the spread operator to clone an array
      let numbers3 = [...numbers];

      document.getElementById("output1").innerHTML=numbers3;

      // using the spread operator to expand an array into function arguments
      let maxNum=Math.max(...numbers); // logs 3
      document.getElementById("output2").innerHTML=maxNum;
   </script>
</body>
</html>

In this example, we use the spread operator to concatenate two arrays, clone an array, and expand an array into function arguments. The spread operator makes it easier to work with arrays and eliminates the need for manual iteration and concatenation.

Conclusion

ES6 introduces many new features and syntax improvements that make it easier to write and maintain complex JavaScript applications. Some of the most important features include `let` and `const` declarations, arrow functions, enhanced object literals, template literals, destructuring, and the rest and spread operators.

By using these features, you can write more concise and readable code, and take advantage of the latest language features to build more powerful and scalable applications.

Updated on: 19-Jan-2023

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements