SimpleTuts.com

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:

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

  1. User enters marks.
  2. The arrow function checkGrade() runs when the button is clicked.
  3. Conditional statements determine the grade.
  4. The result is displayed using a template literal.

8. Practice Exercise

Create a Product Price Calculator.

Inputs:

Output:

Use:


9. What Students Learned


Course Summary

After completing these 10 chapters, students can:

They are now ready to move on to advanced JavaScript or frameworks like Angular.