JavaScript Operators

Types of JavaScript Operators

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Conditional Operators
  • Type Operators

JavaScript is a popular programming language used to build interactive and dynamic web applications. Operators are an essential part of JavaScript that perform specific operations on values and variables. In this guide, we will explore the different types of JavaScript operators, their use cases, and how they work.

Arithmetic Operators

Arithmetic operators perform mathematical operations on numbers. These operators include addition (+), subtraction (-), multiplication (*), division (/), modulo (%), and more. Arithmetic operators are used to perform simple arithmetic calculations and return a single value.

Example:

1let x = 10; 2let y = 20; 3let z = x + y; // returns 30

Assignment Operators

Assignment operators assign values to variables. The most commonly used assignment operator is the equal sign (=), which assigns the value to the right of the operator to the variable on the left. There are also compound assignment operators that perform arithmetic operations and assign the result to the same variable.

Example:

1let x = 10; 2x = x + 5; // x is now equal to 15

Comparison Operators

Comparison operators are used to compare two values and return a Boolean value indicating whether the comparison is true or false. These operators include equal to (==), not equal to (!=), greater than (>), less than (<), and others. Comparison operators are used to make decisions in your code, such as conditional statements.

Example:

1let x = 10; 2let y = 20; 3let isGreater = x > y; // returns false

Logical Operators

Logical operators are used to combine multiple comparison operations and return a single Boolean value. These operators include AND (&&), OR (||), and NOT (!). Logical operators are used to make complex decisions in your code.

Example:

1let x = 10; 2let y = 20; 3let isBetween = x > 5 && x < 15; // returns true

Conditional Operators

Conditional operators, also known as ternary operators, provide a shorthand way to write simple if-else statements. The operator takes three operands: the condition, the value to return if the condition is true, and the value to return if the condition is false.

Example:

1let x = 10; 2let result = x > 5 ? "Greater" : "Lesser"; // returns "Greater"

Type Operators

Type operators are used to determine the type of a value or a variable. The typeof operator returns a string indicating the type of the operand. The instanceof operator returns a Boolean value indicating whether an object is an instance of a particular class.

Example:

1let x = 10; 2let type = typeof x; // returns "number"