Saturday 26 March 2016

ecmascript 6 - What "..." means in Javascript (ES6)?




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?


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...