|

JavaScript 4 🧬 Variables

Variables are containers for storing data values. They allow you to refer back to those values by an assigned name, and you can manipulate or access them throughout your code execution.


A Quick Look at Variables

// String
let greeting = 'Hello, World!';
let name = "Alice";

// Number
let age = 30;
let height = 5.9;
let population = 7_891_024_000; // Numeric separators for readability

// Boolean
let isStudent = true;
let isLoggedIn = false;

// Undefined
let x;

// Null
let y = null;

// Symbol
const id1 = Symbol('id');

// BigInt
const bigIntExample = BigInt(999_999_999_999_999_999);
const anotherBigInt = 1234567890123456789012345678901234567890n;

// Object
let person = {
    name: 'Bob',
    age: 25,
    greet: function() {
        return "Hello, my name is " + this.name;
    }
};

// Array
let fruits = ['apple', 'banana', 'cherry'];

// Function
function multiply(a, b) {
    return a * b;
}

a. JavaScript Variable Declaration (1 of 2)

Variables in JavaScript are used to store and manage data. This data can be manipulated or accessed during code execution. They act as containers for values and allow you to refer back to these values by their assigned name.

You can declare and initialize their value at the same time (or separately).

JavaScript has 3 kinds of declaration:

KeywordScopeReassignable?Hoisted?Introduced
varFunction / Global✅ Yes✅ Yes (initialized as undefined)ES1
letBlock✅ Yes⚠️ Yes (but not initialized — TDZ)ES6
constBlock❌ No⚠️ Yes (but not initialized — TDZ)ES6

The var Keyword

The oldest way to declare a variable. Variables declared with var have function scope or global scope.

They are also hoisted — meaning they are moved to the top of the containing scope during execution.

// var is function-scoped
function example() {
    if (true) {
        var x = 10;
    }
    console.log(x); // 10 — accessible outside the block!
}
example();

// var is hoisted
console.log(y); // undefined (not an error!)
var y = 5;

Why avoid var?

  • Function scope can lead to bugs (variables “leaking” out of blocks)
  • Hoisting can cause confusing behavior
  • let and const are more predictable

b. JavaScript Variable Declaration (2 of 2)

The let Keyword

Allows block-scoped variables. Variables are accessible only within the block, statement, or expression where they are defined. Introduced in ES6.

// let is block-scoped
function example() {
    if (true) {
        let x = 10;
        console.log(x); // 10
    }
    // console.log(x); // ReferenceError: x is not defined
}
example();

// let can be reassigned
let count = 0;
count = 1; // ✅ OK
count = 2; // ✅ OK

The const Keyword

Used to declare constants — variables that cannot be reassigned after their initial assignment. Introduced in ES6.

Constants must be initialized at the time of declaration.

const also declares block-scoped local variables.

// const must be initialized
const PI = 3.14159; // ✅ OK
// const TAX;        // ❌ SyntaxError: Missing initializer

// const cannot be reassigned
const name = "Alice";
// name = "Bob"; // ❌ TypeError: Assignment to constant variable

// But const objects/arrays can be mutated
const person = { name: "Alice" };
person.name = "Bob"; // ✅ OK — mutating the object, not reassigning

const colors = ["red", "green"];
colors.push("blue"); // ✅ OK — mutating the array

// colors = []; // ❌ TypeError: Assignment to constant variable

Naming Rules for Variables

Variables can only contain:

  • Letters (both uppercase and lowercase): a-z, A-Z
  • Digits: 0-9
  • Underscores: _
  • Dollar signs: $

Rules:

  • ✅ Variables cannot start with a digit1name is invalid; name1 is valid
  • ✅ JavaScript is case-sensitivemyVar, MyVar, and MYVAR are three different variables
// Valid names
let name = "Alice";
let _private = "hidden";
let $price = 9.99;
let user123 = "Bob";
let camelCase = "common";
let PascalCase = "class-like";
let snake_case = "underscore";
let kebabCase = "not valid"; // ❌ (kebab-case not allowed in JS)

// Invalid names
// let 123name = "x";  // ❌ Cannot start with digit
// let my-var = "x";   // ❌ Hyphen not allowed
// let my var = "x";   // ❌ Space not allowed
// let class = "x";    // ❌ Reserved keyword

c. JavaScript Types of Data

Variables in JavaScript can hold various types of data, divided into Primitive Types and Reference Types.

Primitive Types (Immutable, Stored by Value)

TypeExampleDescription
Booleantrue or falseLogical true/false
String'hello world'Text enclosed in quotes
Number1978, 3.14Integer or floating-point
undefinedlet x;Variable declared but not assigned
nulllet y = null;Intentional absence of value
BigInt124312435423543645nArbitrarily large integers
SymbolSymbol('id')Unique and immutable identifiers
// Primitive types
let isActive = true;                    // Boolean
let message = "Hello";                  // String
let score = 98.6;                       // Number
let notAssigned;                        // undefined
let empty = null;                       // null
let bigNumber = 12345678901234567890n;  // BigInt
let uniqueId = Symbol('id');            // Symbol

Reference Types (Mutable, Stored by Reference)

TypeExampleDescription
Object{ name: 'Bob', age: 25 }Collections of key-value pairs
Array['apple', 'banana']Lists of values under one name
Functionfunction add(a, b) { }Reusable blocks of code
// Reference types
let person = {
    name: 'Bob',
    age: 25,
    greet: function() {
        return "Hello, my name is " + this.name;
    }
};

let fruits = ['apple', 'banana', 'cherry'];

function multiply(a, b) {
    return a * b;
}

Primitive vs Reference — Key Difference

// Primitives — copied by value
let a = 10;
let b = a; // b gets a copy of 10
b = 20;
console.log(a); // 10 — unchanged

// References — copied by reference
let obj1 = { name: "Alice" };
let obj2 = obj1; // obj2 references the SAME object
obj2.name = "Bob";
console.log(obj1.name); // "Bob" — changed!

d. JavaScript Variable Scope

JavaScript variables can belong to one of three scopes:

ScopeDescriptionAccessible From
Global ScopeDeclared outside any function or blockEverywhere in the script
Function ScopeDeclared inside a functionOnly within that function
Block ScopeDeclared inside a block { }Only within that block

Global Scope

Variables declared outside any function or block are global. They are accessible throughout the entire script.

let globalVar = "I am global";

function showGlobal() {
    console.log(globalVar); // ✅ Accessible
}

showGlobal(); // "I am global"
console.log(globalVar); // ✅ Accessible

Function Scope

Variables declared inside a function are only accessible within that function.

function myFunction() {
    let functionScoped = "I am inside";
    console.log(functionScoped); // ✅ Accessible
}

myFunction();
// console.log(functionScoped); // ❌ ReferenceError: not defined

Block Scope

Variables declared inside a block { } are only accessible within that block.

Blocks include:

  • switch statements
  • try...catch statements
  • for statements
  • Function bodies
  • Static initialization blocks
{
    let blockScoped = "I am in a block";
    const alsoBlockScoped = "Me too";
    console.log(blockScoped); // ✅ Accessible
}

// console.log(blockScoped); // ❌ ReferenceError: not defined

// for loop creates a block
for (let i = 0; i < 3; i++) {
    console.log(i); // ✅ Accessible inside the loop
}
// console.log(i); // ❌ ReferenceError: not defined

// if block
if (true) {
    let insideIf = "Hello";
    console.log(insideIf); // ✅ Accessible
}
// console.log(insideIf); // ❌ ReferenceError: not defined

Scope Comparison

┌─────────────────────────────────────────────────┐
│                GLOBAL SCOPE                     │
│  let global = "I am global";                    │
│                                                 │
│  ┌───────────────────────────────────────────┐  │
│  │         FUNCTION SCOPE                    │  │
│  │  function foo() {                         │  │
│  │    let funcVar = "function scoped";       │  │
│  │                                           │  │
│  │    ┌─────────────────────────────────┐    │  │
│  │    │      BLOCK SCOPE                │    │  │
│  │    │  if (true) {                    │    │  │
│  │    │    let blockVar = "block";      │    │  │
│  │    │  }                              │    │  │
│  │    └─────────────────────────────────┘    │  │
│  │  }                                        │  │
│  └───────────────────────────────────────────┘  │
└─────────────────────────────────────────────────┘

var vs let vs const — Scope Comparison

function scopeTest() {
    if (true) {
        var varVar = "var — function scoped";
        let letVar = "let — block scoped";
        const constVar = "const — block scoped";
    }

    console.log(varVar);   // ✅ "var — function scoped"
    // console.log(letVar);   // ❌ ReferenceError
    // console.log(constVar); // ❌ ReferenceError
}
scopeTest();

Complete Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Variables</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }
        h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
        h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
        .demo-box {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin: 15px 0;
        }
        pre {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            line-height: 1.8;
        }
        .keyword { color: #569cd6; }
        .string { color: #ce9178; }
        .number { color: #b5cea8; }
        .function { color: #dcdcaa; }
        .comment { color: #6a9955; }
        .boolean { color: #569cd6; }
        #output {
            background: #e9ecef;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            min-height: 40px;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            border-left: 4px solid #007bff;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>

    <h1>JavaScript Variables</h1>

    <div class="demo-box">
        <h2>1. Variable Declarations</h2>
        <pre>
<span class="comment">// String</span>
<span class="keyword">let</span> greeting = <span class="string">'Hello, World!'</span>;
<span class="keyword">let</span> name = <span class="string">"Alice"</span>;

<span class="comment">// Number</span>
<span class="keyword">let</span> age = <span class="number">30</span>;
<span class="keyword">let</span> height = <span class="number">5.9</span>;

<span class="comment">// Boolean</span>
<span class="keyword">let</span> isStudent = <span class="boolean">true</span>;

<span class="comment">// undefined</span>
<span class="keyword">let</span> notAssigned;

<span class="comment">// null</span>
<span class="keyword">let</span> empty = <span class="boolean">null</span>;

<span class="comment">// BigInt</span>
<span class="keyword">const</span> bigNumber = <span class="number">12345678901234567890n</span>;

<span class="comment">// Symbol</span>
<span class="keyword">const</span> id = <span class="function">Symbol</span>(<span class="string">'id'</span>);
        </pre>
    </div>

    <div class="demo-box">
        <h2>2. var vs let vs const</h2>
        <pre>
<span class="comment">// var — function-scoped, can be reassigned</span>
<span class="keyword">var</span> oldWay = <span class="string">"old"</span>;
oldWay = <span class="string">"changed"</span>; <span class="comment">// ✅ OK</span>

<span class="comment">// let — block-scoped, can be reassigned</span>
<span class="keyword">let</span> modern = <span class="string">"modern"</span>;
modern = <span class="string">"changed"</span>; <span class="comment">// ✅ OK</span>

<span class="comment">// const — block-scoped, cannot be reassigned</span>
<span class="keyword">const</span> fixed = <span class="string">"fixed"</span>;
<span class="comment">// fixed = "changed"; // ❌ TypeError</span>
        </pre>
    </div>

    <div class="demo-box">
        <h2>3. Data Types</h2>
        <pre>
<span class="comment">// Primitive types</span>
<span class="keyword">let</span> isActive = <span class="boolean">true</span>;        <span class="comment">// Boolean</span>
<span class="keyword">let</span> message = <span class="string">"Hello"</span>;       <span class="comment">// String</span>
<span class="keyword">let</span> score = <span class="number">98.6</span>;            <span class="comment">// Number</span>
<span class="keyword">let</span> notSet;                    <span class="comment">// undefined</span>
<span class="keyword">let</span> nothing = <span class="boolean">null</span>;         <span class="comment">// null</span>
<span class="keyword">let</span> bigInt = <span class="number">123n</span>;            <span class="comment">// BigInt</span>
<span class="keyword">let</span> sym = <span class="function">Symbol</span>(<span class="string">'id'</span>);      <span class="comment">// Symbol</span>

<span class="comment">// Reference types</span>
<span class="keyword">let</span> person = {                 <span class="comment">// Object</span>
    name: <span class="string">'Bob'</span>,
    age: <span class="number">25</span>
};

<span class="keyword">let</span> fruits = [<span class="string">'apple'</span>, <span class="string">'banana'</span>]; <span class="comment">// Array</span>

<span class="keyword">function</span> <span class="function">multiply</span>(a, b) {        <span class="comment">// Function</span>
    <span class="keyword">return</span> a * b;
}
        </pre>
    </div>

    <div class="demo-box">
        <h2>4. Live Output — Data Types</h2>
        <p>Open the console (F12) and check the output below:</p>
        <div id="output">Loading...</div>
    </div>

    <script>
        // ============================================
        // JavaScript Variables — Live Demo
        // ============================================

        // Different data types
        let greeting = 'Hello, World!';
        let age = 30;
        let height = 5.9;
        let isStudent = true;
        let notAssigned;
        let empty = null;
        let bigNumber = 12345678901234567890n;
        let uniqueId = Symbol('id');

        // Objects and arrays
        let person = { name: 'Bob', age: 25 };
        let fruits = ['apple', 'banana', 'cherry'];

        // Function
        function multiply(a, b) {
            return a * b;
        }

        // Build output string
        let output = '📋 Variable Types:\n\n';
        output += 'greeting: ' + typeof greeting + ' → ' + greeting + '\n';
        output += 'age: ' + typeof age + ' → ' + age + '\n';
        output += 'height: ' + typeof height + ' → ' + height + '\n';
        output += 'isStudent: ' + typeof isStudent + ' → ' + isStudent + '\n';
        output += 'notAssigned: ' + typeof notAssigned + ' → ' + notAssigned + '\n';
        output += 'empty: ' + typeof empty + ' → ' + empty + '\n';
        output += 'bigNumber: ' + typeof bigNumber + ' → ' + bigNumber + '\n';
        output += 'uniqueId: ' + typeof uniqueId + ' → ' + String(uniqueId) + '\n';
        output += 'person: ' + typeof person + '\n';
        output += 'fruits: ' + typeof fruits + ' → ' + fruits.join(', ') + '\n';
        output += 'multiply: ' + typeof multiply + '\n';
        output += 'multiply(6, 7): ' + multiply(6, 7);

        // Display in the page
        document.getElementById('output').textContent = output;

        // Also log to console
        console.log('Variable Types:', {
            greeting: typeof greeting,
            age: typeof age,
            height: typeof height,
            isStudent: typeof isStudent,
            notAssigned: typeof notAssigned,
            empty: typeof empty,
            bigNumber: typeof bigNumber,
            uniqueId: typeof uniqueId,
            person: typeof person,
            fruits: typeof fruits,
            multiply: typeof multiply
        });
    </script>

</body>
</html>

What you’ll see:

  • A page showing all variable types and their values
  • The typeof operator reveals each variable’s type
  • Open the console (F12) for detailed output

Quick Reference

KeywordScopeReassignable?Hoisted?Must Initialize?
varFunction / Global✅ Yes✅ Yes (as undefined)❌ No
letBlock✅ Yes⚠️ Yes (TDZ)❌ No
constBlock❌ No⚠️ Yes (TDZ)✅ Yes

Data Types

TypeCategoryExample
BooleanPrimitivetrue, false
StringPrimitive'hello', "world"
NumberPrimitive42, 3.14
undefinedPrimitivelet x;
nullPrimitivelet y = null;
BigIntPrimitive12345678901234567890n
SymbolPrimitiveSymbol('id')
ObjectReference{ name: 'Bob' }
ArrayReference['apple', 'banana']
FunctionReferencefunction add(a, b) { }

Variable Scope

ScopeWhere DeclaredAccessible From
GlobalOutside any function/blockEverywhere
FunctionInside a functionOnly within that function
BlockInside { }Only within that block

Naming Rules

Valid:

let name = "Alice";
let _private = "hidden";
let $price = 9.99;
let user123 = "Bob";
let camelCase = "common";
let PascalCase = "class-like";
let snake_case = "underscore";

Invalid:

// let 123name = "x";    // Cannot start with digit
// let my-var = "x";     // Hyphen not allowed
// let my var = "x";     // Space not allowed
// let class = "x";      // Reserved keyword

Best Practices

Do This:

// Use const by default
const PI = 3.14159;

// Use let when reassignment is needed
let count = 0;
count++;

// Use descriptive names
let userName = "Alice";
let isLoggedIn = true;

// Use camelCase for variables
let firstName = "John";
let totalPrice = 99.99;

// Initialize variables when declaring
let age = 30;

Don’t Do This:

// Don't use var (use let/const instead)
var name = "Alice";

// Don't use vague names
let x = "Alice"; // What is x?
let data = 5;    // What data?

// Don't use reserved keywords
// let class = "Math"; // ❌ SyntaxError

// Don't start with digits
// let 1stPlace = "Alice"; // ❌ SyntaxError

// Don't forget to initialize const
// const TAX; // ❌ SyntaxError

Common Mistakes

MistakeProblemFix
Using varFunction scope leaksUse let or const
Reassigning constTypeErrorUse let if reassignment needed
Forgetting const initSyntaxErrorAlways initialize const
Case confusionmyVarMyVarBe consistent with casing
Hoisting confusionvar hoisted as undefinedUse let/const

Pro Tip: Use const by default — it prevents accidental reassignment and makes your intent clear. Use let only when you know the value will change. Avoid var entirely in modern JavaScript — it has confusing scoping and hoisting behavior. Remember: JavaScript is case-sensitive, so userName, UserName, and USERNAME are three completely different variables. Always use descriptive names that explain what the variable holds — your future self will thank you!


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!