Key New Features of ES6 (ECMAScript 6)

1. New Syntax Additions

1.1 let Variable Declaration

let provides a new way to declare variables with the following key characteristics:

// Multiple declaration formats are supported
let x;
let y, z, w;
let count = 100;
let num = 521, greeting = 'hello world', emptyArr = [];

// 1. No duplicate declarations allowed in the same scope
// let userName = 'Sam';
// let userName = 'Sammy'; // This will throw an error

// 2. Block-level scoping: any curly brace code block creates a separate scope
// if (true) {
//     let nickName = 'Sunny';
// }
// console.log(nickName); // ReferenceError: nickName is not defined

// 3. No variable hoisting
// console.log(songName); // ReferenceError: Cannot access 'songName' before initialization
// let songName = 'Love Story';

// 4. Scope chain behavior remains unchanged
{
    let campus = 'Example University';
    function logCampus(){
        console.log(campus);
    }
    logCampus(); // Logs "Example University"
}

Practical example: click to switch element background color, demonstrates the difference between let and var in loop scoping:

<body>
    <div class="container">
        <h2>Click to Change Color</h2>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
    </div>
    <script>
        // Get all box elements
        let boxes = document.getElementsByClassName('box');

        // Use let in the loop condition to get a separate binding per iteration
        for(let i = 0; i < boxes.length; i++){
            boxes[i].addEventListener('click', function(){
                boxes[i].style.background = 'lightpink';
            });
        }
    </script>
</body>

1.2 const Constant Declaration

const is used to declare read-only constants:

// Declare a constant
const APP_NAME = 'MyDemoApp';

// 1. Must assign an initial value at declaration
// const MAX_VALUE; // SyntaxError: Missing initializer in const declaration

// 2. Convention: constants use uppercase naming
// const maxLimit = 100; // Works but deviates from convention

// 3. Constant reference cannot be re-assigned
// APP_NAME = 'NewApp'; // TypeError: Assignment to constant variable

// 4. Also follows block-level scoping
// {
//     const PLAYER_NAME = 'Alex';
// }
// console.log(PLAYER_NAME); // ReferenceError: PLAYER_NAME is not defined

// 5. Modifying array/object properties does not count as re-assignment, so it is allowed
const TEAM_ROSTER = ['Alex', 'Bob', 'Charlie', 'David'];
TEAM_ROSTER.push('Eve'); // Allowed
TEAM_ROSTER[0] = 'Adam'; // Allowed
// TEAM_ROSTER = ['Alice', 'Ben']; // Error: re-assigning the constant reference

1.3 Destructuring Assignment

ES6 allows extracting values from arrays or objects and assigning them to variables following a matching pattern, called destructuring:

// 1. Array destructuring
// const comedyCast = ['Xiao Shenyang', 'Liu Neng', 'Zhao Si', 'Song Xiaobao'];
// let [xiao, liu, zhao, song] = comedyCast;
// console.log(xiao); // Outputs "Xiao Shenyang"

// 2. Object destructuring
const zhao = {
    fullName: 'Zhao Benshan',
    age: 'Unknown',
    performSketch: function(){
        console.log("I can perform comedy sketches");
    }
};

// let {fullName, age, performSketch} = zhao;
// console.log(fullName); // Outputs "Zhao Benshan"
// performSketch(); // Logs "I can perform comedy sketches"

// Extract only the required property to simplify code
let {performSketch} = zhao;
performSketch(); // No need to write zhao.performSketch() every time

1.4 Shorthand Object Syntax

ES6 allows directly writing variables and functions as object properties and methods inside curly braces, simplifying syntax:

let orgName = 'Tech Training';
let updateContent = function(){
    console.log('We update our content regularly');
};

const trainingOrg = {
    orgName, // Equivalent to orgName: orgName
    updateContent, // Equivalent to updateContent: updateContent
    improveSkills(){ // Shorthand method definition
        console.log("We help you improve your technical skills");
    }
};

console.log(trainingOrg);

1.5 Arrow Function Syntax

Arrow functions (using =>) are a new function syntax. They are best suited for non-context-bound callbacks like timers or array method callbacks, and not ideal for event callbacks or object methods that need their own this.

Key features and declaration syntax:

// Traditional function declaration for comparison
function add(a, b) {
    return a + b;
}
let oldAdd = function(a, b) {};

// 1. Basic arrow function syntax
let newFunc = () => {};

// 2. Omit parentheses when there is exactly one parameter
let singleParamFunc = num => {};

// 3. Omit curly braces and enable implicit return when there is only one line of code
let sum = (a, b) => a + b;

// Arrow functions do not bind their own `this`; `this` inherits from the surrounding lexical context
function logNameTraditional(){
    console.log(this.name);
}
let logNameArrow = () => {
    console.log(this.name);
};

window.name = 'Global Name';
const localObj = {
    name: "Local Object Name"
};

logNameTraditional(); // Logs "Global Name"
logNameArrow(); // Also logs "Global Name", `this` points to surrounding context

// Other key characteristics:
// - Cannot be used as constructor to instantiate objects
// - Cannot use the `arguments` object

// Shorthand example
let square = n => n * n;
console.log(square(9)); // Outputs 81

Practical examples:

// Case 1: Change element background color after 2 seconds on click
let banner = document.getElementById('banner');
banner.addEventListener("click", function(){
    // With arrow function, no need to save `this` to an intermediate variable
    setTimeout(() => {
        this.style.background = 'pink'; // `this` inherits from the click handler, pointing to the banner element
    }, 2000);
});

// Case 2: Filter even numbers from an array
const inputArr = [1, 6, 9, 10, 100, 25];
const evenNumbers = inputArr.filter(item => item % 2 === 0);
console.log(evenNumbers);

1.6 Default Function Parameters

ES6 allows setting default initial values for function parameters:

// 1. Parameter default values. Convention: default parameters are placed at the end of the parameter list
function calculateSum(a, c, b = 10) {
    return a + b + c;
}
let total = calculateSum(1, 2);
console.log(total); // Outputs 1 + 2 + 10 = 13

// 2. Combine with destructuring assignment
function connectDB({host="127.0.0.1", username, password, port}){
    console.log(host);
    console.log(username);
    console.log(password);
    console.log(port);
}

connectDB({
    host: 'db.example.com',
    username: 'root',
    password: 'root123',
    port: 3306
});

1.7 Rest Parameters

Rest parameters (introduced with ... syntax) are used to get all function arguments, replacing the traditional arguments object:

// Traditional way to get arguments (ES5)
function getArgsES5(){
    console.log(arguments); // Array-like object of arguments
}
getArgsES5('Anna', 'Bella', 'Claire');

// Rest parameter syntax (ES6)
function getArgsES6(...args){
    console.log(args); // Actual array of all input arguments
}
getArgsES6('Anna', 'Bella', 'Claire');

// Rest parameters must be placed at the end of the parameter list
function processValues(a, b, ...rest){
    console.log(a); // First input value
    console.log(b); // Second input value
    console.log(rest); // Array of all remaining values
}
processValues(1, 2, 3, 4, 5, 6);

// Rest parameters work with destructuring assignment
let students = ['Zhang San', 'Li Si', 'Wang Wu'];
let [firstStudent, ...remainingStudents] = students;
console.log(firstStudent); // "Zhang San"
console.log(remainingStudents); // ["Li Si", "Wang Wu"]

2. Extensions to Built-in Objects

2.1 Extensions to the String Built-in Object

(1) Template Literals

Template literals use backticks ` as a new string declaration syntax:

// 1. Declare a string
// let newStr = `This is a new string`;
// console.log(newStr, typeof newStr);

// 2. Allow line breaks directly inside the string
let listHtml = `<ul>
    <li>Mary</li>
    <li>Wei Xiang</li>
    <li>Allen</li>
</ul>`;

// 3. Support variable interpolation
let favoriteActor = 'Wei Xiang';
let output = `${favoriteActor} is my favorite comedian!`;
console.log(output);

// 4. Allow function calls inside interpolation
const getSignature = () => {
    return 'Comedy ';
};
let finalOutput = `${getSignature()}${favoriteActor} is my favorite comedian!`;
console.log(finalOutput);

(2) New String Methods

  • includes(searchString[, position]): Check if the string contains the target substring
  • startsWith(searchString[, position]): Check if the string starts with the target substring
  • endsWith(searchString[, endPosition]): Check if the string ends with the target substring
  • repeat(count): Return a new string that repeats the original string count times
  • padStart(targetLength[, padString]): Pad the start of the current string to reach the target length
  • padEnd(targetLength[, padString]): Pad the end of the current string to reach the target length
  • trimStart(): Remove all leading whitespace from the string
  • trimEnd(): Remove all trailing whitespace from the string
  • trim(): Remove all leading and trailing whitespace from the string

2.2 Extensions to the Array Built-in Object

  1. Spread (expansion) operator
  2. Array.from() static method
  3. find() instance method
  4. findIndex() instance method
  5. includes() instance method

2.3 New Set Data Structure

  1. Creation of Set instances
  2. Common instance methods
  3. Iteration over Set structures

3. Object-Oriented Programming

3.1 class Syntax for Classes and Objects

  1. Core concepts of classes and instances
  2. Class declaration and instance creation
  3. constructor constructor method
  4. Addding class methods

3.2 Class Inheritance

3.3 The super Keyword in Inheritance

3.4 Key Notes for ES6 Classes

Tags: javascript ES6 ecmascript Frontend Development

Posted on Mon, 12 Oct 2026 16:35:42 +0000 by chrischen