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

189
Views
JavaScript: Order in which variable assignment takes place

I'm new to JavaScript and would like to understand the order in which variable assignment takes place. Let's assume I have the following toy example:

var foo = document.sentence.split(',');

Do we split the sentence first, then assign the output of split to the foo variable? Or, do we first create the foo variable, and then assign the output of document.sentence.split(',') to foo?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

With var things are a little different, because of hoisting.

Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.

However JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.

Example:

'option strict';
function myFunction() {
  console.log(foo);
  // => undefined
  var sentence = 'my,array,of,strings';
  var foo = sentence.split(',');
  console.log(foo);
  // => ['my', 'array', 'of', 'strings']
}
myFunction();

On the first console.log(foo) we didn't get a Uncaught ReferenceError: foo is not defined error. That's what would normally happen if we tried to access a variable that hadn't been declared yet.

If we try the same thing using const (or let), we get a different response:

'option strict';
function myFunction() {
  console.log(foo);
  // => Uncaught ReferenceError: Cannot access 'foo' before initialization
  const sentence = 'my,array,of,strings';
  const foo = sentence.split(',');
  console.log(foo);
  // => ['my', 'array', 'of', 'strings']
}
myFunction();

about 4 years ago · Juan Pablo Isaza 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!