Input value undefined when using var in javascript

Viewed 60

Here is my code

var form = document.querySelector('form');
var name = form.querySelector('div #name');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  console.log(name.value); // undefined
})
<form>
  <div>
    <input id="name" />
  </div>
  <div>
    <input type="submit" id="submit" />
  </div>
</form>

console.log prints undefined if I use var when declaring name. But prints the actual value if I use const instead of var.

const name = form.querySelector('div #name');

I guess it's a hoisting problem, but can't understand why it's happening. Anyone please explain why it's not working while using var.

2 Answers

That's indeed weird at first, but after reading other questions:

I found a solution

For compatibility reasons using var in a global scope assigns a variable as a property of the global window object. So var name = ... is equal to window.name = ...

window.name is a special property that can only be a string, so var name = form.querySelector('div #name'); converts HTML element to string. You can check this by running typeof name.

Hence you can't access the properties of the HTML element.

Another reason to always use const or let

Using var assigns the variable to the window object, and is therefore equivalent to:

 window.name = form.querySelector('div #name');

and the result is cast to a string, and strings don't have any properties, hence undefined.

const doesn't assign to window(MDN), and so name is assigned as the element.

Related