ADVERTISEMENT
ADVERTISEMENT

How to use Spread Operator and Rest Parameter in JavaScript and ReactJS?

Learn how to use Spread Operator and Rest Parameter in ReactJS and JavaScript with Example?
Submitted by IncludeHelp, on January 20, 2022

Three dots (...) represent "Spread Operator" or "Rest Parameters" and they are the 2 features of JavaScript which have been introduced in ES6 syntax.

JavaScript - Spread Operator

It allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Example: Combining array elements and adding a new key:value to an Object

const numbers = [1, 2, 3];
console.log([...numbers, 4, 5]);

const person = {id: 1, name: 'Ashok Kumar'};
console.log({...person, age: 30});

Output:

[ 1, 2, 3, 4, 5 ]
{ id: 1, name: 'Ashok Kumar', age: 30 }

Example (Another use case): When we want to get a copy of an array or an object. Let's check this example,

Array:

let names = ['Ajay', 'Anil', 'Deepak'];

let anotherNames = names;

anotherNames[2] = 'Deepak Sharma';

// Printing first array
console.log(names);
// Printing copy of first array
console.log(anotherNames);

Output:

[ 'Ajay', 'Anil', 'Deepak Sharma' ]
[ 'Ajay', 'Anil', 'Deepak Sharma' ]

Object:

let person = {id: 1, name: 'Ashok Kumar'};

let anotherPerson = person;

anotherPerson.name = 'Deepak Sharma';

// Printing first object
console.log(person);
// Printing copy of first object
console.log(anotherPerson);

Output:

{ id: 1, name: 'Deepak Sharma' }
{ id: 1, name: 'Deepak Sharma' }

Why this happens?

This is because when you use "=" to copy the array or object then its reference is copied instead of its elements or key:value pair in case of object. So to handle such cases we can use spread operator like,

Array:

let names = ['Ajay', 'Anil', 'Deepak'];

let anotherNames = [...names];

anotherNames[2] = 'Deepak Sharma';

// Printing first array
console.log(names);
// Printing copy of first array
console.log(anotherNames);

Output:

[ 'Ajay', 'Anil', 'Deepak' ]
[ 'Ajay', 'Anil', 'Deepak Sharma' ]

Object:

let person = {id: 1, name: 'Ashok Kumar'};

let anotherPerson = {...person};

anotherPerson.name = 'Deepak Sharma';

// Printing first object
console.log(person);
// Printing copy of first object
console.log(anotherPerson);

Output:

{ id: 1, name: 'Ashok Kumar' }
{ id: 1, name: 'Deepak Sharma' }

Important: Spread will not work for the nested object, check this example,

let person = {id: 1, name: 'Ashok Kumar', address: {home: 'ABC', office: 'DEF'}};

let anotherPerson = {...person};

anotherPerson.name = 'Deepak Sharma';
anotherPerson.address.office = 'GHI';

// Printing first object
console.log(person);
// Printing copy of first object
console.log(anotherPerson);

Output:

{ id: 1, name: 'Ashok Kumar', address: { home: 'ABC', office: 'GHI' } }
{
  id: 1,
  name: 'Deepak Sharma',
  address: { home: 'ABC', office: 'GHI' }
}

JavaScript - Rest Parameter

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

Description:

A function definition's last parameter can be prefixed with "..." which will cause all remaining (user-supplied) parameters to be placed within a standard JavaScript array. Only the last parameter in a function definition can be a rest parameter.

A function definition can have only one ...restParam.

foo(...one, ...wrong, ...wrong)

The rest parameter must be the last parameter in the function definition.

foo(...wrong, arg2, arg3)
foo(arg1, arg2, ...correct)

Important: The rest parameters are Array instances, which means methods like sort, map, forEach or pop can be applied on it directly.

Example:

function showDetails(id, ...details){
  console.log(id);
  console.log(details);
}

showDetails(1, {id: 1, name: 'Ajay'});
showDetails(1, {id: 1, name: 'Ajay'}, {id: 2, name: 'Aman'});

Output:

1
[ { id: 1, name: 'Ajay' } ]
1
[ { id: 1, name: 'Ajay' }, { id: 2, name: 'Aman' } ]

ReactJS - Spread Operator

1. Passing React Props Using Spread Operator in JSX

function App() {
  return <User id="1" name="Ashok Kumar" />
}

By using spread operator, you can write this code like,

function App() {
  const user = {id: 1, name: 'Ashok Kumar'};

  return <User {...user} />
}

Inside User component you can get these values in props.

2. For setting state: first of all, we take a copy of data and then we make the changes and then pass this updated data to set state function.

this.setState(state => ({
  user: {
    ...state.userState,
    name: 'Anil Kumar'
  },
}));

Or

let userCopy = {...user};
userCopy.name = 'Anil Kumar';
this.setState(userCopy);

ReactJS - Rest Parameter

<User id={1} name={'Ajay'} customStyle={'some_property'}>Hello User</User>

const User = ({ customStyle, ...rest }) => {
  // Here customStyle will get some_property in it
  // Apart from customStyle all other props (id, name) 
  // will be available in rest
}

References: Spread syntax (...), Rest parameters

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.