2

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.

Robin
  • 4,902
  • 2
  • 27
  • 43

2 Answers2

2

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

Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    got it now. It has been long time since I'm not working with vanilla js, so I forgot about the `window` object . – Robin Jul 31 '22 at 10:35
1

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.

JMP
  • 4,417
  • 17
  • 30
  • 41