Which method should we use in setState, push or concat? 【JS】
The return is different
These methods can add an item to an array, but the return is different. The return of push is the number of items while that of concat is an array. As a result, If you wrote codes below, it wouldn’t work like you expected .
this.state = {
array: ['a', 'b']
}this.setState({ array: newArray.push('c')}) this.state.array //=> 3
I intended to make a new array, but the return is number. If you want to return an array, you have to use concat method.
this.state = {
array: ['a', 'b']
}this.setState({ array: newArray.concat('c')
})this.state.array //=> ['a', 'b', 'c']
or
this.state = {
array: ['a', 'b']
}const newArray = newArray.push('c')this.setState({ array: newArray})this.state.array //=> ['a', 'b', 'c']
You can make the codes shorter with concat method. However, concat method produces array, it takes more time to finish than push method.
I measured it with console
var a = ["a", "b", "c", "d"], b = ["e","f","g","h"], i, count = 10000;
console.time();
for (i = 0; i < count; i++) {
a = a.concat(b);
}
console.timeEnd();//=> default: 1515.1328125ms
and
var a = ["a", "b", "c", "d"], b = ["e","f","g","h"], i, count = 10000;
console.time();
for (i = 0; i < count; i++) {
Array.prototype.push.apply(a, b);
}
console.timeEnd();// => default: 3.5419921875ms
As you can see, concat is so much slow.
Wrap up
・push: the execution is fast, but the codes become longer.
・concat: the execution is slow, but the codes become shorter.
My opinion is that we had better use push method. The longer code in this case is not a problem because there is not a big difference between them. However, the speed is clearly different, and not good for users.