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

210
Views
Javascript var, let and function

    let x = '1'
    function first(){
        console.log(x)
    }
    x='2'
    function second(){
        let x='3'
        first()
    }
    second()

My question is , why is the answer '2' instead of '3'? I know let is block scope and var is function scope,but I just do not get this right. Please help me here, many thx!

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

0

You are assigning 3 to a local variable, it only has an effect inside the second function

This example works:

let x = '1'

function first(){
    console.log(x)
}

x='2'

function second(){
    x='3'
    first()
}

second()

about 4 years ago · Juan Pablo Isaza Report

0

initially the function first has no idea what x is about. so it automatically searched in the upper scope.

gladly, on the global scope there is x definition.

Therefore, as this script got initialized, the function console.log in function first reserve the memory address of x, and watches that global variable all along.

about 4 years ago · Juan Pablo Isaza Report

0

This is because of shadowing.

In JavaScript, variables with the same name can be specified at multiple layers of nested scope. In such a situation, local variables gain priority over global variables. If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function or block.

And in your case, there is no local variable define inside your first() function so it will take the value of x = 2 of the global variable.

let x = '1'

function first() {
  console.log(x)
}
x = '2'

function second() {
  let x = '3'
  first()
}
second()

See the below code, If you've declared x=4 inside first() then it will return the value 4 instead of 2

let x = '1'

function first() {
  x = '4'
  console.log(x)
}
x = '2'

function second() {
  let x = '3'
  first()
}
second()

Check out this if you want to know more about JavaScript Variable Scope and Hoisting: https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

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!