Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

How Do Rest Parameters Work in JavaScript?

// With rest parameters, you can define a function to store multiple arguments in a single array

function sayHello(message, ...names){
  names.forEach(name => console.log(`${message} ${name}`));
}

sayHello('Hello', "John", "Smith", "Doe");

/*
output:

Hello John

Hello Smith

Hello Doe 

*/

// The ... is what makes names a rest parameter.
Comment

rest parameters javascript

/*
That allows a function to accept an indefinite number of arguments as an array
*/
function fun(...input){
    let sum = 0;
    for(let i of input){
        sum+=i;
    }
    return sum;
}
console.log(fun(1,2)); //3
console.log(fun(1,2,3)); //6
console.log(fun(1,2,3,4,5)); //15 
Comment

javascript rest parameter

function show(a, b, ...args) {
  console.log(a); // one
  console.log(b); // two
  console.log(args); // ["three", "four", "five", "six"]
}

show('one', 'two', 'three', 'four', 'five', 'six')
Comment

javascript Rest Parameter

let func = function(...args) {
    console.log(args);
}

func(3); // [3]
func(4, 5, 6); // [4, 5, 6]
Comment

rest parameters javascript

/*The rest parameter syntax allows a function to accept an indefinite
number of arguments as an array, */

function getFirstElementOfArray(...args){
  return args[1]
}

getFirstElementOfArray("shirshak","Sabtech","Javascript")// return shirshak
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript Arguments Binding 
Javascript :: javascript Tagged Templates 
Javascript :: javascript map size 
Javascript :: javascript Skip Items 
Javascript :: javascript setTimeout() method returns the interval id 
Javascript :: javascript this Inside Inner Function 
Javascript :: javascript Regular Expression Modifier 
Javascript :: JavaScript Object Prototypes 
Javascript :: mui on node 
Javascript :: how to write like query in node js 
Javascript :: dropzone sending event add additional data 
Javascript :: javascript process.env.key with  
Javascript :: switch javascript to java 
Javascript :: alternative for react-tilt 
Javascript :: Elementor Hide Sticky Header on Scroll Down - Show on Scroll Up 
Javascript :: phaser add animation event 
Javascript :: phaser sprite animation event 
Javascript :: javascript accordion 
Javascript :: chai promise resolved 
Javascript :: docker for node , exoress and coackraz 
Javascript :: Return characters in a string in alphabetic order 
Javascript :: Slice and Splice -Javascript 2 
Javascript :: js object filter by keys 
Javascript :: are you sure alert js 
Javascript :: for in loop 
Javascript :: anti aliasing 
Javascript :: pass infinite argument in function 
Javascript :: javascript operators 
Javascript :: object.assign in node.js 
Javascript :: keyboard close when typing react native 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =