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

105
Views
Can anyone help me with this weird behaviour of var in javascript?

How does the fruit variable gets overwritten in the if block, but the color variable doesn't gets overwritten in the function block ?

var fruit = "apple";

if(fruit){
    var fruit = "mango";
    console.log(fruit); // mango
}

console.log(fruit); // mango

var color = "blue";

function displayColor(){
    var color = "red";
    console.log(color);
}

displayColor(); // red

console.log(color);  // blue
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The difference is the function creates a local scope. So it creates a variable in the function scope and discards it when the function is done, leaving the GLOBAL color variable untouched.

If statements dont make a scope, so your just redefining the fruit variable in global scope.

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!