Understanding
Expressions in JavaScript



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

Quick Quiz

Which of the following are expressions?

  1. 5 + 3
  2. let x = 10
  3. if (x > 5)

Answer: 1 and 2 are expressions. 3 is a conditional statement.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M