0

Trying to get an understanding of hoisting in JS and can't seem to understand how hoisting and global/local variables are working in this simple function.

let x = 7;
function timesTwo(num){
    console.log("first ", x);
    x = num * 2;
    console.log("second " , x);
    return x;
    
}

timesTwo(2); // first  7
             // second  4
timesTwo(3); // first  4
             // second  6
             // 6

I know this is not a great way to write out the function. But why does the function not return a value the first time it is run, even though console.log seems to know what the x variable is, and then why is there a return the second time the function runs?

deeble
  • 3
  • 1
  • How do you know that nothing is returned? Your code doesn't do anything with the return of the function. Assign the return to a variable and console log it. – Randy Casburn Jan 25 '21 at 00:53
  • You're right. I ran the function in a variable printed the value and it does return the value. I just assumed the function would print the return value every time it was called. Would you know why the console only shows the return value of the function the last time it was run? – deeble Jan 25 '21 at 01:00
  • The console is asynchronous - so the output all gets blasted out at one time. – Randy Casburn Jan 25 '21 at 01:01
  • Actually there's no hoisting going on here, your function always manipulates and logs the global variable. – Bergi Jan 25 '21 at 01:31
  • @deeble The console just prints the result of the last statement that has been executed. If you write `timesTwo(2);` and hit enter, you'll get 4 printed. If you run `timesTwo(3);` alone afterwards, you'll get 6 printed. If you run all the code at once… – Bergi Jan 25 '21 at 01:34

0 Answers0