Skip to content

Types of variables in JavaScript

  • by

There are 3 Types of variables or ways to define them in JavaScript. The var, let and const keywords are used before the declare variables in JavaScript.

  1. var – It declares a variable globally or locally to an entire function. This type of variable is function-scoped.
  2. let – It declares a block-scoped variable that can be updated but not re-declared within the same block.
  3. const – Declare a block-scoped variable that cannot be updated or re-declared. This type of variable is read-only.

Types of variables in JavaScript example

Simple HTML example code.

<!DOCTYPE html>
<html>
<body>
<script>
    // var variable
    var x = 5;

    function foo() {
        var y = 10;
        console.log(x); 
        console.log(y);
    }

    // let variable
    let z = 15;

    if (true) {
        let z = 20;
        console.log(z);
    }

    console.log(z);

    // const variable
    const a = 0;

    // This will throw an error
    //a = 1;

    // This will also throw an error
    //const a = 2;

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

Output:

Types of variables in JavaScript

Rules while declaring a JavaScript variable

  1. Variable names must start with a letter, underscore (_), or dollar sign ($). They cannot start with a number.
  2. Variable names can contain letters, numbers, underscores, or dollar signs. No other characters are allowed.
  3. Variable names are case-sensitive, which means that “myVar” and “myvar” are two different variables.
  4. Avoid using JavaScript-reserved keywords as variable names.
  5. Always declare your variables with the var, let, or const keyword before using them. This will prevent errors and make your code more readable.
let firstName = "John";
const lastName = "Doe";
var age = 30;

JavaScript local variable vs global variable

Local variables are declared inside a function, and they can only be accessed within that function. Global variables, on the other hand, are declared outside any function, and they can be accessed from anywhere in the code, including inside functions.

local variable

function myFunction() {
  let x = 10; // local variable
  console.log(x); // Output: 10
}

myFunction();
console.log(x); // Output: Uncaught ReferenceError: x is not defined

global variable

let y = 20; // global variable

function myFunction() {
  console.log(y); // Output: 20
}

myFunction();
console.log(y); // Output: 20

Do 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