Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of this operator with three dots in my reducer?

My reducer looks like this:

export const setName = action => {
  return {
    type: "SET_NAME",
    ...action
  };
};

what are these 3 dots and reducer doing?


2 Answers

Spread syntax 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 with function:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));

Example with object

let a = {a: 1};
let b = {...a, b: 2};

console.log(b) //will print {a: 1, b: 2}

Think about it like unzipping one object into another.

More info

like image 114
Yochai Akoka Avatar answered Nov 26 '25 13:11

Yochai Akoka


Well, this is spread operator which preserves original object and adds new elements to new object. For example

var colors = ['red', 'green', 'blue'];
var refColors = [...colors, 'yellow'];
//colors=> ['red', 'green', 'blue']
//refColors => ['red', 'green', 'blue', 'yellow']
like image 40
Amit Naik Avatar answered Nov 26 '25 13:11

Amit Naik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!