JavaScript spread Operator
You are Here:
JavaScript spread Operator
The spread
operator allows an iterable to expand in places where zero or more arguments are expected. It is mostly used in variable array where there is more than one values are expected.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [1, 2, 3, 4];
function myFunction(w, x, y, z){
return w + x + y + z;
}
document.write(myFunction(...arr));
</script>
</body>
</html>
Syntax
...iterableObj
More Examples
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var dateFields = [2020, 10, 13]; // 13 Nov 2020
var d = new Date(...dateFields);
document.write(d);
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<script>
var arr1 = ["two", "three"];
var arr2 = ["one", ...arr1, "four", "five"];
var txt = "";
for(var i = 0; i < arr2.length; i++)
txt += arr2[i] + "<br>";
document.write(txt);
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p>Check your console (Press F12).<p>
<script>
var obj1 = { foo: 'ABC', x: 53 };
var obj2 = { foo: 'XYZ', y: 75 };
var clonedObj = { ...obj1 };
console.log(clonedObj);
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p>Check your console (Press F12).<p>
<script>
var obj1 = { foo: 'ABC', x: 53 };
var obj2 = { foo: 'XYZ', y: 75 };
var mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.