Explore Assignment Operators in JavaScript

HTMLHTMLBeginner
Practice Now

Introduction

In this lab, students will explore JavaScript assignment operators through a hands-on HTML and JavaScript exercise. The lab guides learners through creating an HTML file and implementing various assignment operators, including basic assignment (=), compound assignment (+=, -=), and multiplication/division assignment (*=, /=).

Participants will start by setting up an HTML structure with an embedded script tag, then progressively demonstrate different assignment operator techniques. By using console logging and document.write() methods, students will verify and understand how these operators work in JavaScript, gaining practical experience in variable manipulation and value assignment.

Create HTML File for JavaScript Assignment Operators

In this step, you'll create an HTML file that will serve as the foundation for exploring JavaScript assignment operators. HTML provides the structure for embedding JavaScript code, allowing us to demonstrate and test various assignment operator techniques.

First, open the WebIDE and navigate to the ~/project directory. Create a new file named assignment-operators.html by right-clicking in the file explorer and selecting "New File".

Here's the basic HTML structure you'll use:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript Assignment Operators</title>
  </head>
  <body>
    <h1>Exploring Assignment Operators</h1>

    <script>
      // JavaScript code will be added here in subsequent steps
    </script>
  </body>
</html>

Let's break down the key components:

  • <!DOCTYPE html> declares this as an HTML5 document
  • The <script> tag is where we'll write our JavaScript code
  • The page includes a simple heading to provide context

After creating the file, save it in the ~/project directory. This HTML file will be our playground for learning about assignment operators in the following steps.

Example output when you open this file in a browser:

Exploring Assignment Operators

Implement Basic Assignment Operator (=)

In this step, you'll learn about the basic assignment operator (=) in JavaScript. The assignment operator is used to assign a value to a variable, creating a fundamental way to store and manipulate data.

Open the assignment-operators.html file you created in the previous step. Inside the <script> tag, add the following JavaScript code to explore basic assignment:

// Declaring and assigning variables using the = operator
let firstName = "John";
let age = 25;
let isStudent = true;

// Demonstrating variable assignment
console.log("First Name:", firstName);
console.log("Age:", age);
console.log("Is Student:", isStudent);

Let's break down the key concepts:

  • let is used to declare variables in modern JavaScript
  • The = operator assigns a value to a variable
  • Variables can store different types of data: strings, numbers, and boolean values
  • console.log() is used to print values to the browser's console

You can also reassign variables using the same operator:

// Reassigning variable values
age = 26;
console.log("Updated Age:", age);

// Assigning the value of one variable to another
let originalAge = age;
console.log("Original Age:", originalAge);

Example output in browser console:

First Name: John
Age: 25
Is Student: true
Updated Age: 26
Original Age: 26

Practice Compound Assignment Operators (+=, -=)

In this step, you'll explore compound assignment operators += and -= in JavaScript. These operators provide a shorthand way to perform addition and subtraction while assigning a new value to a variable.

Open the assignment-operators.html file and add the following JavaScript code inside the <script> tag:

// Initial variable declaration
let score = 100;
console.log("Initial Score:", score);

// Using += operator to add and assign
score += 50; // Equivalent to: score = score + 50
console.log("Score after +50:", score);

// Using -= operator to subtract and assign
score -= 25; // Equivalent to: score = score - 25
console.log("Score after -25:", score);

// Practicing with another variable
let quantity = 10;
console.log("Initial Quantity:", quantity);

quantity += 5; // Add 5 to quantity
console.log("Quantity after +5:", quantity);

quantity -= 3; // Subtract 3 from quantity
console.log("Quantity after -3:", quantity);

Key points about compound assignment operators:

  • += adds the right-side value to the variable and assigns the result
  • -= subtracts the right-side value from the variable and assigns the result
  • These operators provide a more concise way to modify variable values
  • They work with numbers and can simplify arithmetic operations

Example output in browser console:

Initial Score: 100
Score after +50: 150
Score after -25: 125
Initial Quantity: 10
Quantity after +5: 15
Quantity after -3: 12

Demonstrate Multiplication and Division Assignment Operators (*=, /=)

In this step, you'll explore multiplication and division assignment operators *= and /= in JavaScript. These operators provide a concise way to multiply or divide a variable and assign the result back to the same variable.

Open the assignment-operators.html file and add the following JavaScript code inside the <script> tag:

// Multiplication assignment operator (*=)
let price = 10;
console.log("Initial Price:", price);

price *= 3; // Equivalent to: price = price * 3
console.log("Price after *3:", price);

// Division assignment operator (/=)
let quantity = 24;
console.log("Initial Quantity:", quantity);

quantity /= 4; // Equivalent to: quantity = quantity / 4
console.log("Quantity after /4:", quantity);

// Practical example: Calculating total cost
let itemPrice = 5;
let itemCount = 7;
console.log("Item Price:", itemPrice);
console.log("Item Count:", itemCount);

let totalCost = itemPrice * itemCount;
console.log("Total Cost:", totalCost);

totalCost *= 0.9; // Apply 10% discount
console.log("Discounted Total Cost:", totalCost);

Key points about multiplication and division assignment operators:

  • *= multiplies the variable by the right-side value and assigns the result
  • /= divides the variable by the right-side value and assigns the result
  • These operators help simplify mathematical operations and assignments
  • They work with numeric values and can be used in various calculations

Example output in browser console:

Initial Price: 10
Price after *3: 30
Initial Quantity: 24
Quantity after /4: 6
Item Price: 5
Item Count: 7
Total Cost: 35
Discounted Total Cost: 31.5

Verify Assignment Operator Results Using document.write()

In this step, you'll learn how to use document.write() to display the results of assignment operators directly on the web page. This method provides a simple way to output values for beginners to visualize their JavaScript operations.

Open the assignment-operators.html file and modify the <script> tag to include the following code:

// Demonstrating assignment operators with document.write()
let initialValue = 10;
document.write("<h2>Assignment Operator Demonstration</h2>");
document.write("Initial Value: " + initialValue + "<br>");

// Basic assignment
initialValue = 20;
document.write("After Basic Assignment (=): " + initialValue + "<br>");

// Compound addition assignment
initialValue += 5;
document.write("After Addition Assignment (+=): " + initialValue + "<br>");

// Compound subtraction assignment
initialValue -= 3;
document.write("After Subtraction Assignment (-=): " + initialValue + "<br>");

// Multiplication assignment
initialValue *= 2;
document.write(
  "After Multiplication Assignment (*=): " + initialValue + "<br>"
);

// Division assignment
initialValue /= 4;
document.write("After Division Assignment (/=): " + initialValue + "<br>");

Key points about document.write():

  • Writes HTML or text directly to the web page
  • Can be used to display variable values
  • Useful for debugging and demonstrating JavaScript operations
  • Adds content to the page in the order it's called

Example output in the browser:

Assignment Operator Demonstration
Initial Value: 10
After Basic Assignment (=): 20
After Addition Assignment (+=): 25
After Subtraction Assignment (-=): 22
After Multiplication Assignment (*=): 44
After Division Assignment (/=): 11

Summary

In this lab, participants explore JavaScript assignment operators through a hands-on HTML and JavaScript exercise. The lab begins by creating an HTML file that serves as a foundation for demonstrating various assignment operator techniques, starting with the basic assignment operator (=) to declare and initialize variables with different data types like strings, numbers, and booleans.

The learning journey progresses through implementing compound assignment operators such as +=, -=, *=, and /=, which provide concise ways to perform arithmetic operations and update variable values. By using document.write() and console.log(), participants can verify and visualize the results of these assignment operations, gaining practical understanding of how these operators work in JavaScript programming.