Hello everyone and welcome back to a weekly article from the JavaScript Corner. In this week’s article I will be covering Operators and Expressions in JavaScript.
Whether you’re a front-end engineer or work in web development, understanding JavaScript operators and expressions is crucial for writing efficient and effective code. This post will delve into the various types of operators and expressions in JavaScript, providing detailed explanations and practical code samples.
What are Operators and Expressions?
In JavaScript, operators are symbols that perform specific operations on operands. An expression is a combination of values, variables, and operators that evaluates to a single value.
> "An expression is any valid unit of code that resolves to a value." - MDN Web Docs
Types of Operators
1. Arithmetic Operators
Arithmetic operators perform mathematical operations on numeric operands. let a = 10; let b = 5; console.log(a + b); // Addition: 15 console.log(a - b); // Subtraction: 5 console.log(a * b); // Multiplication: 50 console.log(a / b); // Division: 2 console.log(a % b); // Modulus (remainder): 0 console.log(a ** b); // Exponentiation: 100000
let a = 10;
let b = 5;
console.log(a + b); // Addition: 15
console.log(a - b); // Subtraction: 5
console.log(a * b); // Multiplication: 50
console.log(a / b); // Division: 2
console.log(a % b); // Modulus (remainder): 0
console.log(a ** b); // Exponentiation: 100000
Let's explore each arithmetic operator in more detail:
Addition (+)
Adds two numbers or concatenates strings
Can be used for type coercion
console.log(5 + 3); // 8
console.log('5' + 3); // '53' (string concatenation)
console.log(+'5' + 3); // 8 (type coercion)
Subtraction (-)
Subtracts the right operand from the left operand
Can be used as a unary operator to negate a value
console.log(5 - 3); // 2
console.log(-5); // -5 (unary negation)
Multiplication (*)
Multiplies two numbers
console.log(5 * 3); // 15
Division (/)
Divides the left operand by the right operand
Always returns a floating-point number in JavaScript
console.log(10 / 3); // 3.3333333333333335
Modulus (%)
Returns the remainder of a division operation
console.log(10 % 3); // 1
Exponentiation (**)
Raises the left operand to the power of the right operand
console.log(2 ** 3); // 8
2. Assignment Operators
Assignment operators assign values to variables.
let x = 5;
x += 3; // Equivalent to: x = x + 3
console.log(x); // 8
x *= 2; // Equivalent to: x = x * 2
console.log(x); // 16
Assignment operators often combine arithmetic operations with assignment for concise code:
let y = 10;
y -= 4; // Equivalent to: y = y - 4
y /= 2; // Equivalent to: y = y / 2
y %= 3; // Equivalent to: y = y % 3
3. Comparison Operators
Comparison operators compare two values and return a boolean result.
let a = 5;
let b = '5';
console.log(a == b); // Equality: true (type coercion)
console.log(a === b); // Strict equality: false (no type coercion)
console.log(a != b); // Inequality: false
console.log(a !== b); // Strict inequality: true
console.log(a > 3); // Greater than: true
console.log(a <= 5); // Less than or equal to: true
These operators are essential for conditional statements and loops. The difference between `==` and `===` is particularly important:
- `==` performs type coercion before comparison
- `===` compares both value and type without coercion
4. Logical Operators
Logical operators perform logical operations and are typically used with boolean values.
let x = true;
let y = false;
console.log(x && y); // Logical AND: false
console.log(x || y); // Logical OR: true
console.log(!x); // Logical NOT: false
Logical operators can also be used with non-boolean values and exhibit short-circuit evaluation:
// Short-circuit evaluation
console.log(true || someExpensiveOperation()); // true, someExpensiveOperation() is not called
console.log(false && someExpensiveOperation()); // false, someExpensiveOperation() is not called
5. Unary Operators
Unary operators work on a single operand.
let a = 5;
console.log(typeof a); // 'number'
let b = '5';
console.log(+b); // Unary plus: converts to number 5
let c = true;
console.log(!c); // Logical NOT: false
Additional unary operators include increment and decrement:
let d = 10;
console.log(d++); // 10 (post-increment: returns, then increments)
console.log(++d); // 12 (pre-increment: increments, then returns)
6. Conditional (Ternary) Operator
The conditional operator is the only JavaScript operator that takes three operands.
et age = 20;
let canVote = (age >= 18) ? 'Yes' : 'No';
console.log(canVote); // 'Yes'
This operator provides a concise way to write an if-else statement in a single line.
Expressions
Expressions are combinations of values, variables, and operators that resolve to a single value. Here are some examples:
1. Arithmetic Expressions
let result = 5 * (10 - 3) + 2;
console.log(result); // 37
2. String Expressions
let greeting = 'Hello' + ' ' + 'World!';
console.log(greeting); // 'Hello World!'
3. Logical Expressions
let isAdult = (age >= 18) && (hasID === true);
4. Assignment Expressions
let x, y;
y = x = 5; // Assigns 5 to x, then assigns the result (5) to y
console.log(x, y); // 5 5
Expressions can be more complex, combining different types of operations:
// Complex arithmetic expression
let complexResult = 5 * (10 - 3) + 2 ** 3;
// String and arithmetic expression
let fullName = 'John' + ' ' + 'Doe' + ' ' + (30 + 5);
// Logical and comparison expression
let isEligible = (age >= 18) && (hasID === true) || (isSpecialCase && age > 15);
Operator Precedence
Operator precedence determines the order in which operators are evaluated in an expression.
let result = 2 + 3 * 4;
console.log(result); // 14 (not 20, because * has higher precedence than +)
To override the default precedence, use parentheses:
let result = (2 + 3) * 4;
console.log(result); // 20
Understanding operator precedence is crucial for writing correct expressions:
let complexExpression = 2 + 3 * 4 - 1; // 13 (multiplication before addition and subtraction)
let parenthesesExample = (2 + 3) * (4 - 1); // 15 (parentheses override default precedence)
Conclusion
Understanding JavaScript operators and expressions is fundamental to writing effective JavaScript code. They allow you to perform calculations, make comparisons, assign values, and create complex logic in your programs. As you continue your journey as a front-end engineer, mastering these concepts will greatly enhance your ability to write efficient and powerful JavaScript applications.
Remember, practice makes perfect. Try experimenting with different operators and expressions to solidify your understanding!
By thoroughly understanding these operators and expressions, you'll be better equipped to write clear, efficient, and bug-free JavaScript code. Keep practicing and exploring these concepts in your projects to reinforce your knowledge.
This is all for this week folks, in the next article I will be covering Control structures (if-else, switch, loops).
Till then, happy coding!
https://open.substack.com/pub/emilyalexandraguglielmo/p/my-first-public-blogpost?r=2mtps5&utm_medium=ios