Asked 1 years ago
24 Apr 2023
Views 376
dilip

dilip posted

JavaScript - local vs global variable

what is difference between local vs global variable ?
ching

ching
answered Jun 29 '23 00:00

Global variables are variables which declared outside of function and it can be used at any function, so it can be used as global temp storage in entire execution program.

Local variables are variables which declared within a function and are only used within that function, it used as local use storage of that function.

Global variables Example ::

var g= 'i can be used anywhere inside or outside at function and i hold same block of memory';

function fun() {
  console.log(g);
}

fun();  

console.log(globalVar);  // Output: 'i can be used anywhere inside or outside at function and i hold same block of memory'


Local variables Example ::

 
function fun() {
var l='i am local';
  console.log(l);
}

fun();  

console.log(globalVar);  // Output: 'i am local'


lets use mix of the global and local variable

 var g='global'
function fun() {
var g='i am local';
   
}

fun();  

console.log(g);  // Output: 'global'


as you can see the global variable is never changed at function because it used as local variable so it will print global variable
rajiv

rajiv
answered Jun 29 '23 00:00

local variable have the scope of variables is limited.
Global variable available in the whole execution program.
Post Answer