Modern JavaScript Syntax
ES6 (ECMAScript 2015) introduced many new features that make JavaScript code cleaner, more concise, and more powerful.
Arrow functions provide a shorter syntax for writing functions and have different behavior with the 'this' keyword.
Other ES6 features like template literals, destructuring, spread operator, and default parameters are now standard in modern JavaScript development.
// Arrow Functions
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => {
return a + b;
};
// Concise arrow function (implicit return)
const add = (a, b) => a + b;
// Single parameter (no parentheses needed)
const square = x => x * x;
// Template Literals
const name = 'John';
const age = 25;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
// Destructuring
const person = { firstName: 'Jane', lastName: 'Doe', age: 30 };
const { firstName, lastName } = person;
const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
// Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // { a: 1, b: 2, c: 3 }
// Default Parameters
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
greet(); // "Hello, Guest!"
greet('Alice'); // "Hello, Alice!"
- Arrow Functions - Shorter syntax: (params) => expression
- Template Literals - String interpolation using backticks and ${}
- Destructuring - Extract values from arrays/objects easily
- Spread Operator (...) - Expand arrays/objects into elements
- Default Parameters - Set default values for function parameters
- const/let - Block-scoped variables (replace var)
- for...of Loop - Iterate over array values directly
Try ES6 Features
<div class="es6-demo">
<h3>ES6 Features Demo</h3>
<div class="section">
<h4>Arrow Functions & Array Methods</h4>
<button id="mapBtn">Map Array</button>
<button id="filterBtn">Filter Array</button>
<div id="arrayOutput"></div>
</div>
<div class="section">
<h4>Template Literals</h4>
<input type="text" id="userName" placeholder="Your name">
<input type="number" id="userAge" placeholder="Your age">
<button id="templateBtn">Create Message</button>
<div id="templateOutput"></div>
</div>
<div class="section">
<h4>Destructuring & Spread</h4>
<button id="destructureBtn">Destructure Object</button>
<button id="spreadBtn">Combine Arrays</button>
<div id="destructureOutput"></div>
</div>
</div>
Note: Arrow Functions & 'this': Arrow functions don't have their own 'this' - they inherit it from parent scope.
Note: Browser Support: ES6 features are supported in all modern browsers. Use Babel for older browser support.
Note: Best Practices: Use const by default, let when reassignment needed, avoid var. Use arrow functions for callbacks and short functions.