Angular what's the meaning of these three dots in @NGRX

AngularNgrx

Angular Problem Overview


What do these three dots mean exactly, and why do I need them?

export function leadReducer(state: Lead[]= [], action: Action {
    switch(action.type){
        case ADD_LEAD:
            return [...state, action.payload];
        case REMOVE_LEAD:
            return state.filter(lead => lead.id !== action.payload.id )
}
}

Angular Solutions


Solution 1 - Angular

The three dots are known as the spread operator from Typescript (also from ES7).

The spread operator return all elements of an array. Like you would write each element separately:

let myArr = [1, 2, 3];
return [1, 2, 3];
//is the same as:
return [...myArr];

This is mostly just syntactic sugar as it compiles this:

func(...args);

to this:

func.apply(null, args);

In your case this gets compiled to this:

return [...state, action.payload];
//gets compiled to this:
return state.concat([action.payload]);

Solution 2 - Angular

It is a spread operator (...) which is used for spreading the element of an array/object or for initializing an array or object from another array or object.

Let's create new array from existing array to understand this.

> let Array1 = [ 1, 2, 3]; //1,2,3 > > let Array2 = [ 4, 5, 6]; //4,5,6 > > //Create new array from existing array > > let copyArray = [...Array1]; > //1,2,3 > > //Create array by merging two arrays > > let mergedArray = [...Array1, ...Array2]; //1,2,3,4,5,6 > > //Create new array from existing array + more elements > > let newArray = [...Array1, 7, 8]; //1,2,3,7,8

Solution 3 - Angular

The ...(spread operator) works by returning each value from index 0 to index length-1:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnouar MokhtariView Question on Stackoverflow
Solution 1 - AngularSpitzbuebView Answer on Stackoverflow
Solution 2 - AngularShwetaView Answer on Stackoverflow
Solution 3 - AngularRahul SinghView Answer on Stackoverflow