Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Input value undefined when using var in javascript

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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

  • Using the variable "name" doesn't work with a JS object
  • var name produces strange result in Javascript

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

about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!