top of page

# Javascript operators with code examples.

Updated: Dec 22, 2022 Image by Dok Sev: https://pixabay.com/users/doki7-646987

Javascript is a powerful programming language that is widely used to build web applications. One of the key features of Javascript is its operators, which allow developers to perform various operations on data. In this blog, we will explore some of the most common Javascript operators and provide code examples to illustrate how they work.

First, let's look at arithmetic operators. These include the basic math operators like addition (+), subtraction (-), multiplication (*), and division (/). These operators work exactly as you would expect, allowing you to perform basic math operations in your code. For example:

```let x = 10;
let y = 5;
let sum = x + y; // 15
let difference = x - y; // 5
let product = x * y; // 50
let quotient = x / y; // 2```

Next, we have the assignment operator (=). This operator is used to assign a value to a variable. For example, you could use the assignment operator to set the value of a variable called "x" to 10 like this:

```let x;
x = 10;```

Javascript also has a set of comparison operators, which allow you to compare two values. These include the equal to operator (==), the not equal to operator (!=), the greater than operator (>), and the less than operator (<). These operators return a boolean value of true or false, depending on the result of the comparison. For example:

```let x = 10;
let y = 5;
console.log(x == y); // false
console.log(x != y); // true
console.log(x > y); // true
console.log(x < y); // false```

Another important type of operator in Javascript is the logical operator. These include the and operator (&&) and the or operator (||). These operators allow you to perform logical operations on boolean values, such as determining if two conditions are both true or if at least one of them is true. For example:

```let x = 10;
let y = 5;
if (x > 0 && y > 0) {
console.log("Both x and y are positive");
}

if (x > 0 || y > 0) {
console.log("At least one of x and y is positive");
}```

Finally, we have the ternary operator (?). This operator is a shorthand way of performing an if-else statement. It takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false. For example:

```let x = 10;
let result = (x > 0) ? "positive" : "negative";
console.log(result); // "positive"```

These are just a few examples of the many operators available in Javascript. Understanding how to use these operators is an essential part of developing web applications with the language.