Local variable and global variable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Local variable and global variable

local variable and global variable which different between them ?

9th May 2018, 1:11 PM
Arnab Chakma
Arnab Chakma - avatar
3 Answers
+ 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
9th May 2018, 1:30 PM
Zephyr Koo
Zephyr Koo - avatar
+ 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.
9th May 2018, 1:29 PM
apex137
apex137 - avatar
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) .
26th Jun 2018, 3:48 PM
Adnen Rebai
Adnen Rebai - avatar