javascriptuse-strict

With "use strict" enabled, why can I assign a variable without let while using prompt()


I wrote "use strict"; at the top of my script.

I can't write num = 5; because I get ReferenceError: Can't find variable: num.

To fix this I can write let num = 5;.

Using that logic, why am I allowed to write name = prompt("What is your name?");?

Shouldn't I have to write let name = prompt("What is your name?")?


Solution

  • Assuming that you're running this in the browser, you're seeing this behavior because of the window.name property. You're second example is storing the value returned by prompt in this property.

    If window had a built-in num property your first example would work as well.

    Of course, in actual code you'd want to create a variable to store the prompt value rather than clobbering window.name.