Search code examples
javascriptspread-syntax

I don't understand about spread syntax inside objects


I don't understand about spread syntax inside objects.

console.log(...false) // TypeError not iterable
console.log(...1) // TypeError not iterable
console.log(...null) // TypeError not iterable
console.log(...undefined) // TypeError not iterable

I understand above codes that occurs error because of none-iterator.

But these codes are working well.

console.log({...false}) // {}
console.log({...1}) // {}
console.log({...null}) // {}
console.log({...undefined}) // {}

Please let me know why the above codes are working.


Solution

  • The object spread is quite different. It maps to Object.assign() internally.

    So const a = {...1} is same as const a = Object.assign({}, 1) Here Object.assign({},1) has treated 1 as object not as number. Therefore, you did not get any exception thrown.

    Additionally if you have tried same thing for arrays [...1] it should have thrown error, since it does not treats 1 as object and you get the same behavior as ..1.

    To summarize:

    console.log({...false}) => console.log(Object.assign({}, false))
    console.log({...1}) => console.log(Object.assign({}, 1))
    console.log({...null}) => console.log(Object.assign({}, null))
    console.log({...undefined}) => console.log(Object.assign({}, undefined))
    

    PS: Object.assign() spec