DEV Community

wekesamuel
wekesamuel

Posted on • Originally published at samuelweke.hashnode.dev on

Upgrade Your JavaScript Skills with These Essential ES6 Syntax

Upgrade Your JavaScript Skills with These Essential ES6 Syntax Techniques!

The 2015 revision of ECMAScript, commonly called ES6, is one of the most important updates for the JavaScript language. This update introduced new features that made JS coding more efficient and readable. Although there are a few debatable features in ES6, most of them are worth acquainting yourself with.

Here are the top ES6 syntaxes you should know about.

Arrow Function

Arrow functions in ES6 are a significant improvement from the previous syntax. Not only do they allow you to create anonymous functions easily, but they also provide a more concise syntax.

For example:

const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
Enter fullscreen mode Exit fullscreen mode

In this example, the arrow function defines the function “add,” which takes two parameters and returns their values. The syntax in this code is shorter compared to ES5, which would look like this:

var add = function(a, b) {
  return a + b;
};

console.log(add(2, 3)); // Outputs: 5
Enter fullscreen mode Exit fullscreen mode

It is essential to note that arrow functions do not have their own “this” since they bind to the “this” of the parent context. This ES6 revision helps avoid serious bugs that used to occur with the traditional function syntax. The next code illustrates this feature:

const person = {
  name: John,
  sayName: function() {
    setTimeout(() => {
      console.log(this.name);
    }, 1000);
  }
};
person.sayName(); // Output: John
Enter fullscreen mode Exit fullscreen mode

Here, the arrow function is used as a callback function for the setTimeout method. Since arrow functions automatically bind to the this keyword of their parent context, you can access the name property of the person object inside the arrow function.

Let and Const

let and const are updated ways of declaring variables, making var obsolete in this work.

Let

let is used in declaring or initializing block-scoped variables, meaning they can only be accessed within their specific block. This contrasts the var keyword, whose variables were function-scoped, leading to variable hoisting. An example of let declared block-scope variable is as follows:

function example() {
  let x = 1;

  if (true) {
    let x = 2;
    console.log(x); // Output: 2
  }

  console.log(x); // Output: 1
}
Enter fullscreen mode Exit fullscreen mode

We are using the let keyword to declare a block-scoped variable x. When we enter the if block, we declare a new block-scoped variable x with a value of 2. If we log the value of x inside the if block, we get 2. Conversely, when we log the value of x outside the if block, we get 1, the value of the outer block-scoped variable x.

The above code would look like this if it were declared using var instead of let:

function example() {
  var x = 1;

  if (true) {
    var x = 2;
    console.log(x); // Output: 2
  }

  console.log(x); // Output: 2
}
Enter fullscreen mode Exit fullscreen mode

Since var in this code has function scope, the inner x variable in the if block would override the outer x variable. Consequently, both console.log statements would output 2 rather than 2 and 1 as they do in the previous example. This issue can lead to bugs and unexpected behaviour, which is why let and const were introduced in ES6 to provide more predictable scoping rules.

Const

const has relatively the same function as let, but it declares a constant variable that cannot be reassigned. This feature can be helpful in declaring values that should not be changed, such as constants or configuration values.
For example:

const PI = 3.14159;
Enter fullscreen mode Exit fullscreen mode

Since PI is declared as a constant variable, it cannot be reassigned to a new value.

Destructuring Assignment

Destructuring assignment is an ES6 syntax that allows the extraction of values from arrays or objects and assigning them to variables in a single statement. This technique is crucial since it can simplify code significantly.
For example, consider the following code written in a traditional way:

const numbers = [1, 2, 3, 4];

const a = numbers[0];
const b = numbers[1];
const c = numbers[2];
const d = numbers[3];

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
console.log(d); // Output: 4
Enter fullscreen mode Exit fullscreen mode

With a destructuring assignment, the above code looks like this:

const numbers = [1, 2, 3, 4];

const [a, b, c, d] = numbers;

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
console.log(d); // Output: 4
Enter fullscreen mode Exit fullscreen mode

As you can see, without destructuring assignment, you must manually assign each value to a separate variable using array index notation, which can be highly problematic when working with larger arrays or more complex data structures. Using destructuring assignment to extract the values from the numbers array and assign them to variables a, b, c, and d results in a more concise and readable code.

Template Literals

Template literals allow you to embed expressions inside a string, making creating dynamic and complex strings easier. They can be handy when working with dynamic content, such as building SQL queries. Moreover, they can help simplify code by reducing the need for complex string concatenation. For example:

const firstName = 'Sam';
const lastName = 'Walter';
const age = 30;


// Without template literals
const greeting = 'Hello, my name is ' + firstName + ' ' + lastName + ' and I am ' + age + ' years old.';

// With template literals
const greeting2 = `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`;

console.log(greeting); // Output: “Hello, my name is Sam Walter and I am 30 years old.”
console.log(greeting2); // Output: “Hello, my name is Sam Walter and I am 30 years old.”
Enter fullscreen mode Exit fullscreen mode

Here, template literals generate a string that includes the values of firstName, lastName, and age. The resulting code is much more concise and easier to read than the equivalent code using string concatenation.

Spread Operator

The spread operator is a useful ES6 syntax that allows you to spread the elements of an iterable (e.g. an array) into a new array or function call. For instance:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = [...arr1, ...arr2];
console.log(mergedArr); // Output: [1, 2, 3, 4, 5, 6]

function sum(a, b, c) {
  return a + b + c;
}

const nums = [1, 2, 3];
console.log(sum(...nums)); // Output: 6
Enter fullscreen mode Exit fullscreen mode

In the first code, the spread operator concatenates two arrays into a new array. In the second example, it is used to pass the elements of the nums array as individual arguments to the sum function.

Conclusion

ES6 introduced several essential syntaxes to help you write more efficient and readable code in JS. Here, we have explored some critical syntaxes you should know as a beginner, including let and const keywords, arrow functions, template literals, destructuring, and the spread operator. By mastering these features, you will be well on your way to becoming a better JS programmer.

Top comments (0)