DEV Community

Cover image for Working with Operators and Expressions in JavaScript
Lordson Ajatiton
Lordson Ajatiton

Posted on

Working with Operators and Expressions in JavaScript

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. For example, the addition operator (+) adds two numbers and the multiplication operator (*) multiplies two numbers.

JavaScript has a wide range of operators, including arithmetic, assignment, comparison, logical, and more. Let's take a look at some examples:

Arithmetic Operators

The most common arithmetic operators are +, -, *, /, and %.

Here's an example of how to use them:

let a = 10;
let b = 5;

console.log(a + b); // Output: 15
console.log(a - b); // Output: 5
console.log(a * b); // Output: 50
console.log(a / b); // Output: 2
console.log(a % b); // Output: 0
Enter fullscreen mode Exit fullscreen mode

Assignment Operators

Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (=), which assigns the value on the right to the variable on the left.

Here's an example:

let x = 10;
let y = 5;

x = y;
console.log(x); // Output: 5
Enter fullscreen mode Exit fullscreen mode

JavaScript also has compound assignment operators, which combine a math operation and assignment.
For example, x += y is the same as x = x + y.

Comparison Operators

Comparison operators are used to compare two values and return a boolean value (true or false). The most common comparison operators are ==, !=, >, <, >=, and <=.

Here's an example:

let x = 10;
let y = 5;

console.log(x == y); // Output: false
console.log(x != y); // Output: true
console.log(x > y); // Output: true
console.log(x < y); // Output: false
console.log(x >= y); // Output: true
console.log(x <= y); // Output: false
Enter fullscreen mode Exit fullscreen mode

Logical Operators

Logical operators are used to combine conditional statements. The most common logical operators are && (and), || (or), and ! (not).

Here's an example:

let x = 10;
let y = 5;

console.log(x > 0 && y > 0); // Output: true
console.log(x > 0 || y > 0); // Output: true
console.log(!(x > 0)); // Output: false
Enter fullscreen mode Exit fullscreen mode

Expressions are combinations of values, variables, and operators that produce a result.
For example, the expression x + y is a combination of the values of x and y, and the operator +.

In JavaScript, you can use expressions as stand-alone statements or as part of a larger statement.
For example:

let x = 10;
let y = 5;

let result = x + y;
console.log(result); // Output: 15

if (x > y) {
  console.log('x is greater than y');
}
Enter fullscreen mode Exit fullscreen mode

Where x > y and x + y are expressions.

Conclusion

I hope this tutorial has been helpful in introducing you to operators and expressions in JavaScript. Happy coding!

Top comments (0)