DEV Community

bonnguyenitc
bonnguyenitc

Posted on

Operators in JavaScript: The Fundamentals

Operators
Operators in JavaScript are symbols that perform specific operations on operands, or values, to produce a new value. In this post, we will discuss the different types of operators available in JavaScript and how they can be used in our code.

Arithmetic Operators
Arithmetic operators perform basic arithmetic operations such as addition, subtraction, multiplication, and division. These operators are +, -, *, /, %, ++, and --.

For example, 2 + 3 would evaluate to 5 and 10 / 2 would evaluate to 5. The % operator returns the remainder of the division of two operands. For instance, 10 % 3 would evaluate to 1. The ++ and -- operators are used to increment and decrement the value of a variable by 1 respectively.

Assignment Operators
Assignment operators are used to assign a value to a variable. The most commonly used assignment operator is =. Other assignment operators include +=, -=, *=, and /=. These operators perform the respective arithmetic operation and assign the result back to the variable.

For instance, x = x + 3 can be written as x += 3.

Comparison Operators
Comparison operators are used to compare values and return a Boolean value of true or false. These operators include ==, !=, ===, !==, >, <, >=, and <=.

For example, 5 == 5 would evaluate to true, while 5 == 6 would evaluate to false. The === and !== operators perform strict equality checks, meaning they check both the value and type of the operands.

Logical Operators
Logical operators are used to perform logical operations such as and, or, and not. The && operator returns true if both operands are true, while the || operator returns true if either operand is true. The ! operator is used to negate a value and return the opposite Boolean value.

For instance, true && false would evaluate to false, while true || false would evaluate to true.

Ternary Operators
The ternary operator is a shorthand for an if statement. It is written as condition ? expression1 : expression2. If the condition is true, the operator returns expression1, otherwise it returns expression2.

For example, let x = 5 > 3 ? "yes" : "no" would assign the value "yes" to x.

Conclusion
In conclusion, operators play a crucial role in JavaScript and allow us to perform various operations on values. Understanding these operators and their use cases can greatly improve our ability to write efficient and readable code.

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted