DEV Community

Cover image for Variables in Js
Mahalakshmi C
Mahalakshmi C

Posted on

Variables in Js

Variable

  • A variable is a named container used to store data Values.
  • It is used for storing, retrieving, and manipulating data during program execution.

Rules for Naming Variables

  1. A variable name can contain letters, digits, _ (underscore), and $ (dollar sign).
  2. A variable name cannot start with a number.
  3. Variable names are case-sensitive(Age and age).
  4. We cannot use JavaScript reserved keywords as variable names. Example: var, let, const, if, for, etc.
  5. Use meaningful names that describe the stored data. Example: studentName is better than x.

Types of Variables in JavaScript

  1. var
  2. let
  3. const

Variable Declaration

  • Declaration means creating a variable by specifying its name using var, let, or const.
let age;
Enter fullscreen mode Exit fullscreen mode

Variable Initialization

  • Initialization means assigning a value to a variable for the first time.
let age = 22;
Enter fullscreen mode Exit fullscreen mode

Variable Reassignment

  • Reassignment means changing the existing value of a variable.
let age = 22;
age = 23;
Enter fullscreen mode Exit fullscreen mode

var

  • var is a keyword used to declare a variable in JavaScript.
  • It is the older way of declaring variables.
  • A variable declared using var can be redeclared and reassigned.
  • It is function-scoped, which means it is accessible throughout the function in which it is declared.
function student() {
    var name = "Laksh";     // Declaration + Initialization

    name = "Lakshmi";     // Reassignment

    var name = "Arun"; // Redeclaration

    console.log(name);  // Arun
}

console.log(name); // Error
Enter fullscreen mode Exit fullscreen mode

let

  • A variable declared using let can be reassigned, but it cannot be redeclared in the same scope.
  • It is block-scoped, which means it can be accessed only within the block { } where it is declared.
  • It was introduced in ES6 to overcome some limitations of var.
function student() {
    let name = "John";       // Declaration + Initialization

    name = "David";          // Reassignment

    let name = "Max";        // Error
    {
        let name = "Alex";   // New variable in another block
        console.log(name);   // Alex
    }

    console.log(name);       // David
}

student();
Enter fullscreen mode Exit fullscreen mode

const

  • A variable declared using const cannot be redeclared or reassigned in the same scope.
  • It is also block-scoped and It is used when the value of a variable should not be changed after initialization.
function student() {
    const name = "John";

    {
        const name = "David";
        console.log(name);    // David
    }

    console.log(name);       // John
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)