Search code examples
javascriptcoerciontemplate-literals

JavaScript template literals and implicit coercion


What value should be assigned to "x" in order to meet the following condition:

// let x = ?; 

console.log(`${x}` != '' + x) // true
console.log(`${x}` !== '' + x) // true

Solution

  • Something like this can work, but it is tricky, the method toString() of the x object changes his internal state on every call and returns it. This happens because of the implicit coercion that takes effect when trying to cast x to a string (it will use the toString() method of the object if found).

    let x = {
      counter: 1,
      toString: () => x.counter++
    }
    
    console.log('' + x);
    console.log(`${x}`);
    
    console.log(`${x}` != '' + x) // true
    console.log(`${x}` !== '' + x) // true