JavaScript scope of variables

 JavaScript scope of variables

In JavaScript, the scope of a data type, refers to the visibility of that particular type.
But, for starters let's look at the scope of a variable.
A variable, once declared is globally accessible to the whole JS file.
If you want to limit it to a specific block, declare it within a function



Let's declare a variable.

var price = 25;

The price variable is now visible across the file. But, lets assume, we want to override the value of price which is 25 to 20 for a special sale that's currently running. Now, we have a issue to address. If we access the price variable the value is always 25. Let's fix this by creating a function and declare the variable locally.

function discountForMay(){
var price = 20;
console.log(price);
}
discountForMay();
console.log(price);

Now, try to understand this, the price is 25 in global scope. Inside the function the value is 20.
If you look at the result, it show's 20, and then 25. 

As you can see, the local instance of var variable, which is inside the function always takes precedence over the global var variable. 

You should also know that the variables declared within function are not accessible outside the function block. If it was a different variable, it'd throw an error. Try it for yourself. I made up this very example to demonstrate the scope of JavaScript variable.

In case you ever want to get the values out of the function, you can return them. Let's see how this is done. The result in this case is 9.

function squareIt(a){
return a*a; // Squares a number
}
var returnedValue = squareIt(3);
undefined
console.log(returnedValue);

Awesome, we are through this lesson. If you have any doubts ask.



Post a Comment

0 Comments

React