What is an Expression in JavaScript?
An expression in JavaScript is any valid unit of code that resolves to a value. This could be a simple value like a number or string, or a more complex operation like a function call or arithmetic operation.
Types of Expressions
JavaScript supports different types of expressions. Let's explore them with examples and intuitive questions.
1. Arithmetic Expressions
These are expressions that perform arithmetic operations and return numeric values.
let result = 5 + 3 * 2;
console.log(result);
Output:
11
Explanation: JavaScript evaluates 3 * 2
first (due to operator precedence), then adds 5 to get 11.
Question:
What will be the result of 10 / 2 + 3 * 2
?
Answer: First 10 / 2 = 5
, then 3 * 2 = 6
, and finally 5 + 6 = 11
2. String Expressions
These involve strings and usually use the +
operator to concatenate (combine) them.
let greeting = "Hello, " + "World!";
console.log(greeting);
Output:
Hello, World!
Explanation: The +
operator joins the two string values into one.
3. Logical Expressions
These use logical operators like &&
, ||
, and !
to return boolean values.
let isAdult = true;
let hasTicket = false;
console.log(isAdult && hasTicket);
Output:
false
Explanation: The &&
(AND) operator returns true
only if both operands are true
. Since hasTicket
is false
, the result is false
.
Question:
What does true || false
evaluate to?
Answer: true
— because the ||
(OR) operator returns true
if at least one operand is true
.
4. Assignment Expressions
An assignment expression assigns a value to a variable using the =
operator.
let score = 100;
console.log(score);
Output:
100
Explanation: score = 100
is an expression that assigns the value 100
to the variable score
.
5. Comparison Expressions
These expressions compare two values and return a boolean (true/false).
let isEqual = (10 === 10);
console.log(isEqual);
Output:
true
Explanation: The ===
operator checks for both value and type equality. Here, 10 === 10
is true.
6. Function Call Expressions
Calling a function is also an expression since it resolves to the return value of the function.
function square(x) {
return x * x;
}
let result = square(5);
console.log(result);
Output:
25
Explanation: square(5)
evaluates to 25
, so result
gets assigned that value.
Key Takeaways
- Expressions evaluate to values, unlike statements which perform actions.
- Expressions can be simple (like
5
) or complex (likeMath.max(4, 10)
). - Understanding expressions is fundamental to writing any logic in JavaScript.
Quick Quiz
Which of the following are expressions?
5 + 3
let x = 10
if (x > 5)
Answer: 1 and 2 are expressions. 3 is a conditional statement.