Search code examples
javascripttype-coercion

Different Results when assigning an expression to a variable and running it in the JavaScript REPL environment


I am currently trying to develop a deeper understanding of JavaScript type coercion. While playing around with the node REPL environment, I encountered the statements []+{} and let x = []+{}. After executing the second statement, the variable x holds the value undefined, although I expected that the expression evaluates to '[object Object]' in both statements.

What causes this difference?


Solution

  • That's because let statement returns undefined, not variable value. To retrieve variable value, you have to type the variable name.

    let x = [] + {};
    // undefined
    x;
    // "[object Object]"