-2
//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?

  • 5
    If you declare the variable inside the function, then every time the function is called, you create a new variable. And you're initializing that variable to 1. If you declare it outside, then it's created only once. – Nicholas Tower Apr 26 '22 at 14:38
  • 5
    [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – 001 Apr 26 '22 at 14:38
  • 2
    Please do look the documentation on function scope, block scope and global scope in javascript. – bnays mhz Apr 26 '22 at 14:40

1 Answers1

0

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

Neil
  • 68
  • 6