Java Script
Back Next

JavaScript Varaibles


Variables in JavaScript are like containers that store information for later use. They allow you to save data, reuse it, and manipulate it dynamically in your programs.

Think of a variable as a labeled box: you can put data inside it, change it, and access it whenever you need.


1️⃣ Declaring Variables

There are three main ways to declare variables in JavaScript:

1. let (Modern, block-scoped)

let name = "Alice"; // Stores the string "Alice"
let age = 25;       // Stores the number 25
  • Can change the value later
  • Scope is block-level (inside { } only)

2. const (Constant, cannot be changed)

const pi = 3.1416; // Cannot reassign value later
  • Used for values that should not change
  • Trying to change a const value will cause an error

3. var (Older, function-scoped)

var city = "Paris";
  • Older syntax, still works
  • Scope is function-level, which can sometimes cause unexpected behavior
  • Avoid using var in modern code


2️⃣ Variable Naming Rules

  1. Names cannot start with a number
  2. Names can include letters, numbers, $, or _
  3. Names cannot contain spaces or special characters
  4. Names are case-sensitive

Valid Examples:

let userName;
let $price;
let _age;
let totalCount;

Invalid Examples:

let 1stName; // Cannot start with number
let user-name; // Cannot use hyphen


3️⃣ Data Types Stored in Variables

JavaScript variables can store different types of data:

let name = "Alice";      // String
let age = 25;            // Number
let isStudent = true;    // Boolean
let colors = ["red","blue","green"]; // Array
let person = {name:"Alice", age:25}; // Object
let empty = null;        // Null
let notDefined;          // Undefined
  • Strings → Text
  • Numbers → Integer or Decimal
  • Boolean → true / false
  • Array → Collection of values
  • Object → Key-value pairs


4️⃣ Changing Variable Values

Variables declared with let or var can be reassigned:

let age = 20;
age = 25; // New value
console.log(age); // 25

const cannot be reassigned:

const pi = 3.14;
pi = 3.1416; // ❌ Error: Cannot reassign constant


5️⃣ Using Variables in Operations

Variables can be used in mathematical operations or string concatenation:

let x = 10;
let y = 5;

console.log(x + y); // 15
console.log(x - y); // 5

let firstName = "Alice";
let lastName = "Smith";
console.log(firstName + " " + lastName); // Alice Smith


Compilation of Entire Code

Explanation:

  • Variables userName, age, and pi are declared
  • Clicking the button updates the paragraph dynamically using these variables
  • age is incremented inside the function to show that variables can change


Example Code:
<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Variables Example</title>
  <style>
    body { font-family: Arial; padding: 20px; }
    button { padding: 10px 20px; margin: 5px; cursor: pointer; }
    p { font-size: 18px; color: darkgreen; }
  </style>
</head>
<body>

  <h1>JavaScript Variables Demo</h1>

  <p id="demo">Your message will appear here.</p>
  <button onclick="showMessage()">Click Me</button>

  <script>
    // Variable declaration
    let userName = "Alice";
    let age = 25;
    const pi = 3.1416;

    // Function using variables
    function showMessage() {
      document.getElementById("demo").innerHTML = 
        "Hello, " + userName + "! You are " + age + " years old. Pi is " + pi;
      
      // Changing variable value
      age += 1; // Increment age by 1
      console.log("Updated age:", age);
    }
  </script>

</body>
</html>
Java Script
Introduction Application of JavaScript Defining JavaScript Client-Side JavaScript JavaScript Syntax JavaScript Varaibles JavaScript Operators JavaScript Statements JavaScript Arrays Sorting JavaScript Array JavaScript Functions JavaScript Objects JavaScript Switch Case & While Loops JavaScript For & For-In Loops JavaScript Cookies JavaScript Form Validation JavaScript Error and Exception Handling JavaScript Animation
All Courses
Bootstrap Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel HTML Java Script Machine Learning MySQLi PHP Power Bi Python for Analysis SEO SMM SQL