DeveloperBreeze

Section 2.3: Operators

Tutorial 2.3.1: Arithmetic Operators


Arithmetic Operators in JavaScript

Arithmetic operators are used to perform mathematical calculations on numeric values (literals or variables). They are fundamental for tasks ranging from simple calculations to complex algorithms.


OperatorSymbolDescriptionExampleResult
Addition+Adds two numbers5 + 38
Subtraction-Subtracts one number from another10 - 46
Multiplication*Multiplies two numbers7 * 642
Division/Divides one number by another20 / 45
Modulus%Returns the remainder of division10 % 31
Exponentiation**Raises a number to a power2 ** 38
Increment++Increases a number by 1let x = 5; x++6
Decrement--Decreases a number by 1let y = 7; y--6

List of Arithmetic Operators

  1. Addition (+):
  • Adds two numbers.
  • Example:
     let sum = 10 + 5; // 15
  1. Subtraction (-):
  • Subtracts the second number from the first.
  • Example:
     let difference = 10 - 5; // 5
  1. Multiplication (*):
  • Multiplies two numbers.
  • Example:
     let product = 10 * 5; // 50
  1. Division (/):
  • Divides the first number by the second.
  • Example:
     let quotient = 10 / 5; // 2
  1. Modulus (%):
  • Returns the remainder of the division.
  • Example:
     let remainder = 10 % 3; // 1
  1. Exponentiation (</strong>)**:
  • Raises the first operand to the power of the second operand.
  • Example:
     let power = 2 ** 3; // 8
  1. Increment (++):
  • Increases a variable by one.
  • Postfix Increment (i++):
     let i = 5;
     console.log(i++); // Outputs 5, then i becomes 6
     console.log(i);   // Outputs 6
  • Prefix Increment (++i):
     let i = 5;
     console.log(++i); // Outputs 6
  1. Decrement (--):
  • Decreases a variable by one.
  • Postfix Decrement (i--):
     let i = 5;
     console.log(i--); // Outputs 5, then i becomes 4
     console.log(i);   // Outputs 4
  • Prefix Decrement (--i):
     let i = 5;
     console.log(--i); // Outputs 4

Operator Precedence

Operator precedence determines the order in which operations are performed in an expression.

  • Order of Operations:
  1. Parentheses ()
  2. Exponentiation **
  3. Multiplication *, Division /, Modulus %
  4. Addition +, Subtraction -
  • Example:
  let result = 10 + 5 * 2; // 20
  // Multiplication happens before addition
  // 10 + (5 * 2) = 10 + 10 = 20

  let resultWithParentheses = (10 + 5) * 2; // 30
  // Parentheses alter the order
  // (10 + 5) * 2 = 15 * 2 = 30

Type Coercion with the `+` Operator

  • When adding a number and a string, JavaScript converts the number to a string and concatenates.
  let message = "The total is: " + 20; // "The total is: 20"
  • Be cautious to avoid unexpected results.
  console.log(5 + "5"); // "55"
  console.log(5 - "2"); // 3 (string "2" is coerced to number)

Unary Operators

  1. Unary Plus (+):
  • Attempts to convert the operand to a number.
  • Example:
     let x = "5";
     let num = +x; // 5 (number)
  1. Unary Negation (-):
  • Converts the operand to a number and negates it.
  • Example:
     let x = "5";
     let num = -x; // -5 (number)

Examples of Arithmetic Operations

  1. Calculating the Area of a Circle:
   const PI = 3.1416;
   let radius = 5;
   let area = PI * radius ** 2;
   console.log("Area:", area); // Area: 78.54
  1. Even or Odd Checker:
   let number = 7;
   if (number % 2 === 0) {
     console.log(number + " is even.");
   } else {
     console.log(number + " is odd."); // Outputs: 7 is odd.
   }
  1. Incrementing Values in a Loop:
   for (let i = 0; i < 5; i++) {
     console.log("Count:", i);
   }
   // Outputs:
   // Count: 0
   // Count: 1
   // Count: 2
   // Count: 3
   // Count: 4

Common Mistakes to Avoid

  • Integer Division:
  • Unlike some languages, dividing integers in JavaScript returns a floating-point number.
    console.log(5 / 2); // 2.5
  • Modulus with Negative Numbers:
  • Be cautious, as the result can be negative.
    console.log(-10 % 3); // -1

Exercise

  1. Simple Calculator:
  • Create variables a and b with values 12 and 4.
  • Perform all arithmetic operations and log the results.
     let a = 12;
     let b = 4;
     console.log("Addition:", a + b);        // 16
     console.log("Subtraction:", a - b);     // 8
     console.log("Multiplication:", a * b);  // 48
     console.log("Division:", a / b);        // 3
     console.log("Modulus:", a % b);         // 0
  1. Increment and Decrement Practice:
  • Initialize counter to 10.
  • Use both prefix and postfix increment/decrement operators and observe the outputs.
     let counter = 10;
     console.log(counter++); // 10
     console.log(counter);   // 11
     console.log(++counter); // 12
     console.log(counter--); // 12
     console.log(counter);   // 11
     console.log(--counter); // 10

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Comparison and Logical Operators

Example:

let age = 20;
let hasID = true;

if (age >= 18 && hasID) {
  console.log("Access granted.");
} else {
  console.log("Access denied.");
}
// Output: "Access granted."

Dec 11, 2024
Read More
Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

  • Iterating Over Arrays:
  for (let fruit of fruits) {
    console.log(fruit);
  }

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

A variable that has been declared but not assigned a value is undefined.

  • Example:

Dec 11, 2024
Read More
Tutorial
javascript

Variables and Constants

     const API_KEY = "12345";
     // API_KEY = "67890"; // Error: Assignment to constant variable
  • Variables are accessible only within the block they are declared in.
  • Example:

Dec 10, 2024
Read More
Tutorial
javascript

Hello World and Comments

     console.log(Hello, World!);
  • Correct:

Dec 10, 2024
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

  • manifest.json: Defines the extension's metadata and permissions.
  • background.js: Runs in the background to handle tweet automation logic.
  • content.js: Interacts with the X website.
  • popup.html: The user interface for starting/stopping the automation.
  • popup.js: Handles user interactions from the popup.

The manifest.json is the heart of the extension. It defines the extension's properties and permissions. Paste the following code into your manifest.json file:

Dec 10, 2024
Read More
Tutorial
javascript

Easy JavaScript Tutorial for Beginners

let age = 18;

if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor.");
}
let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else {
    console.log("Grade: C");
}

Sep 18, 2024
Read More
Tutorial
javascript

JavaScript Tutorial for Absolute Beginners

console.log("Hello, World!");
  • Open index.html in your web browser.
  • Right-click and select "Inspect" or press Ctrl + Shift + I to open the Developer Tools.
  • Go to the "Console" tab to see the message.

Sep 02, 2024
Read More
Tutorial
javascript

Creating a Dropdown Menu with JavaScript

To follow along with this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Familiarity with DOM manipulation in JavaScript will be helpful but isn’t required.

The first step in creating a dropdown menu is to build the basic HTML structure. We’ll create a navigation bar with a dropdown menu that is initially hidden.

Sep 02, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

class Animal {
  constructor(type, name) {
    this.type = type;
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super('Dog', name);
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak(); // Output: Buddy barks.

The super keyword is used to call the constructor or methods of the parent class. This is particularly useful when you need to add functionality to a subclass while still retaining the behavior of the parent class.

Sep 02, 2024
Read More
Tutorial
javascript

Asynchronous JavaScript: A Beginner's Guide

Asynchronous programming allows tasks to run in the background without interfering with the main thread of execution. In JavaScript, this means you can start an operation (like fetching data), let it run in the background, and continue executing other code while waiting for the operation to complete.

In synchronous programming, tasks are performed one after another. Each task must be completed before the next one begins. This can lead to issues like blocking, where a long-running task prevents other tasks from executing.

Aug 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

You can insert the new element into the DOM using methods like appendChild, insertBefore, or append.

const parentElement = document.getElementById('parent');
parentElement.appendChild(newElement); // Adds the new element as the last child

Aug 30, 2024
Read More
Code
python

Exponentiation

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!