JavaScript Operators and Expressions: A Complete Beginner’s Guide

5/5 - (1 vote)

Introduction:

JavaScript is like a toolbox filled with various tools to build and manipulate web pages. Among these tools, operators and expressions are some of the most essential. They are the building blocks that help you perform calculations, compare values, assign data, and much more.

In this beginner’s guide, we will dive deep into JavaScript’s basic operators and expressions. You will learn about different types of operators, such as arithmetic, assignment, unary, comparison, relational, and conditional operators. By the end, you’ll understand how these operators work and how they are used to create smart and interactive web applications. So, let’s jump in and start learning!

1. What Are Operators and Expressions?

Before we start, let’s understand what operators and expressions are.

  • Operators are symbols that perform operations on variables and values. For example, + is an operator that adds two numbers.
  • Expressions are combinations of values, variables, and operators that JavaScript evaluates to produce a result. For example, 5 + 3 is an expression that evaluates to 8.

Understanding these two concepts is crucial for writing any JavaScript code!

2. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical calculations like addition, subtraction, multiplication, and division. Here are the most common arithmetic operators:

  • Addition (+): Adds two numbers.
  • Subtraction (-): Subtracts one number from another.
  • Multiplication (*): Multiplies two numbers.
  • Division (/): Divides one number by another.
  • Modulus (%): Finds the remainder after division.
  • Exponentiation (``)**: Raises the first number to the power of the second number.
OperatorSymbolExampleExplanation
Addition+5 + 2Adds two numbers together. Result: 7.
Subtraction-8 - 3Subtracts the second number from the first. Result: 5.
Multiplication*4 * 2Multiplies two numbers. Result: 8.
Division/9 / 3Divides the first number by the second. Result: 3.
Modulus%10 % 3Returns the remainder of dividing two numbers. Result: 1.

Example:

let a = 10;
let b = 3;
console.log(a + b);  // Output: 13
console.log(a - b);  // Output: 7
console.log(a * b);  // Output: 30
console.log(a / b);  // Output: 3.333...
console.log(a % b);  // Output: 1
console.log(a ** b); // Output: 1000 (10 to the power of 3)
JavaScript

3. Assignment Operators

Assignment operators are used to assign values to variables. The most basic assignment operator is the equal sign (=), which assigns the value on the right to the variable on the left. There are also combined operators that perform an operation and then assign the result.

  • Equal (=): Assigns a value.
  • Add and Assign (+=): Adds a value and then assigns.
  • Subtract and Assign (-=): Subtracts a value and then assigns.
  • Multiply and Assign (*=): Multiplies a value and then assigns.
  • Divide and Assign (/=): Divides a value and then assigns.
OperatorSymbolExampleExplanation
Assign=x = 5Assigns the value 5 to variable x.
Add and Assign+=x += 3Adds 3 to the current value of x.
Subtract and Assign-=x -= 2Subtracts 2 from the current value of x.
Multiply and Assign*=x *= 4Multiplies the current value of x by 4.
Divide and Assign/=x /= 5Divides the current value of x by 5.

Example:

let x = 5;
x += 3; // x = x + 3; Output: 8
x -= 2; // x = x - 2; Output: 6
x *= 4; // x = x * 4; Output: 24
x /= 2; // x = x / 2; Output: 12
JavaScript

4. Unary Operators

A unary operator works with a single operand, meaning it takes only one value to perform its operation. The most common unary operators in JavaScript are:

  • Unary Plus (+): Tries to convert the operand into a number.
  • Unary Minus (-): Negates the number, making it negative.
  • Increment (++): Adds 1 to the value.
  • Decrement (--): Subtracts 1 from the value.
  • Logical NOT (!): Converts the operand to its opposite boolean value.
OperatorSymbolExampleExplanation
Increment++x++Increases x by 1.
Decrement--x--Decreases x by 1.
Negation--xReturns the negative version of x.

Example:

let num = 5;
console.log(+num);   // Output: 5 (Already a number)
console.log(-num);   // Output: -5 (Negative value)
num++;
console.log(num);    // Output: 6 (Incremented by 1)
num--;
console.log(num);    // Output: 5 (Decremented by 1)
let isHappy = true;
console.log(!isHappy); // Output: false (Opposite boolean)
JavaScript

5. Comparison Operators

Comparison operators compare two values and return a boolean result (true or false). They are mainly used in conditional statements like if or while.

  • Equal to (==): Returns true if values are equal.
  • Not equal to (!=): Returns true if values are not equal.
  • Strictly equal to (===): Returns true if values and types are equal.
  • Strictly not equal to (!==): Returns true if values or types are not equal.
  • Greater than (>): Returns true if the left value is greater.
  • Less than (<): Returns true if the left value is smaller.
  • Greater than or equal to (>=): Returns true if the left value is greater or equal.
  • Less than or equal to (<=): Returns true if the left value is smaller or equal.
OperatorSymbolExampleExplanation
Equal to==x == yReturns true if x equals y.
Not equal to!=x != yReturns true if x does not equal y.
Strict equal to===x === yReturns true if x and y are equal and of the same type.
Strict not equal to!==x !== yReturns true if x and y are not equal or not of the same type.
Greater than>x > yReturns true if x is greater than y.
Less than<x < yReturns true if x is less than y.

Example:

let age = 15;
console.log(age == 15);  // Output: true
console.log(age === '15'); // Output: false (Different types)
console.log(age != 20);   // Output: true
console.log(age > 10);    // Output: true
console.log(age <= 15);   // Output: true
JavaScript

6. Relational Operators

Relational operators are used to compare two values and establish a relationship between them, much like comparison operators.

  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)

Relational operators are often used with loops and conditions.

Operator NameSymbolExampleDescription
Equality (Loose)==5 == '5'Compares values for equality after type conversion.
Equality (Strict)===5 === '5'Compares values for equality without type conversion.
Inequality (Loose)!=5 != '5'Compares values for inequality after type conversion.
Inequality (Strict)!==5 !== '5'Compares values for inequality without type conversion.
Greater Than>10 > 5Checks if the value on the left is greater than the value on the right.
Less Than<10 < 5Checks if the value on the left is less than the value on the right.
Greater Than or Equal>=10 >= 10Checks if the value on the left is greater than or equal to the value on the right.
Less Than or Equal<=10 <= 5Checks if the value on the left is less than or equal to the value on the right.

Example:

let score = 80;
if (score >= 50) {
    console.log("You passed the exam!");
} else {
    console.log("You need to study more.");
}
JavaScript

7. Conditional Operators

Conditional operators, also known as the ternary operator (? :), are used to make decisions in a single line of code. The ternary operator takes three operands: a condition followed by a question mark (?), then the expression to execute if the condition is true, and finally, the expression to execute if the condition is false, separated by a colon (:).

Syntax:

condition ? expressionIfTrue : expressionIfFalse;
JavaScript

Example:

let age = 18;
let canVote = (age >= 18) ? "Yes, you can vote!" : "Sorry, you can't vote yet.";
console.log(canVote); // Output: "Yes, you can vote!"
JavaScript

8. Examples of Combining Different Operators

JavaScript allows you to combine different operators to perform complex calculations and logic.

Example:

let a = 5;
let b = 10;
let c = (a + b) * 2;  // Addition, then multiplication
console.log(c);  // Output: 30

let isValid = (a < b) && (b > 0); // Comparison and logical operator
console.log(isValid);  // Output: true
JavaScript

9. Common Mistakes and Tips

  • Using = Instead of == or ===: Remember, = is for assignment, while == and === are for comparison.
  • Confusing == and ===: Use === for strict comparison to avoid unexpected results.
  • Forgetting Operator Precedence: JavaScript follows specific rules for the order in which operators are evaluated. Use parentheses () to clarify and control the order.

Conclusion

Understanding JavaScript operators and expressions is essential for anyone learning to code. These tools help you perform calculations, make decisions, and control

the flow of your program. Practice using these operators, experiment with different expressions, and soon you’ll find them easy and fun to use!

Remember, every JavaScript program you write will use these operators, so mastering them will make your coding journey much smoother. Keep experimenting, and don’t be afraid to try new things!

References

Spread the love

Leave a Comment