Topic : JavaScript ES6+ Features, Arrow Functions, Destructuring & Spread Operator
Introduction
JavaScript is a popular programming language used to create interactive and dynamic websites. Modern JavaScript includes several features that help developers write cleaner, shorter, and more maintainable code.
ES6 introduced many important improvements to JavaScript, and later versions added even more useful features. These are commonly referred to as ES6+ features.
In this session, you will learn about variable declarations, arrow functions, template literals, destructuring, spread and rest operators, default parameters, and practical JavaScript programming.
1. What Is ES6?
Definition: ES6 stands for ECMAScript 2015. It is a major update to the JavaScript language that introduced several features to improve code readability and functionality.
Important ES6+ Features
letandconstfor variable declarations.- Arrow functions for concise function syntax.
- Template literals for dynamic strings.
- Destructuring for extracting values from arrays and objects.
- Spread and rest operators for working with multiple values.
- Default parameters for assigning default argument values.
- Modules for organizing code into separate files.
- Promises for handling asynchronous operations.
Example:
const studentName = "Aman";
const course = "Full Stack Development";
console.log(`${studentName} is learning ${course}.`);
Output:
Aman is learning Full Stack Development.
2. Variables: var, let, and const
Definition: Variables are used to store data in JavaScript. The var, let, and const keywords are used to declare variables, but they differ in scope and reassignment behavior.
A. var
The var keyword declares a function-scoped or globally scoped variable. It allows reassignment and redeclaration within the same scope.
var name = "Aman";
name = "Rahul";
console.log(name);
Output:
Rahul
B. let
The let keyword declares a block-scoped variable. Its value can be reassigned, but it cannot be redeclared in the same scope.
let age = 21;
age = 22;
console.log(age);
Output:
22
C. const
The const keyword declares a block-scoped variable that cannot be reassigned after initialization.
const course = "JavaScript";
console.log(course);
Output:
JavaScript
A const array or object can still have its contents modified, but the variable cannot be reassigned to a different array or object.
const languages = ["HTML", "CSS"];
languages.push("JavaScript");
console.log(languages);
Output:
["HTML", "CSS", "JavaScript"]
Difference Between var, let, and const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Reassignment | Allowed | Allowed | Not allowed |
| Redeclaration in the same scope | Allowed | Not allowed | Not allowed |
| Initialization required | No | No | Yes |
Best Practice: Prefer const by default and use let when a variable needs reassignment. Avoid var in most modern JavaScript code.
3. Arrow Functions
Definition: An arrow function is a shorter way to write a JavaScript function. It uses the => arrow symbol and is commonly used for callbacks and array methods.
Traditional Function
function add(a, b) {
return a + b;
}
console.log(add(10, 20));
Output:
30
Arrow Function
const add = (a, b) => {
return a + b;
};
console.log(add(10, 20));
Output:
30
Short Arrow Function
When the function contains only one expression, curly braces and the return keyword can be omitted.
const multiply = (a, b) => a * b;
console.log(multiply(5, 4));
Output:
20
Arrow Functions with Array Methods
Arrow functions are frequently used with methods such as map(), filter(), and forEach().
const numbers = [10, 20, 30, 40];
const doubled = numbers.map(number => number * 2);
console.log(doubled);
Output:
[20, 40, 60, 80]
Important Note: Arrow functions do not have their own this value. They inherit it from the surrounding scope, so they are not a direct replacement for every regular function.
4. Template Literals
Definition: Template literals are a way to create strings using backticks (`). They allow developers to insert variables and expressions directly into strings using ${}.
Example
const studentName = "Priya";
const marks = 85;
console.log(`Student ${studentName} scored ${marks} marks.`);
Output:
Student Priya scored 85 marks.
Using Expressions
const a = 10;
const b = 20;
console.log(`The total is ${a + b}.`);
Output:
The total is 30.
Practical Applications
Template literals are useful for:
- Displaying student details.
- Showing product names and prices.
- Creating personalized messages.
- Generating dynamic website content.
5. Destructuring
Definition: Destructuring is a JavaScript feature that allows you to extract values from arrays or properties from objects and assign them to variables.
A. Array Destructuring
Array destructuring extracts values according to their positions in an array.
const courses = ["HTML", "CSS", "JavaScript"];
const [first, second, third] = courses;
console.log(first);
console.log(second);
console.log(third);
Output:
HTML
CSS
JavaScript
You can skip values by leaving an empty space between commas.
const numbers = [10, 20, 30];
const [first, , third] = numbers;
console.log(first);
console.log(third);
Output:
10
30
B. Object Destructuring
Object destructuring extracts values using property names.
const student = {
name: "Rahul",
age: 21,
course: "Full Stack Development"
};
const { name, age, course } = student;
console.log(name);
console.log(age);
console.log(course);
Output:
Rahul
21
Full Stack Development
C. Renaming Variables
You can assign an object property to a variable with a different name.
const employee = {
name: "Aman",
salary: 35000
};
const { name: employeeName, salary } = employee;
console.log(employeeName);
console.log(salary);
Output:
Aman
35000
Practical Applications: Destructuring is useful when working with API responses, employee records, configuration objects, and React component properties.
6. Spread Operator (…)
Definition: The spread operator uses three dots (...) to expand the elements of an iterable, such as an array, or the enumerable properties of an object.
A. Copying an Array
const original = [1, 2, 3];
const copied = [...original];
copied.push(4);
console.log(original);
console.log(copied);
Output:
[1, 2, 3]
[1, 2, 3, 4]
The original array remains unchanged because the spread operator creates a separate shallow copy.
B. Combining Arrays
const frontend = ["HTML", "CSS"];
const backend = ["Node.js", "Express"];
const fullStack = [...frontend, ...backend];
console.log(fullStack);
Output:
["HTML", "CSS", "Node.js", "Express"]
C. Copying and Updating an Object
const student = {
name: "Aman",
course: "JavaScript"
};
const updatedStudent = {
...student,
course: "Full Stack Development"
};
console.log(student);
console.log(updatedStudent);
Output:
{ name: "Aman", course: "JavaScript" }
{ name: "Aman", course: "Full Stack Development" }
The original object remains unchanged in this example.
Important Note: Spread creates a shallow copy. If an object contains nested objects or arrays, those nested values may still be shared between the original and copied objects.
7. Rest Parameters
Definition: Rest parameters use three dots (...) to collect multiple function arguments into a single array.
Example
function calculateTotal(...prices) {
return prices.reduce((total, price) => total + price, 0);
}
console.log(calculateTotal(100, 200, 300, 400));
Output:
1000
In this example, all arguments are collected inside the prices array, and reduce() calculates their total.
Spread vs. Rest
| Spread Operator | Rest Parameter |
|---|---|
| Expands values | Collects values |
| Commonly used in arrays and objects | Commonly used in function parameters |
Example: [...numbers] | Example: function sum(...numbers) |
Although both use ..., their purpose depends on where they appear.
8. Default Parameters
Definition: Default parameters allow a function to use a predefined value when an argument is omitted or explicitly passed as undefined.
Example
function greet(name = "Student") {
return `Welcome, ${name}!`;
}
console.log(greet("Priya"));
console.log(greet());
Output:
Welcome, Priya!
Welcome, Student!
Multiple Default Parameters
function courseDetails(
name = "Student",
course = "Full Stack Development"
) {
return `${name} is enrolled in ${course}.`;
}
console.log(courseDetails("Aman"));
console.log(courseDetails());
Output:
Aman is enrolled in Full Stack Development.
Student is enrolled in Full Stack Development.
Practical Use: Default parameters are helpful when creating reusable functions that may receive incomplete information.
9. Array Methods: map(), filter(), forEach(), and reduce()
These array methods are frequently used in modern JavaScript applications.
A. map()
Definition: The map() method creates a new array by applying a function to every element of the original array.
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(number => number * number);
console.log(squares);
Output:
[1, 4, 9, 16, 25]
B. filter()
Definition: The filter() method creates a new array containing only the elements that satisfy a specified condition.
const salaries = [20000, 35000, 45000, 28000, 50000];
const highSalaries = salaries.filter(salary => salary > 30000);
console.log(highSalaries);
Output:
[35000, 45000, 50000]
C. forEach()
Definition: The forEach() method executes a function for each element in an array. It is useful for displaying or processing array items.
const courses = ["HTML", "CSS", "JavaScript"];
courses.forEach(course => {
console.log(course);
});
Output:
HTML
CSS
JavaScript
D. reduce()
Definition: The reduce() method processes array elements to produce a single accumulated result, such as a sum or total.
const numbers = [100, 200, 300, 400];
const total = numbers.reduce((sum, number) => sum + number, 0);
console.log(total);
Output:
1000
10. Practical Mini Project: Student Profile Generator
This mini-project combines arrow functions, default parameters, object properties, template literals, and array iteration.
Code
const createStudent = (
name = "Student",
course = "Full Stack Development",
marks = 0
) => {
return {
name,
course,
marks,
status: marks >= 40 ? "Pass" : "Fail"
};
};
const student1 = createStudent("Aman", "JavaScript", 78);
const student2 = createStudent("Priya", "React", 35);
const students = [student1, student2];
students.forEach(({ name, course, marks, status }) => {
console.log(
`${name} | ${course} | Marks: ${marks} | Result: ${status}`
);
});
Output
Aman | JavaScript | Marks: 78 | Result: Pass
Priya | React | Marks: 35 | Result: Fail
Project Explanation
- The
createStudent()arrow function creates a student object. - Default parameters provide values when information is omitted.
- The object stores the student’s name, course, marks, and result status.
- The
studentsarray stores multiple student records. forEach()processes each student.- Object destructuring extracts the student properties.
- Template literals format the output into readable text.
- The ternary operator determines whether the student passes or fails.
This project demonstrates how modern JavaScript features can work together in a practical application.
Conclusion
Modern JavaScript ES6+ features make code more readable, reusable, and easier to maintain. Understanding these concepts is an important step toward learning frontend frameworks such as React and building full-stack web applications.
Read the material carefully, practice each concept, and complete the assignment independently to strengthen your programming skills.
Keep Practicing, Keep Coding, Keep Growing
— Team ONLEI Technologies
