Scope of variable in JavaScript

222
learning javascript basics kodementor

Variables are essential part of every programming language. So, you must understand the basics of variable before you dive into builiding application. In Javascript, you can define variable using var, let and const.

There are two types of scope in JavaScript. They are Local Scope and Global Scope. A global variable has global scope and a local variable has local scope. A Global variable is declared outside of any function whereas local variable is declared inside of a function.

A Global variable can be accessed from outside of the function as well as inside of the function but, a local variable can only be accessed only inside of the function. If accessed from outside of the function, you will get ‘undefined variable’ error.

Example

var foo = 50;  //<= Global variable

function myFunciton() {
    var bar = 100; //<= Local variable
}

More Advanced Example


First of all, getaverage function is called passing two variables which return average value of passed variable. Then, the return value is stored in myResult variable which is a glovbal variable. After this, logResult() function is called which displays the value stored in global variable.

You can learn more about loops in javascript in this article
You can learn more about javascript basics in this article

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.