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

182
Views
Explain the running result of this Javascript code?

const obj = {
    length:10,
    log() {
       console.log(this.length)
    }
}
obj.log() // 10

const length = 20
const fn = obj.log
fn() // 0

const arr = [30,obj.log]
arr[1]() // 2

Why the fn() result is 0 ? if use var length = 20 instead of const length = 20 the result is 20, how this happening?

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

0

the differences lies in what this means in the context of execution of the function log

in the first case this = obj so this.lenght = 10

in the second case this is the window object in the browser so if you use var or if you write window.length it returns the value you set

in the third case this means the array so it returns the array length

const obj = {
    length:10,
    log() {
       console.log(this.length)
    }
}
obj.log() // 10

const length = 20
const fn = obj.log
fn() // 0
window.length = 20
fn() // 20

const arr = [30,obj.log]
arr[1]() // 2

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!