ES6 (ECMAScript 6), also known as ES2015, introduced many new features and improvements to JavaScript. Some of the key features include arrow functions, template literals, destructuring, and the spread operator.
Tabular Comparisons:
Feature | Description |
---|---|
Arrow functions | A shorthand way of writing functions |
Template literals | A way of embedding variables and expressions in strings |
Destructuring | A way of extracting data from arrays and objects |
Spread operator | A way of spreading the elements of an array or object |
Text Diagram:
ES6+ Features
|
Arrow Functions Template Literals Destructuring Spread Operator
| | | |
Shorthand syntax Embed variables Extract data Spread elements
for functions and expressions from arrays of arrays/objects
| | and objects |
() => {} `Hello ${name}` const { [...arr, 4, 5]
const { name, age } = obj
name, age } = obj
Basic Programs:
- Arrow functions:
// Traditional function
function add(x, y) {
return x + y;
}
// Arrow function
const add = (x, y) => x + y;
console.log(add(2, 3)); // 5
- Template literals:
const name = 'John Doe';
console.log(`Hello ${name}!`); // "Hello John Doe!"
- Destructuring:
const person = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA',
zip: '12345'
}
};
// Extracting data from an object
const { name, age, address: { city } } = person;
console.log(name); // "John Doe"
console.log(age); // 30
console.log(city); // "Anytown"
const numbers = [1, 2, 3, 4, 5];
// Extracting data from an array
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
- Spread operator:
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const arr3 = [...arr1, ...arr2, 6, 7];
console.log(arr3); // [1, 2, 3, 4, 5, 6, 7]
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = { ...obj1, ...obj2, e: 5 };
console.log(obj3); // {a: 1, b: 2, c: 3, d: 4, e: 5}
To run these programs in Visual Studio Code, create a JavaScript file with a .js
extension and run the file using Node.js. For example:
// script.js
const add = (x, y) => x + y;
console.log(add(2, 3)); // 5
const name = 'John Doe';
console.log(Hello ${name}!); // "Hello John Doe!"
const numbers = [1, 2, 3, 4, 5];
const [first, second, …rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
Open the terminal in Visual Studio Code and navigate to the folder where the script.js
file is located. Then, run the file using the following command:
node script.js
This will run the file and output the results in the terminal.