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

222
Views
Javascript arrow function weird behaviour with "this" keyword

This arrow function prints the concatenated string version of the array correctly:

var tahoe = {
  resorts: ["Kirkwood","Squaw","Alpine","Heavenly","Northstar"],
  print: function(delay=1000) {

    setTimeout(
      () => console.log(this.resorts.join(",")),
      delay
    )

  }
}

tahoe.print()

If I understand correctly, if I use a normal function inside the setTimeout, it will not work, because setTimeout requires a nested function that is aways evaluated in the global scope, while the array is defined within the scope of the object. So the arrow function is used which works in the scope of the object.

Then, how come putting the print function as arrow function as well reverses the problem again?

var tahoe = {
  resorts: ["Kirkwood","Squaw","Alpine","Heavenly","Northstar"],
  print: (delay=1000) => {

    setTimeout(() => {
      console.log(this.resorts.join(","))
    }, delay)

  }
}

tahoe.print()

This doesn't work. The book explains it like this:

enter image description here enter image description here

Can somebody explain what this means, and why it works like this? What is the exact difference between the two cases?

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