JavaScript Variables

Variables in JavaScript are containers for storing data values. They allow you to store, manipulate, and retrieve data during the execution of a program. JavaScript supports three types of variable declarations: var, let, and const.

Key Topics

Declaring Variables

You can declare variables using the var, let, or const keywords. Use let for variables whose values can change, and const for variables whose values remain constant.

// Declaring variables
var x = 5; // Global or function-scoped
let y = 10; // Block-scoped
const z = 15; // Constant value

console.log(x, y, z);

Output

5

10

15

Explanation: x is declared using var, y using let, and z using const. Each has specific scoping rules and use cases.

Variable Types

JavaScript variables can hold different data types: numbers, strings, objects, and more. JavaScript is dynamically typed, meaning you don't need to specify the variable's type.

// Different variable types
let name = "John"; // String
let age = 30; // Number
let isStudent = true; // Boolean
let hobbies = ["reading", "coding"]; // Array
let person = { firstName: "John", lastName: "Doe" }; // Object

console.log(name);
console.log(age);
console.log(isStudent);
console.log(hobbies);
console.log(person);

Output

John

30

true

reading,coding

[object Object]

Explanation: Variables in JavaScript can hold values of various types, including strings, numbers, booleans, arrays, and objects. Each type serves different purposes in programming.

Variable Scope

Variable scope determines where in the code a variable can be accessed. JavaScript has three types of scope:

  • Global Scope: Variables declared outside any function or block are globally scoped and accessible throughout the script.
  • Function Scope: Variables declared with var inside a function are accessible only within that function.
  • Block Scope: Variables declared with let or const inside a block (e.g., inside curly braces) are accessible only within that block.
// Global Scope
var globalVar = "I am global";

function testScope() {
    // Function Scope
    var functionVar = "I am function scoped";
    console.log(globalVar); // Accessible
    console.log(functionVar); // Accessible
}

testScope();
// console.log(functionVar); // Error: functionVar is not defined

// Block Scope
{
    let blockVar = "I am block scoped";
    console.log(blockVar); // Accessible inside the block
}
// console.log(blockVar); // Error: blockVar is not defined

Explanation: The example shows the three types of variable scope in JavaScript. A global variable is accessible throughout the script, function-scoped variables are limited to their function, and block-scoped variables are limited to their block.

DOM Interaction Example

JavaScript variables can be used to dynamically update the DOM. This example demonstrates how to declare variables, use them to interact with the DOM, and display the result on a webpage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript DOM Interaction</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #result {
            margin-top: 10px;
            padding: 10px;
            border: 1px solid black;
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <h1>DOM Interaction Example</h1>
    <button id="btnChange">Click Me</button>
    <div id="result">Initial Content</div>

    <script>
        // JavaScript code
        const button = document.getElementById("btnChange");
        const result = document.getElementById("result");

        button.addEventListener("click", function() {
            let newText = "The content has been updated!";
            result.textContent = newText;
        });
    </script>
</body>
</html>

Explanation: This example demonstrates how variables can be used to dynamically update the DOM. The button click triggers an event listener that updates the text content of a div element using a variable.

Key Takeaways

  • Keywords: Use var, let, and const to declare variables.
  • Dynamic Typing: JavaScript variables can hold any type of data.
  • Scoping: Understand the differences between var, let, and const regarding scope and mutability.
  • DOM Interaction: Variables are powerful for manipulating DOM elements dynamically.