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

148
Views
JavaScript running order questions

I have a very simple Javascript code, can't fully understand the running order and output.

function f1() {

    n = 999;

    change = function() {
        n = "Barry";
    };
    return change;

}

var result = f1();

result(); 
console.log(n)
change();
console.log(n)

Output:

Barry
Barry

As my understand, I define a globale variable n, and n = 999. Then I create a function which will define globale n to "Barry". and assign this function to change. and return this change variable.

Then I trigger this f1(), and give change to result. At this timepoint the change is a function but not runs yet.

So why the first Console.log return my Barry? Then change has not runs yet..

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

0

You are not properly declaring your variables in the scope with either var, let or const so it is polluting the global or outer scopes.

n is changed because result === change and change sets n to Barry.

about 4 years ago · Juan Pablo Isaza Report

0

The reason for this behavior is at this line ,

var result = f1(); // n - 999

At this point you are calling the inner function and setting the n to Barry

result(); // n - Barry

I am not sure how you calling this function directly. But hope it's just a pseudo code

change(); // n - Barry

Which means,

 result() === change()
about 4 years ago · Juan Pablo Isaza Report

0

why the first Console.log return my Barry? Then change has not runs yet..

Yes it has, you are only calling console.log after having called result(). Try the following:

var n, change;
function f1() {

    n = 999;

    change = function() {
        n = "Barry";
    };
    return change;

}

console.log(n);
var result = f1();
console.log(result === change);
console.log(n);
result(); 
console.log(n);
change();
console.log(n);

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!