Perform Arithmetic Operations in JavaScript

JavaScriptBeginner
Practice Now

Introduction

In this lab, participants will explore the fundamental arithmetic operations in JavaScript, learning how to manipulate numbers using various mathematical operators. The lab provides a comprehensive journey through setting up an HTML environment, implementing basic arithmetic operations like addition, subtraction, multiplication, and division, and understanding more advanced concepts such as modulo and increment/decrement operators.

Participants will start by creating an HTML file with an embedded JavaScript section, then progressively build their skills by practicing different arithmetic techniques. Through hands-on coding exercises, learners will gain practical experience in performing mathematical calculations, understanding operator precedence, and exploring prefix and postfix increment/decrement operations, which are essential skills for JavaScript programming.

Set Up HTML File for JavaScript Arithmetic Operations

In this step, you'll create a basic HTML file that will serve as the foundation for performing JavaScript arithmetic operations. We'll set up a simple HTML structure and include an embedded JavaScript section to demonstrate basic arithmetic functionality.

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

Copy and paste the following HTML code into the arithmetic.html file:

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

    <script>
      // We'll add our JavaScript code here in this section
      console.log("HTML file is ready for arithmetic operations!");
    </script>
  </body>
</html>

Let's break down the key components of this HTML file:

  1. <!DOCTYPE html> declares this is an HTML5 document
  2. The <head> section contains metadata about the document
  3. The <body> contains the visible content
  4. The <script> tag is where we'll write our JavaScript code

To verify the file is created correctly, you can open the file in the browser's developer console. The initial console.log() will help confirm the file is set up properly.

Implement Basic Arithmetic Operators (+, -, *, /)

In this step, you'll learn how to perform basic arithmetic operations in JavaScript using the fundamental mathematical operators: addition (+), subtraction (-), multiplication (*), and division (/).

Open the arithmetic.html file created in the previous step and modify the <script> section to include the following code:

<script>
  // Addition Operator (+)
  let sum = 10 + 5;
  console.log("Addition: 10 + 5 =", sum);

  // Subtraction Operator (-)
  let difference = 20 - 7;
  console.log("Subtraction: 20 - 7 =", difference);

  // Multiplication Operator (*)
  let product = 6 * 4;
  console.log("Multiplication: 6 * 4 =", product);

  // Division Operator (/)
  let quotient = 25 / 5;
  console.log("Division: 25 / 5 =", quotient);
</script>

When you open this HTML file in a web browser and check the browser's developer console, you'll see the following example output:

Addition: 10 + 5 = 15
Subtraction: 20 - 7 = 13
Multiplication: 6 * 4 = 24
Division: 25 / 5 = 5

Key points to understand:

  • The + operator adds two numbers together
  • The - operator subtracts the right operand from the left
  • The * operator multiplies two numbers
  • The / operator divides the left operand by the right operand

You can also perform operations with variables and mix different types of numbers, including integers and floating-point numbers.

Explore Modulo and Increment/Decrement Operators

In this step, you'll learn about two important JavaScript arithmetic operators: the modulo operator (%) and increment/decrement operators (++ and --).

Open the arithmetic.html file and update the <script> section with the following code:

<script>
  // Modulo Operator (%)
  // Returns the remainder of a division
  let remainder = 17 % 5;
  console.log("Modulo: 17 % 5 =", remainder);

  // Increment Operator (++)
  let x = 10;
  x++; // Increases x by 1
  console.log("Increment: x++ =", x);

  // Decrement Operator (--)
  let y = 20;
  y--; // Decreases y by 1
  console.log("Decrement: y-- =", y);

  // More modulo examples
  console.log("Even/Odd Check: 15 % 2 =", 15 % 2);
  console.log("Even/Odd Check: 16 % 2 =", 16 % 2);
</script>

When you open this HTML file in a web browser and check the developer console, you'll see the following example output:

Modulo: 17 % 5 = 2
Increment: x++ = 11
Decrement: y-- = 19
Even/Odd Check: 15 % 2 = 1
Even/Odd Check: 16 % 2 = 0

Key points to understand:

  • The modulo operator % returns the remainder after division
  • You can use modulo to check if a number is even or odd
  • The increment operator ++ increases a variable by 1
  • The decrement operator -- decreases a variable by 1

The modulo operator is particularly useful for:

  • Checking even/odd numbers
  • Cycling through a range of numbers
  • Creating patterns or distributions

Understand Prefix and Postfix Increment/Decrement

In this step, you'll learn the difference between prefix and postfix increment/decrement operators in JavaScript. These operators might look similar, but they behave differently when used in expressions.

Open the arithmetic.html file and update the <script> section with the following code:

<script>
  // Postfix Increment (x++)
  let a = 5;
  let b = a++;
  console.log("Postfix Increment:");
  console.log("a =", a); // a is incremented after the value is assigned
  console.log("b =", b); // b gets the original value of a

  // Prefix Increment (++x)
  let x = 5;
  let y = ++x;
  console.log("\nPrefix Increment:");
  console.log("x =", x); // x is incremented before the value is assigned
  console.log("y =", y); // y gets the incremented value of x

  // Similar concept applies to decrement operators
  let p = 10;
  let q = p--;
  console.log("\nPostfix Decrement:");
  console.log("p =", p); // p is decremented after the value is assigned
  console.log("q =", q); // q gets the original value of p

  let m = 10;
  let n = --m;
  console.log("\nPrefix Decrement:");
  console.log("m =", m); // m is decremented before the value is assigned
  console.log("n =", n); // n gets the decremented value of m
</script>

When you open this HTML file in a web browser and check the developer console, you'll see the following example output:

Postfix Increment:
a = 6
b = 5

Prefix Increment:
x = 6
y = 6

Postfix Decrement:
p = 9
q = 10

Prefix Decrement:
m = 9
n = 9

Key points to understand:

  • Postfix x++: Returns the original value, then increments
  • Prefix ++x: Increments first, then returns the new value
  • The same principle applies to decrement operators x-- and --x
  • This difference matters when the operator is used in an expression or assignment

Practice Combining Arithmetic Operations

In this step, you'll learn how to combine multiple arithmetic operations to create more complex calculations. We'll explore different ways of combining operators and demonstrate how JavaScript handles order of operations.

Open the arithmetic.html file and update the <script> section with the following code:

<script>
  // Combining multiple arithmetic operations
  let result1 = 10 + 5 * 2;
  console.log("Result 1 (10 + 5 * 2):", result1);

  // Using parentheses to change order of operations
  let result2 = (10 + 5) * 2;
  console.log("Result 2 ((10 + 5) * 2):", result2);

  // Complex calculation with multiple operators
  let x = 15;
  let y = 7;
  let complexCalc = (x % 4) + y * 2 - x++ / 3;
  console.log("Complex Calculation:", complexCalc);

  // Combining increment/decrement with other operations
  let a = 5;
  let b = 3;
  let mixedCalc = ++a + b-- * 2;
  console.log("Mixed Calculation (++a + b-- * 2):", mixedCalc);
  console.log("a after calculation:", a);
  console.log("b after calculation:", b);

  // Practical example: Calculating average
  let score1 = 85;
  let score2 = 92;
  let score3 = 78;
  let averageScore = (score1 + score2 + score3) / 3;
  console.log("Average Score:", averageScore);
</script>

When you open this HTML file in a web browser and check the developer console, you'll see the following example output:

Result 1 (10 + 5 * 2): 20
Result 2 ((10 + 5) * 2): 30
Complex Calculation: 9
Mixed Calculation (++a + b-- * 2): 11
a after calculation: 6
b after calculation: 2
Average Score: 85

Key points to understand:

  • JavaScript follows standard mathematical order of operations (PEMDAS)
  • Parentheses can be used to change the default order of operations
  • You can combine different types of arithmetic operators in a single expression
  • Increment and decrement operators can be used within larger calculations
  • Always be careful with the order and placement of operators

Summary

In this lab, participants learned how to set up a basic HTML file for JavaScript arithmetic operations and explore fundamental mathematical computations. The lab guided learners through creating an HTML document with an embedded JavaScript section, enabling them to practice essential arithmetic techniques using operators like addition (+), subtraction (-), multiplication (*), and division (/).

The learning journey progressed from establishing a foundational HTML structure to implementing various arithmetic operations, including exploring modulo, increment, and decrement operators. Participants gained hands-on experience with different operator variations, understanding how to combine arithmetic operations and manipulate numeric values effectively in JavaScript.