4
When I try to merge two objects using the operator spread
conditionally, it works perfectly with both conditions 'true'
and 'false'
:
let condition1 = false;
let condition2 = true;
let obj1 = {
key1: 'value1'
};
let obj2 = {
key2: 'value2',
...(condition1 && obj1),
};
let obj3 = {
key3: 'value3'
};
let obj4 = {
key4: 'value4',
...(condition2 && obj3),
};
console.log(obj2); // {key2: 'value2'}
console.log(obj4); // {key4: "value4", key3: "value3"}
When I try to use the same logic with Arrays
, only works when the condition is true 'true'
:
let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];
console.log(arr2); // ['value2', 'value1']
If the condition is false 'false'
, an error will be cast:
let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];
console.log(arr2); // Error
Why behavior is different between Array
and Object
?
Running your code did not cause the error, try running: https://es6console.com/jvrzeln3/
– Thiago Krempser
@Thiagokrempser, interestingly the code does not generate any error in es6console.with, but this does not solve the question because in others it browsers/compilers generates.
– Cristiano Gilberto João