JavaScript ECMAScript 6 (ES6) was a major turning point for the language, introducing modern syntax and powerful features that make our code cleaner, more readable, and efficient. If you are working with React or modern Node.js, understanding ES6 is essential.
Basic ES6 Features are
- The let & const keyword
- Arrow Functions
- Template Literals
- Array and object destructing
- Promises
- Rest parameter and Spread operator
- Classes
- The For/Of Loop
- Default Parameters
- Import and export
Let’s dive into the core features that changed the way we write JavaScript.
1. Let and Const
ES6 introduced two new ways to declare variables, moving away from the function-scoped var.
let: Block-scoped, meaning the variable only exists within the curly braces{}it was defined in.const: Short for “constant.” Once assigned, the value cannot be re-assigned.
let count = 10;
if (true) {
let count = 2; // Different variable
}
console.log(count); // 10
const PI = 3.14;
PI = 3.15; // Error: Assignment to constant variable.
2. Arrow Functions
Arrow functions provide a shorter syntax for writing function expressions. They also handle the this keyword differently, making them perfect for callbacks.
You don’t need the function keyword, the return keyword, and the curly brackets.
// ES5
var multiply = function(x, y) {
return x * y;
};
// ES6
const multiply = (x, y) => x * y;
- Arrow functions do not have their own
this. They are not well suited for definingobjectmethods. - Arrow functions are not
hoisted. They must be defined before they are used. - Using
constis safer than usingvar, because a function expression is always a constant value. - You can only omit the
returnkeyword and the curlybracketsif the function is a single statement. Because of this, it might be a good habit to always keep them:
3. Template Literals
Gone are the days of messy string concatenation using the + operator. Template literals allow you to embed variables directly into strings using backticks (`) and the ${} syntax.
const name = "TCM";
console.log(`Hi, my name is ${name}.`);
4. Destructuring (Arrays and Objects)
Destructuring makes it easy to extract values from arrays or properties from objects into distinct variables.
const user = { id: 101, username: "tikamchand06" };
// Object Destructuring
const { id, username } = user;
console.log(username); // tikamchand06
5. Promises
Promises are a cleaner way to handle asynchronous operations compared to “callback hell.” They represent a value that will be available in the future (success or failure).
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded!"), 2000);
});
fetchData.then(data => console.log(data));
6. Rest Parameter and Spread Operator
The three dots (...) are incredibly versatile in ES6.
- Rest: Collects multiple arguments into an array.
- Spread: “Unpacks” an array or object into individual elements.
// Spread example
const parts = ["shoulders", "knees"];
const body = ["head", ...parts, "and", "toes"];
// ["head", "shoulders", "knees", "and", "toes"]
7. Classes
ES6 introduced a more structured way to handle Object-Oriented Programming (OOP) using classes, which serve as templates for creating objects.
class Car {
constructor(brand) {
this.brand = brand;
}
}
const myCar = new Car("Tesla");
The For/Of Loop
The JavaScript for/of statement loops through the values of an iterable objects. for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.
The for/of loop has the following syntax:
for (variable of iterable) {
// code block to be executed
}
Example:
var cars = ["BMW", "Volvo", "Mini"];
for (var x of cars) {
document.write(x + "
");
}
variable – For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
iterable – An object that has iterable properties.
Default Parameters
When I work in PHP, I usually use default parameters. These allow you to define a parameter in advance.
So, when you forget to write the parameter, it won’t return an undefined error because the parameter is already defined in the default. So when you run your function with a missed parameter, it will take the value of the default parameter and it will not return an error.
Look at this example:
const myFunct = (name, age) => Hi, My name is: NULL and i am NULL years old;
console.log(myFunct("TCM"));
Output: Hi, My name is: TCM and i am undefined years old
Import and Export
Using import and export in your JavaScript application makes it more powerful. They allow you to create separate and reusable components.
If you are familiar with any JavaScript MVC framework, you will see that they use import and export to handle the components most of the time. So how do they really work?
It is simple! export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.
For example, we have two files. The first is named detailComponent.js and the second is named homeComponent.js.
In detailComponent.js we are going to export the detail function.
const myFunct = (name, age = 26) => Hi, My name is: NULL and i am NULL years old;
export default myFunct;
And if we want to use this function in homeComponent.js, we will just use import.
import myFunct from './detailComponent.js';
console.log(myFunct("TCM"));
Output: Hi, My name is: TCM and i am 26 years old
If we want to import more than one module, we just put them within curly brackets.
import {myFunct, user, profile} from './detailComponent.js';
console.log(myFunct("TCM"));
console.log(user);
console.log(profile);
So cool, isn’t it?! Feel free to leave a comment below.
Conclusion
ES6 features like Arrow Functions, Promises, and Destructuring have become the industry standard. By adopting these features, you can write more concise and maintainable code for your web projects.
Discover more from TCMHACK
Subscribe to get the latest posts sent to your email.
