Modern JavaScript (ES6) Features
Understanding Modern JavaScript (ES6) Features
1. What is ES6?
ES6 (ECMAScript 2015) introduced many modern features that make JavaScript easier to write and read.
Some important ES6 features include:
- Arrow Functions
- Template Literals
- Destructuring
- Spread Operator
letandconst
These features are widely used in modern frameworks such as Angular, React, and Vue.
2. Arrow Functions
Arrow functions provide a shorter syntax for writing functions.
Traditional Function:
function add(a, b){
return a + b;
}
Arrow Function:
const add = (a, b) => a + b;
console.log(add(5,3));
3. Template Literals
Template literals allow us to insert variables into strings easily.
let name = "Rahul";
let age = 20;
console.log(`Name: ${name}, Age: ${age}`);
4. Destructuring
Destructuring allows extracting values from arrays or objects.
Example with object:
let student = {
name: "Anu",
age: 19
};
let {name, age} = student;
console.log(name);
console.log(age);
5. Spread Operator
The spread operator allows expanding elements of arrays or objects.
let numbers = [1,2,3];
let newNumbers = [...numbers, 4,5];
console.log(newNumbers);
6. Real-Life Example: Student Grade Analyzer
This application analyzes student marks and assigns grades.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Student Grade Analyzer</title>
</head>
<body>
<h2>Student Grade Analyzer</h2>
<input type="number" id="marks" placeholder="Enter marks">
<button onclick="checkGrade()">Check Grade</button>
<h3 id="result"></h3>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
const checkGrade = () => {
let marks = Number(document.getElementById("marks").value);
let grade = "";
if(marks >= 90){
grade = "A+";
}
else if(marks >= 75){
grade = "A";
}
else if(marks >= 60){
grade = "B";
}
else if(marks >= 50){
grade = "C";
}
else{
grade = "Fail";
}
let result = document.getElementById("result");
result.innerText = `Grade: ${grade}`;
};
Run Code
7. How This Example Works
- User enters marks.
- The arrow function
checkGrade()runs when the button is clicked. - Conditional statements determine the grade.
- The result is displayed using a template literal.
8. Practice Exercise
Create a Product Price Calculator.
Inputs:
- Product price
- Discount percentage
Output:
- Final price after discount
Use:
- Arrow functions
- Template literals
9. What Students Learned
- Modern JavaScript features
- Arrow functions
- Template literals
- Destructuring
- Spread operator
Course Summary
After completing these 10 chapters, students can:
- Write JavaScript programs
- Use conditions, loops, and functions
- Work with arrays and objects
- Manipulate the DOM
- Handle browser events
- Use modern JavaScript features
They are now ready to move on to advanced JavaScript or frameworks like Angular.