-1

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
ebv
  • 9
  • 4

1 Answers1

0

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
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • Thank you @Shidersz this answer certainly meets the condition. Could you please explain whats happening or point to a resource where I can read about it. Also do you know other cases when this condition is met? – ebv Feb 18 '19 at 20:37
  • while this certainly "works", it has absolutely zero practical value. What is the point of trying to compare if `x` isn't the same as itself, if you are so desperate to prove it that you go to the point of not even caring what the value of `x` even is? – Claies Feb 18 '19 at 20:41
  • @ebv Sure, you can found a lot of explanations here: https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true. But you need to read about [Javascript coercion](https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839) too. – Shidersz Feb 18 '19 at 20:43
  • @Claies I agree with you, this sound more like an interview question. – Shidersz Feb 18 '19 at 20:45