JS Variables

Overview

Variables are containers used to store data values in JavaScript. They play a crucial role in dynamic programming, allowing you to store, manipulate, and retrieve information.


Declaring Variables

In JavaScript, you can declare variables using three keywords: var, let, and const.

Try yourself
        
            var age = 25;       // Old way, less preferred now
let name = "John";   // Variable value can be changed
const PI = 3.14;     // Variable value is constant
        
    

Variable Naming

Try yourself
        
            let myVar;            // Valid variable name
let _myVariable;      // Valid variable name
let $count;           // Valid variable name
let _my_varible;      // Valid variable name
let my_2_variable;    // Valid variable name
let _my_variable_;    // Valid variable name
let 12my_variable_;   // InValid variable name
let .my_variable_;    // InValid variable name

        
    

Variable Types

JavaScript automatically determines the data type of variables. For example, if you assign a numerical value, JavaScript will recognize it as a number.

Try yourself
        
            let count = 10;          // Integer
let price = 19.99;       // Floating-point number
let name = "Alice";      // String
let isActive = true;     // Boolean
let ages = [25, 30, 35]; // Array
let nullVar = null;      // Null
let undefinedVar;        // Undefined
        
    

Variable Assignment

You can assign values to variables using the assignment operator (=).

Try yourself
        
            let age = 30;
let name = "John";
        
    

Reassigning Variables

Try yourself
        
            let score = 100;
document.getElementById("first").innerHTML = score;

score = 150;   // Reassigning 'score' with 'let'
document.getElementById("second").innerHTML = score;


const pi = 3.14;
pi = 3.14159;  // Error: Cannot reassign 'pi' with 'const'

        
    

Variable Scope

Variables in JavaScript have a scope limited to a specific code block. Variables declared with var have function scope, while those declared with let and const have block scope.

Global Scope

Variables declared outside of any function or code block have global scope. They are accessible from anywhere in the script, including within functions. Global variables exist as long as the web page or script is loaded.

Try yourself
        
            let globalVariable = "I am global";

function printGlobal() {
    console.log(globalVariable); // Accessible inside the function
}
printGlobal()
console.log(globalVariable); // Accessible outside the function
        
    

However, using excessive global variables can lead to potential issues, such as naming conflicts and difficulty in tracking changes.

Local Scope

Variables declared within a function or a code block have local scope. They are only accessible within that function or block. This helps in encapsulating variables and preventing unintended side effects.

Try yourself
        
            function printLocal() {
    let localVariable = "I am local"; // Local variable
    console.log(localVariable); // Accessible within the function
}

printLocal()

console.log(localVariable); // Throws an error - not accessible outside the function
        
    

Local variables are generally preferred because they minimize the risk of variable name clashes and promote better code organization.

Block-Level scoped variables

Starting from ES6 (ECMAScript 6), variables declared with let and const have block scope, meaning they are limited to the nearest enclosing block, whether it's a function, loop, or conditional statement.

Try yourself
        
            function exampleFunction() {
   if (true) {
      var x = 10; // Function-scoped variable
      let y = 20; // Block-scoped variable
      const z = 30; // Block-scoped variable
   }

   console.log(x); // Outputs 10, x is accessible due to function scope
   console.log(y); // Throws an error, y is not accessible outside the block
   console.log(z); // Throws an error, z is not accessible outside the block
}

exampleFunction();
        
    
Function-Level scoped variables

Function-level scope, which means it's accessible throughout the entire function in which it's declared.

Try yourself
        
            function exampleFunction() {
   if (true) {
      var x = 10; // Function-scoped variable
      let y = 20; // Block-scoped variable
      const z = 30; // Block-scoped variable
   }

   console.log(x); // Outputs 10, x is accessible due to function scope
   console.log(y); // Throws an error, y is not accessible outside the block
   console.log(z); // Throws an error, z is not accessible outside the block
}

exampleFunction();
        
    

Summary

Variables in JavaScript provide a way to store and manipulate data values. They come in different flavors (var, let, const) and have various scopes and behaviors.