+ 4
Local variable and global variable
local variable and global variable which different between them ?
3 ответов
+ 8
Global variable will be shared across different functions while local variable is accessible within the function scope only.
Here's an example for your reference:-
var a = 1; // global
function getValue2() {
var b = 2; // local
return b;
}
function getValue3() {
a = 3; // global
return a;
}
alert(a); // global
+ 2
Local variables can only be accessed in the function they are declared in. Global variables can be accessed anywhere within the program.
It is a good programming practice to use global variables as sparingly as possible, as to prevent these values from being touched too often by other functions.
0
gobal variable you can access it in console just when you declare it with var... mean if you have other file js in your project your variable can be overrided.... local variable declared inside a function ... to protect your variable from global scope use IIFE (Immediately Invoked Function Expression) .