'What is the difference between declaring a variable within and outside a function?

//I have written the below code in JS.

var output = [];
var num =1 ;
function fizzBuzz(){
    var a = output.push(num);
    num ++;
    console.log(output);
}

// Each time I call the function the values are incremented by 1. So the output is:

fizzBuzz();
[1]
fizzBuzz();
[1,2]
fizzBuzz();
[1,2,3]

// And so on:

// However when I write the code like this:

var output = [];
function fizzBuzz(){
    var num =1 ;
    var a = output.push(num);
    num ++;
    console.log(output);
}

// The output is different.

fizzBuzz();
[1]
fizzBuzz();
[1,1]
fizzBuzz();
[1,1,1]

// and so on.

// May I know the logic behind this?



Solution 1:[1]

This would be a variable scope topic, and it is best to check out "variable scope" and "global scope".

In your first example, this is considered a "global variable scope."

var output = []; // output variable declared in global scope.
var num =1 ; // num variable declared in global scope.
function fizzBuzz(){
  var a = output.push(num); // a variable declared in function scope.
  num ++;
  console.log(output);
}

output and the num are available and their respective values are still stored every time you call fizzBuzz. That is why you are getting [1, 2, 3] as values.

the second example can be considered as a function scope. Every time you call fizzBuzz, you are always creating a new num variable and setting it to 1. Hence the result [1, 1, 1]

See more: https://developer.mozilla.org/en-US/docs/Glossary/Scope

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neil