Skip to content

Function scope and Block scope in JavaScript | Basics

  • by

Function scope and Block scope concepts are used with variable acceptability and availability. Function Scope variable is declared inside a function, it is only accessible within that function and cannot be used outside that function.

Block Scope variables declared inside the if statement or switch conditions block or inside for or while loops are accessible within that particular condition or loop. To be concise the variables declared inside the curly braces are called as within block scope.

There are also keywords are used:

The let and var are used to the scope of a variable defined with let are limited to the block in which it is declared while the variable declared with var has the global scope.

Function scope and Block scope in JavaScript example

Simple example code.

<!DOCTYPE html>

    // function scope
    function myFunction() {
      // Function Scope variables
      var car1 = "Volvo";  
      var car2 = "BMW";
      var car3 = "Tesla"; 



    // bock scope
      let x = 100;



Function scope and Block scope in JavaScript

Do comment if you have any doubts or suggestions on this JS scope topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *