-2
 var a = 10
 function fun(){
     var b = 20
 }
fun()

In this code var a has global scope but var b dont have global scope but functional scope. But as fun() itself is global function which will be global to everywhere why var b is not global

Balkrushna
  • 41
  • 2
  • 9

2 Answers2

1

A variable declared outside a function becomes GLOBAL. Variables inside the Global scope can be accessed and altered in any other scope.

Global Scope:

// global scope
var a = 1;

function one() {
  alert(a); // alerts '1'
}

Local scope:

// global scope
var a = 1;

function two(a) { // passing (a) makes it local scope
  alert(a); // alerts the given argument, not the global value of '1'
}

// local scope again
function three() {
  var a = 3;
  alert(a); // alerts '3'
}

Global scope lives as long as your application lives. Local Scope lives as long as your functions are called and executed.

Here, b is inside a function so b is a local variable and it has a local scope, and a is a global variable and it lives when the application lives, and b lives when fun() lives.

mitesh7172
  • 666
  • 1
  • 11
  • 21
0

You have initialized the b variable inside fun() so that varaiable is global only inside that function, If you need to make the variable global which all the methods can us, You have to declare as global

var a = 10
var b = 0;
 function fun(){
     this.b = 20
 }
fun()
Googlian
  • 6,077
  • 3
  • 38
  • 44