JavaScript tutorials for Beginners – JavaScript Variable Scope

Hits: 19

 

(JavaScript Tutorials for Beginners)

In this end-to-end example, you will learn – JavaScript tutorials for Beginners – JavaScript Variable Scope.

JavaScript Variable Scope

In this tutorial, you will learn about the variable scope in JavaScript with the help of examples.

Scope refers to the availability of variables and functions in certain parts of the code.

In JavaScript, a variable has two types of scope:

  1. Global Scope
  2. Local Scope

Global Scope

A variable declared at the top of a program or outside of a function is considered a global scope variable.

Let’s see an example of a global scope variable.

// program to print a text 
let a = "hello";

function greet () {
    console.log(a);
}

greet(); // hello

In the above program, variable a is declared at the top of a program and is a global variable. It means the variable a can be used anywhere in the program.


The value of a global variable can be changed inside a function. For example,

// program to show the change in global variable
let a = "hello";

function greet() {
    a = 3;
}

// before the function call
console.log(a);

//after the function call
greet();
console.log(a); // 3

In the above program, variable a is a global variable. The value of a is hello. Then the variable a is accessed inside a function and the value changes to 3.

Hence, the value of a changes after changing it inside the function.

Note: It is a good practice to avoid using global variables because the value of a global variable can change in different areas in the program. It can introduce unknown results in the program.


In JavaScript, a variable can also be used without declaring it. If a variable is used without declaring it, that variable automatically becomes a global variable.

For example,

function greet() {
    a = "hello"
}

greet();

console.log(a); // hello

In the above program, variable a is a global variable.

If the variable was declared using let a = "hello", the program would throw an error.

Note: In JavaScript, there is "strict mode"; in which a variable cannot be used without declaring it. To learn more about strict, visit JavaScript Strict.


Local Scope

A variable can also have a local scope, i.e it can only be accessed within a function.

Example 1: Local Scope Variable

// program showing local scope of a variable
let a = "hello";

function greet() {
    let b = "World"
    console.log(a + b);
}

greet();
console.log(a + b); // error

Output

helloWorld
Uncaught ReferenceError: b is not defined

In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet. Hence, when we try to access variable b outside of the function, an error occurs.


let is Block Scoped

The let keyword is block-scoped(variable can be accessed only in immediate block).

Example 2: block-scoped Variable

// program showing block-scoped concept
// global variable
let a = 'Hello';

function greet() {

    // local variable
    let b = 'World';

    console.log(a + ' ' + b);

    if (b == 'World') {

        // block-scoped variable
        let c = 'hello';

        console.log(a + ' ' + b + ' ' + c);
    }

    // variable x cannot be accessed here
    console.log(a + ' ' + b + ' ' + c);
}

greet();

Output

Hello World
Hello World hello
Uncaught ReferenceError: x is not defined

In the above program, variable

  • a is a global variable. It can be accessed anywhere in the program.
  • b is a local variable. It can be accessed only inside the function greet.
  • c is a block-scoped variable. It can be accessed only inside the if statement block.

Hence in the above program, the first two console.log() work without any issue.

However, we are trying to access the block-scoped variable c outside of the block in the third console.log(). This will throw an error.


Note: In JavaScript, var is function scoped and let is block-scoped. If you try to use var c = 'hello'; inside the if statement in the above program, the whole program works, as c is treated as a local variable.

To learn more about let versus var, visit JavaScript let vs var.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!