Search code examples
javascriptvariablesalertprompt

Assigning a value without declaring it first?


Can anyone please explain why we CAN assign a value without declaring it first. To my understanding we would need to declare a variable first (var visitorsName = prompt("Input your name: "). What is a visitorName if not variable? Thank you so much!

 visitor_name = prompt("Input your name : ");
 if(visitor_name !=null && visitor_name != ""){
   alert("Your name is: " + visitor_name);
 } else {
   alert("No Name User")
 }

Solution

  • When javascript was created, it was expected to be used for small scripts and often by novice programmers. As a result, it was designed to tolerate some sloppy coding practices. One of the ways it does this is that if you fail to declare your variable, it will create a global variable for you.

    When this line runs:

     visitor_name = prompt("Input your name : ");
    

    Javascript will create a property on the window object named visitor_name. And later on, any time you refer to visitor_name, since there's no other variable with that name, it will access window.visitor_name

    I recommend you avoid using this "feature" of javascript, and just declare your variables explicitly.