JavaScript ES6+ Features for Beginners

Learn JavaScript ES6+ features for beginners: let, const, arrow functions, template literals, classes, modules, promises, async/await, and more.


JavaScript ES6, also known as ECMAScript 2015, introduced a wide range of modern features that make coding more efficient, readable, and maintainable. In the years since, newer ECMAScript versions (ES7, ES8, ES9, ES10, and beyond) have added even more powerful capabilities. This guide explores all major ES6+ features for beginners, with practical examples and best practices to help you write modern JavaScript code confidently.

1. Let and Const

ES6 introduced let and const for block-scoped variables, replacing var in most cases.

1.1 Let

let age = 25;
age = 26; // allowed
console.log(age);

1.2 Const

const pi = 3.14159;
// pi = 3.14; // Error: cannot reassign a const variable
console.log(pi);

Use let for variables that change and const for constants or objects that should not be reassigned.

2. Template Literals

Template literals allow multi-line strings and string interpolation using backticks (`).

const name = 'John';
const greeting = `Hello, ${name}! Welcome to ES6+ JavaScript.`;
console.log(greeting);

3. Arrow Functions

Arrow functions provide a shorter syntax and lexical this binding:

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

// Arrow function
const sumArrow = (a, b) => a + b;

console.log(sumArrow(5, 3));

4. Default Parameters

Set default values for function parameters:

function greet(name = 'Guest') {
    console.log(`Hello, ${name}!`);
}

greet(); // Hello, Guest!

5. Destructuring

5.1 Array Destructuring

const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, b, c);

5.2 Object Destructuring

const user = { name: 'Alice', age: 30 };
const { name, age } = user;
console.log(name, age);

6. Spread and Rest Operators

6.1 Spread

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2);

6.2 Rest

function sumAll(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}
console.log(sumAll(1,2,3,4));

7. Enhanced Object Literals

Shorter syntax for objects:

const name = 'Bob';
const age = 25;
const user = { name, age, greet() { console.log('Hi!'); } };
user.greet();

8. Modules

ES6 supports importing and exporting modules:

// utils.js
export function add(a, b) { return a + b; }

// main.js
import { add } from './utils.js';
console.log(add(5, 3));

9. Classes

ES6 introduces a cleaner syntax for object-oriented programming:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
}

const alice = new Person('Alice', 30);
alice.greet();

10. Promises

Promises simplify asynchronous operations:

const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve('Data received'), 1000);
    });
};

fetchData().then(data => console.log(data)).catch(err => console.error(err));

11. Async/Await

Async/Await provides cleaner syntax for handling asynchronous code:

async function getData() {
    try {
        const data = await fetchData();
        console.log(data);
    } catch(err) {
        console.error(err);
    }
}

getData();

12. Map and Set

12.1 Map

const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);
console.log(map.get('name'));

12.2 Set

const set = new Set([1,2,3,3]);
console.log(set); // {1,2,3}

13. For...of and For...in Loops

const arr = [10,20,30];
for(const value of arr) {
    console.log(value);
}

const obj = {name:'Alice', age:25};
for(const key in obj) {
    console.log(key, obj[key]);
}

14. Template Strings for Multi-Line HTML

const html = `

Hello World

This is a template literal

`; document.body.innerHTML = html;

15. Optional Chaining

const user = { name: 'Alice', address: { city: 'Paris' } };
console.log(user.address?.city); // Paris
console.log(user.contact?.phone); // undefined

16. Nullish Coalescing Operator

const name = null;
console.log(name ?? 'Guest'); // Guest

17. Default Parameters & Destructuring

function greet({name='Guest', age=0} = {}) {
    console.log(`Hello ${name}, age ${age}`);
}
greet({name:'Bob'}); // Hello Bob, age 0

18. Practical Examples

18.1 Dynamic To-Do App

class Todo {
    constructor(task) { this.task = task; }
}
const todos = [];
const input = document.querySelector('input');
const form = document.querySelector('form');
form.addEventListener('submit', e => {
    e.preventDefault();
    const todo = new Todo(input.value);
    todos.push(todo);
    input.value = '';
    console.log(todos);
});

18.2 Fetch API with Async/Await

async function getUsers() {
    try {
        const res = await fetch('https://jsonplaceholder.typicode.com/users');
        const data = await res.json();
        console.log(data);
    } catch(err) { console.error(err); }
}
getUsers();

18.3 ES6 Modules in Practice

// math.js
export const add = (a,b) => a+b;
export const subtract = (a,b) => a-b;

// app.js
import { add, subtract } from './math.js';
console.log(add(5,3));
console.log(subtract(5,3));

19. Best Practices

  • Prefer let and const over var.
  • Use arrow functions for concise syntax.
  • Use template literals for string interpolation.
  • Keep asynchronous code readable using async/await.
  • Organize code using modules and classes.
  • Use Map and Set for specialized collections.
  • Use optional chaining and nullish coalescing for safer code.

20. Common Mistakes

  • Overusing global variables.
  • Misunderstanding this in arrow vs normal functions.
  • Not handling errors in asynchronous code.
  • Confusing == and ===.
  • Forgetting to import/export modules correctly.

21. FAQs about JavaScript ES6+

What is ES6?

ES6 (ECMAScript 2015) is a major update to JavaScript that introduced modern features such as let/const, arrow functions, template literals, classes, and modules.

Should beginners learn ES6 or older JavaScript first?

Learning ES6+ from the start is recommended since most modern projects and frameworks use ES6 syntax.

What are arrow functions?

Arrow functions are concise function expressions with lexical this binding.

What is destructuring?

Destructuring allows unpacking values from arrays or objects into distinct variables.

How do ES6 modules work?

Modules allow splitting code into reusable files using export and import.

What is optional chaining?

Optional chaining (?.) allows accessing nested properties safely without causing errors if a property is undefined.

Conclusion

JavaScript ES6+ brings modern syntax and features that improve code readability, maintainability, and functionality. By understanding let/const, template literals, arrow functions, destructuring, classes, modules, promises, async/await, and other features, beginners can write clean, efficient, and modern JavaScript. Start practicing these features in small projects like to-do apps, fetch API interactions, and modular coding to build confidence and master ES6+ for real-world development.

About the author

Prasun Barua
Prasun Barua is a graduate engineer in Electrical and Electronic Engineering with a passion for simplifying complex technical concepts for learners and professionals alike. He has authored numerous highly regarded books covering a wide range of elec…

Post a Comment