Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What "..." means in Javascript (ES6)? [duplicate]

I am learning Redux, React and ES6. I already developed with JS, but this new world of ES6 are surprising me with a lot of new things like "=>" to declare arrow functions and other. However, in this new Redux studies, I confront with ... in middle of my code.

Bellow I have an example:

import { combineReducers, createStore } from 'redux'

const userReducer = (state={}, action) => {
    switch(action.type) {
        case 'CHANGE_NAME':
            state = {...state, name: action.payload};
            break;
        case 'CHANGE_AGE':
            state = {...state, age: action.payload};
            break;
    }
    return state;
};

const tweetsReducer = (state=[], action) => {
    return state;
};

const reducers = combineReducers ({
    user: userReducer,
    tweetsReducer: tweetsReducer,
});


const store = createStore(reducers);

store.subscribe(() =>
    console.log('The chage was: ', store.getState())
);

store.dispatch({type: 'CHANGE_NAME', payload: 'Will'})
store.dispatch({type: 'CHANGE_AGE', payload: 21});

If I replace
state = {...state, name: action.payload}; and
state = {...state, age: action.payload};
with
state.name = action.payload; and
state.age = action.payload;
it works, but the age was inserted into object together name and in first case the name was inserted and after age was inserted.

Why does it happen? How can I use ... in my future codes? Is it just in related with states?

like image 568
Aipi Avatar asked Jan 25 '17 21:01

Aipi


People also ask

What does ES6 mean in JavaScript?

JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer version of JavaScript that was introduced in 2015. ECMAScript is the standard that JavaScript programming language uses. ECMAScript provides the specification on how JavaScript programming language should work.


1 Answers

That's called the spread operator.

It unpacks values from an object or array, into another object or array. For example, using arrays:

a1  = [1, 2, 3]
a2  = [4, 5, 6]
a12 = [...a1, ...a2] // [1, 2, 3, 4, 5, 6]

The same semantics apply to objects:

o1  = { foo: 'bar' }
o2  = { bar: 'baz' }
o12 = { ...o1, ...o2 } // { foo: 'bar', bar: 'baz' }

You can use it to shallow-copy objects and arrays:

a = [1, 2, 3]
aCopy = [...a] // [1, 2, 3], on a new array

o = { foo: 'bar' }
oCopy = { ...o } // { foo: 'bar' }, on a new object

Check out the Mozilla docs, an excellent source for all things javascript.

like image 75
slezica Avatar answered Sep 20 '22 18:09

slezica