Skip to content

Local variable in JavaScript

  • by

In JavaScript, a local variable is a variable that is declared inside a function or block of code, and its scope is limited to that function or block. This means that the variable can only be accessed and used within that specific function or block of code.

// declaring a local variable using let
function myFunction() {
  let myVariable = "some value";
  // other code here
}

// declaring a local variable using const
function myOtherFunction() {
  const myConstant = "some value";
  // other code here
}

Local variables are created using the let or const keywords can only be accessed and used within the specific function or block where they are declared.

A local variable in JavaScript example

A simple example code declares and uses a local variable. It can be accessed and used within the function, but it is not defined outside of it, as shown by the ReferenceError that is thrown when trying to access it outside the function.

<!DOCTYPE html>
<html>
<body>
    <script>
        function myFunction() {
            let myVariable = "Hello, world!"; // declare a local variable
            console.log(myVariable);
        }

        myFunction();
        console.log(myVariable); // access Local Variable

    </script>
</body>
</html>

Output:

Local variable in JavaScript

Comment if you have any doubts or suggestions on this JS variable 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading