• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Using the spread operator

Using the spread operator

Using the spread operator

The spread operator allows you to quite literally “spread” out an array. This can be used to transform an array into a list of arguments or even combine two arrays together. You could also use it to form a list of arguments to a function too. Check it out:

let data = [1,2,3,4,5];
console.log(...data);
--> 1 2 3 4 5
let data2 = [6,7,8,9,10];
let combined = [...data, ...data2];
console.log(...combined);
--> 1 2 3 4 5 6 7 8 9 10
console.log(Math.max(...combined));
--> 10

In the first example we show how the spread operator works on an array and turns each item into an individual element. The second example combines the contents of two arrays together by creating a new temporary array containing both contents. The last example illustrates how the spread operator can turn an array into a list of arguments to a function. The Math.max returns the highest number in a list of arguments passed to it. One of those arguments was 10 which is the highest.

Source

https://levelup.gitconnected.com/6-javascript-code-snippets-for-solving-common-problems-33deb6cacef3

Miscellaneous

Related Snippets:

  • Get the index of the first matching item in an array
  • Determine if a string contains a substring
  • How to Make the First Letter of a String Uppercase in JavaScript
  • How to Check if an Array Includes a Value in JavaScript

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers