ES6 introduces several features that provide shortcuts for working with arrays and objects, as well as creating variables more elegantly. Some of the prominent features include:
-
Arrow Functions: Arrow functions offer a concise syntax for defining functions. They are particularly useful for one-liners and implicit returns, making code more readable.
-
Spread Operator: The spread operator (
...
) allows for easy copying of arrays and objects. It simplifies tasks such as combining arrays/objects or creating shallow copies. -
Rest Parameter Syntax: The rest parameter syntax (
...rest
) enables functions to accept variable numbers of arguments. It simplifies handling additional arguments beyond a specified number. -
Destructuring: Destructuring provides a convenient way to extract values from arrays and objects. It allows for assigning values to multiple variables in a single expression.
// Arrow Functions
const addTwoNumbers = (a, b) => a + b;
let sum = addTwoNumbers(3, 5);
// Spread Operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4];
// Rest Parameter Syntax
const sumRest = (a, b, c, ...rest) => {
let sum = a + b + c;
for (let i of rest) {
sum += i;
}
return sum;
}
// Destructuring
let [first, second, ...rest] = [1, 2, 3, 4, 5];
To run the provided JavaScript script, follow these steps:
- Ensure you have Node.js installed on your machine. You can download it from here.
- Open a terminal or command prompt.
- Navigate to the directory where the
destructuring.js
file is located. - Run the script using the following command:
node destructuring.js