Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

global and function scope javascript

//This seems confusing, but if you understamd this, You are strong in hoisting
//this helps confusion b/w (gobal var, function's local var) & execution context

var a = 8; // global var has - 8

function A(){
	var a = 1;
	console.log(a); // 1
	function B(){
		var b = 3;
		a = 77; // replaces A()'s "a" value to 77 but (not the outer var a=8)
		console.log(a,b); // 77,3
		function C(){
			var a = 99;
			b = 1; //replaces "b" to outer B()func so B()'s "b" is 1 now
			c = 98; //globally available
			console.log(a,b,c); // 99,1,98
		}
	C();
	console.log(a,b,c); // 77,1,98
	}
B();
console.log(`a is : ${a}`); //77
};


console.log(`Initially 'a' is : ${a}`); //8
A();
console.log(`now 'a' is : ${a} - outer as global`); //8


//output
//global
	//8
//A
	//1
//B
	//77,3
//A
	//77
//C
	//99,1,98
	//77,1,98
//global
	//8 - outer global variable
 
PREVIOUS NEXT
Tagged: #global #function #scope #javascript
ADD COMMENT
Topic
Name
8+2 =