codecademy: Introduction to Functions in JS Tutorial 10#
== Global and local Variable in JS ==
Let's talk about an important concept: scope. Scope can be global or local.
Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global.
For example:
var timesTwo = function(number) {
var my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};
timesTwo(7);
console.log("Outside the function my_number is: ")
console.log(my_number);
Out put:
Inside the function my_number is 14
Outside the function my_number is 7
== Global and local Variable in JS ==
Let's talk about an important concept: scope. Scope can be global or local.
Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global.
For example:
var globalVar = "hello";
var foo = function() {
console.log(globalVar); // prints "hello"
};
// The variable globalVar
can be accessed anywhere,
even inside the function foo
.
Variables defined inside a function are local variables.
They cannot be accessed outside of that function.
var bar = function() {
var localVar = "howdy";
}
console.log(localVar); // error
The var
keyword creates a new variable in the current scope.
That means if var
is used outside a function, that variable has a global scope.
If var
is used inside a function, that variable has a local scope.
var my_number = 7; //this has global scopevar timesTwo = function(number) {
var my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};
timesTwo(7);
console.log("Outside the function my_number is: ")
console.log(my_number);
Out put:
Inside the function my_number is 14
Outside the function my_number is 7
No comments:
Post a Comment