Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are the latest operators added to JavaScript?
JavaScript has introduced several powerful operators in recent versions, with the rest and spread operators being among the most significant additions in ES6 (ES2015). These operators use the same three-dot syntax (...) but serve different purposes depending on context.
Rest Operator
The rest operator allows you to represent an indefinite number of arguments as an array. It's indicated by three dots (...) and precedes a parameter in function definitions.
Example
Here's how to use the rest operator to handle multiple function arguments:
<html>
<body>
<script>
function addition(...numbers) {
var res = 0;
numbers.forEach(function (number) {
res += number;
});
return res;
}
document.write("Sum of 3: " + addition(3) + "<br>");
document.write("Sum of multiple: " + addition(9, 10, 11, 12, 13));
</script>
</body>
</html>
Sum of 3: 3 Sum of multiple: 55
Spread Operator
The spread operator allows an expression to expand into multiple arguments, elements, or variables. It's useful for array manipulation, function calls, and object cloning.
Example
Compare traditional array concatenation with the spread operator:
<html>
<body>
<script>
var a, b, c, d, e, f;
a = [10, 20];
b = "rank";
c = [30, "points"];
d = "run";
// Traditional concat method
e = a.concat(b, c, d);
// Spread operator
f = [...a, b, ...c, d];
document.write("Concat result: " + e + "<br>");
document.write("Spread result: " + f);
</script>
</body>
</html>
Concat result: 10,20,rank,30,points,run Spread result: 10,20,rank,30,points,run
Other Modern JavaScript Operators
Beyond rest and spread, JavaScript has added several other operators:
- Nullish Coalescing (??) - Returns right operand when left is null or undefined
- Optional Chaining (?.) - Safely access nested object properties
- Logical Assignment (&&=, ||=, ??=) - Combine logical operations with assignment
Key Differences
| Operator | Usage Context | Purpose |
|---|---|---|
| Rest (...) | Function parameters | Collect multiple arguments into array |
| Spread (...) | Function calls, arrays, objects | Expand array/object elements |
Conclusion
The rest and spread operators have revolutionized JavaScript development by simplifying array manipulation and function parameter handling. These operators provide cleaner, more readable code compared to traditional methods.
