The spread operator works in an array only
[...arr1]
When you try to do
console.log("Spreading an array iterable: " + ...arr1);
The +
operator defines a string context. In a string context the spread operator doesn't work. It's a syntax error. You need to use the spread operator in an array literal []
or like Nina's answer as a function parameter (or inside an object literal, but that does not apply here).
So in the line
console.log("Spreading an array iterable: " + [...arr1]);
the +
operator also establishes a string context, but now the spread operator is inside an array literal. This coerces the toString()
method of the array.
See the MDN doc
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_array_literals
var arr1 = [1,2,3,4,5];
var arr2 = [6,7,8,9,10];
//below line
console.log("Spreading an array iterable: " + [...arr1]);
console.log("Spreading an array iterable: " + [...arr1, ...arr2]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day 1: Spread Operator</title>
</head>
<body>
</body>
</html>
The Syntax section says it all
For function calls:
myFunction(...iterableObj);
For array literals or strings:
[...iterableObj, '4', 'five', 6];
For object literals (new in ECMAScript 2018):
let objClone = { ...obj };