Complete Guide to JavaScript Variables and DOM Manipulation

Complete Guide to JavaScript Variables and DOM Manipulation

In programming, particularly in JavaScript, declaration and initialization are two key concepts related to variables.

Declaration

Declaration is the process of defining a variable or function without assigning a value to it.

  • For variables, you simply tell the program that a variable exists by using keywords like var, let, or const.

Example:

var myVar;  // Variable declaration using var
let myLetVar;  // Variable declaration using let
const myConstVar;  // Variable declaration using const (const variables must be initialized at the time of declaration)

In this example, myVar, myLetVar, and myConstVar are declared but not initialized (except for const, which must be initialized).

  • For functions, you define the function name and its body.

Example:

function myFunction() {
  console.log("Hello, World!");
}

Initialization

Initialization is the process of assigning a value to a declared variable.

  • For variables, you can assign a value either at the time of declaration or later.

Example:

var myVar = 10;  // Variable declaration and initialization using var
let myLetVar = 20;  // Variable declaration and initialization using let
const myConstVar = 30;  // Variable declaration and initialization using const

myVar = 15;  // Variable re-initialization (only for var and let)
myLetVar = 25;  // Variable re-initialization (only for var and let)

In this example, myVar, myLetVar, and myConstVar are initialized with values 10, 20, and 30 respectively. Later, myVar and myLetVar are re-initialized with new values 15 and 25.

  • For functions, the body of the function is set during the declaration, so there is no separate initialization step.

Key Points

  • Declaration: Creates the variable or function in memory.

  • Initialization: Assigns a value to the declared variable.

Combined Example

var myVar;  // Declaration
myVar = 10;  // Initialization

let myLetVar = 20;  // Declaration and initialization combined

const myConstVar = 30;  // Declaration and initialization combined (mandatory for const)

You can declare variables using three different keywords: var, let, and const. Each of these keywords has distinct characteristics and use cases. Here's a breakdown of each:

var

  • Function Scope: Variables declared with var are function-scoped, meaning they are only accessible within the function they are declared in.

  • Hoisting: Variables declared with var are hoisted to the top of their scope, meaning they can be accessed before their declaration (but will be undefined).

  • Re-declaration: Variables declared with var can be re-declared within the same scope without causing an error.

function example() {
  console.log(x); // undefined (hoisted)
  var x = 10;
  console.log(x); // 10
}
example();

let

  • Block Scope: Variables declared with let are block-scoped, meaning they are only accessible within the block ({}) they are declared in.

  • Hoisting: Variables declared with let are also hoisted, but they are not initialized. Accessing them before the declaration will result in a ReferenceError.

  • Re-declaration: Variables declared with let cannot be re-declared within the same scope.

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

const

  • Block Scope: Variables declared with const are block-scoped, just like let.

  • Hoisting: Variables declared with const are also hoisted but not initialized. Accessing them before the declaration will result in a ReferenceError.

  • Re-declaration: Variables declared with const cannot be re-declared within the same scope.

  • Immutability: The value assigned to a const variable cannot be changed. However, if the const variable holds an object, the properties of the object can be modified.

function example() {
  const x = 10;
  console.log(x); // 10
  x = 20; // TypeError: Assignment to constant variable.
}
example();

const obj = { a: 1 };
obj.a = 2; // This is allowed
console.log(obj.a); // 2

Summary

  • var: Use for function-scoped variables. Avoid if possible due to hoisting issues.

  • let: Use for block-scoped variables. Prefer over var for most cases as it helps to write clearer, more maintainable, and less error-prone code compared to var.

    Example:

      function testVar() {
        if (true) {
          var x = 1;
        }
        console.log(x); // 1
      }
    
      function testLet() {
        if (true) {
          let y = 1;
        }
        console.log(y); // ReferenceError: y is not defined
      }
    
      testVar();
      testLet();
    
  • const: Use for block-scoped constants. Prefer for values that should not change.

Example Code

Here’s an example demonstrating the use of var, let, and const:

function example() {
  if (true) {
    var a = 1;
    let b = 2;
    const c = 3;

    console.log(a); // 1
    console.log(b); // 2
    console.log(c); // 3
  }

  console.log(a); // 1 (var is function-scoped)
  console.log(b); // ReferenceError: b is not defined
  console.log(c); // ReferenceError: c is not defined
}

example();

Use let and const for better control over scope and to avoid common issues with variable hoisting and re-declaration.

1. JavaScript Variables

1.1 Variable Declaration

Variables are like containers for storing values. We can create a variable using the let keyword. In the below case, variable is declared but not assigned a value.

let message;

1.2 Assigning a Value to the Variable

We can put data into a variable using an assignment operator =

let message = "wasimakram.in";
let message;
message = "wasimakram.in";
💡
Printing a variable without assigning a value will give the output undefined

2. Document Object Model (DOM)

The DOM is the structured representation of the HTML document created by the browser. It allows JavaScript to manipulate, structure, and style your website.

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1>wasimakram.in</h1>
    <button>Visit my portfolio</button>
  </body>
</html>

2.1 Document Object

It is the entry point of the DOM. For accessing any HTML Element, you should always start with accessing the document object first.

2.2 HTML DOM Tree

The DOM tree represents an HTML document as nodes. Each node is referred to as an Object.

2.3 Methods

2.3.1 getElementById

The getElementById() method helps to select the HTML Element with a specific ID.

console.log(document.getElementById("headingElement"))

2.4 Properties

2.4.1 textContent

To manipulate the text within the HTML Element, we use textContent Property.

2.4.2 style

The style property is used to get or set a specific style of an HTML Element using different CSS properties.

Use Camel Case naming convention (starting letter of each word should be in the upper case except for the first word) for naming the Style Object Properties.

For example, color, fontFamily, backgroundColor, etc.

2.5 Events

Events are the actions by which the user or browser interacts with the HTML Elements. Actions can be anything like clicking a button, pressing keyboard keys, scrolling the page, etc.

2.5.1 Click Event

Description: This event happens when you click on an element, like a button.

<!DOCTYPE html>
<html>
<head>
  <title>Click Event Example</title>
</head>
<body>
  <button id="clickButton">Click Me!</button>
  <script src="click.js"></script>
</body>
</html>
document.getElementById('clickButton').onclick = function() {
  alert("Button clicked!");
};

Explanation: When you click the button, a message pops up saying "Button clicked!"


2.5.2 Mouseover Event

Description: This event happens when you move your mouse over an element, like a paragraph.

<!DOCTYPE html>
<html>
<head>
  <title>Mouseover Event Example</title>
</head>
<body>
  <p id="hoverText">Hover over this text.</p>
  <p id="hoverMessage"></p>
  <script src="mouseover.js"></script>
</body>
</html>
document.getElementById('hoverText').onmouseover = function() {
  document.getElementById('hoverMessage').innerText = "Mouse is over the text!";
};

Explanation: When you move your mouse over the paragraph, the message "Mouse is over the text!" appears below it.


2.5.3 Double Click Event

Description: This event happens when you double-click on an element, like a paragraph.

<!DOCTYPE html>
<html>
<head>
  <title>Double Click Event Example</title>
</head>
<body>
  <p id="doubleClickText">Double-click this paragraph.</p>
  <script src="dblclick.js"></script>
</body>
</html>
document.getElementById('doubleClickText').ondblclick = function() {
  alert("Paragraph double-clicked!");
};

Explanation: When you double-click the paragraph, a message pops up saying "Paragraph double-clicked!"


2.5.4 Keydown Event

Description: This event happens when you press a key on the keyboard.

<!DOCTYPE html>
<html>
<head>
  <title>Keydown Event Example</title>
</head>
<body>
  <input type="text" id="keydownInput" placeholder="Press any key">
  <p id="keydownMessage"></p>
  <script src="keydown.js"></script>
</body>
</html>
document.getElementById('keydownInput').onkeydown = function(event) {
  document.getElementById('keydownMessage').innerText = `Key pressed: ${event.key}`;
};

Explanation: When you press any key while typing in the text box, it shows which key you pressed below the box.


2.5.5 Keyup Event

Description: This event happens when you release a key on the keyboard.

<!DOCTYPE html>
<html>
<head>
  <title>Keyup Event Example</title>
</head>
<body>
  <input type="text" id="keyupInput" placeholder="Press any key">
  <p id="keyupMessage"></p>
  <script src="keyup.js"></script>
</body>
</html>
document.getElementById('keyupInput').onkeyup = function(event) {
  document.getElementById('keyupMessage').innerText = `Key released: ${event.key}`;
};

Explanation: When you release a key while typing in the text box, it shows which key you released below the box.


2.5.6 Submit Event

Description: This event happens when you submit a form.

<!DOCTYPE html>
<html>
<head>
  <title>Submit Event Example</title>
</head>
<body>
  <form id="submitForm">
    <input type="text" name="name" placeholder="Enter your name">
    <button type="submit">Submit</button>
  </form>
  <script src="submit.js"></script>
</body>
</html>
document.getElementById('submitForm').onsubmit = function(event) {
  event.preventDefault();
  alert("Form submitted!");
};

Explanation: When you submit the form, it stops the default action (which would reload the page) and shows a message saying "Form submitted!"


2.5.7 Change Event

Description: This event happens when the value of an element changes, like selecting a different option from a dropdown.

<!DOCTYPE html>
<html>
<head>
  <title>Change Event Example</title>
</head>
<body>
  <select id="changeSelect">
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>
  </select>
  <p id="changeMessage"></p>
  <script src="change.js"></script>
</body>
</html>
document.getElementById('changeSelect').onchange = function(event) {
  document.getElementById('changeMessage').innerText = `Selected value: ${event.target.value}`;
};

Explanation: When you select a different option from the dropdown, it shows the selected value below the dropdown.


2.5.8 Load Event

Description: This event happens when the entire page loads.

<!DOCTYPE html>
<html>
<head>
  <title>Load Event Example</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p id="loadMessage"></p>
  <script src="load.js"></script>
</body>
</html>
window.onload = function() {
  document.getElementById('loadMessage').innerText = "Page fully loaded!";
};

Explanation: When the page finishes loading, a message pops up saying "Page fully loaded!"


2.5.9 Resize Event

Description: This event happens when the browser window is resized.

<!DOCTYPE html>
<html>
<head>
  <title>Resize Event Example</title>
</head>
<body>
  <h1>Resize the browser window</h1>
  <p id="resizeMessage"></p>
  <script src="resize.js"></script>
</body>
</html>
window.onresize = function() {
  document.getElementById('resizeMessage').innerText = "Window resized!";
};

Explanation: When you resize the browser window, it shows the message "Window resized!" below the heading.


2.5.10 Copy Event

Description: This event happens when you copy content.

<!DOCTYPE html>
<html>
<head>
  <title>Copy Event Example</title>
</head>
<body>
  <p id="copyText">Try copying this text.</p>
  <script src="copy.js"></script>
</body>
</html>
document.getElementById('copyText').oncopy = function() {
  alert("Content copied!");
};

Explanation: When you copy the text in the paragraph, a message pops up saying "Content copied!"


2.5.11 Paste Event

Description: This event happens when you paste content.

<!DOCTYPE html>
<html>
<head>
  <title>Paste Event Example</title>
</head>
<body>
  <textarea id="pasteArea" placeholder="Paste something here"></textarea>
  <script src="paste.js"></script>
</body>
</html>
document.getElementById('pasteArea').onpaste = function() {
  alert("Content pasted!");
};

Explanation: When you paste something into the text area, a message pops up saying "Content pasted!"