Skip to main content

JavaScript Expressions

Introduction

An expression in JavaScript is a piece of code that produces a value. Think of expressions as phrases in the JavaScript language that can be evaluated to determine their meaning. Understanding expressions is fundamental to mastering JavaScript as they are the building blocks for your code.

Expressions can be as simple as a single value or variable, or as complex as a combination of values, variables, and operators that need to be calculated. In this tutorial, we'll explore the various types of expressions in JavaScript and how to use them effectively.

What are JavaScript Expressions?

An expression is any valid unit of code that resolves to a value. JavaScript has various types of expressions, each serving different purposes in your code.

Here's a simple example:

javascript
// This is an expression that evaluates to 10
5 + 5

When the JavaScript engine evaluates this expression, it produces the value 10.

Types of JavaScript Expressions

Let's explore the main types of expressions you'll use in JavaScript:

1. Arithmetic Expressions

Arithmetic expressions perform mathematical calculations and return a numeric value.

javascript
// Addition
let sum = 5 + 3; // Evaluates to 8

// Subtraction
let difference = 10 - 4; // Evaluates to 6

// Multiplication
let product = 6 * 7; // Evaluates to 42

// Division
let quotient = 20 / 5; // Evaluates to 4

// Modulus (remainder)
let remainder = 17 % 3; // Evaluates to 2

// Exponentiation
let power = 2 ** 3; // Evaluates to 8

console.log(sum, difference, product, quotient, remainder, power);
// Output: 8 6 42 4 2 8

2. String Expressions

String expressions involve operations with text values.

javascript
// String concatenation
let greeting = "Hello, " + "world!";
console.log(greeting); // Output: Hello, world!

// Template literals (ES6)
let name = "Alice";
let welcomeMessage = `Welcome, ${name}!`;
console.log(welcomeMessage); // Output: Welcome, Alice!

// String expressions can also use methods
let shout = "hello".toUpperCase();
console.log(shout); // Output: HELLO

3. Logical Expressions

Logical expressions evaluate to Boolean values (true or false).

javascript
// Comparison expressions
let isGreater = 5 > 3; // Evaluates to true
let isEqual = 4 === 4; // Evaluates to true
let isNotEqual = 7 !== 7; // Evaluates to false

// Logical operators
let andOperator = true && false; // Evaluates to false
let orOperator = true || false; // Evaluates to true
let notOperator = !true; // Evaluates to false

console.log(isGreater, isEqual, isNotEqual);
// Output: true true false

console.log(andOperator, orOperator, notOperator);
// Output: false true false

4. Primary Expressions

The simplest expressions in JavaScript include literals and variables.

javascript
// Literals (fixed values)
42 // Numeric literal
"Hello" // String literal
true // Boolean literal
null // null literal
[1, 2, 3] // Array literal
{name: "John", age: 30} // Object literal

// Variables
let x = 10;
console.log(x); // Output: 10

5. Assignment Expressions

Assignment expressions assign values to variables and also return a value.

javascript
let x;
let y;

// Simple assignment
x = 5; // Assigns 5 to x and evaluates to 5
console.log(x); // Output: 5

// Chained assignment
x = y = 10; // Assigns 10 to y, then assigns y's value to x
console.log(x, y); // Output: 10 10

// Assignment with operation
let num = 5;
num += 3; // Same as: num = num + 3
console.log(num); // Output: 8

6. Function Expressions

Functions can be defined and used within expressions.

javascript
// Function declaration (not an expression)
function greet(name) {
return `Hello, ${name}!`;
}

// Function expression
const sayHello = function(name) {
return `Hello, ${name}!`;
};

// Arrow function expression (ES6)
const greetPerson = (name) => `Hello, ${name}!`;

console.log(greet("Alice")); // Output: Hello, Alice!
console.log(sayHello("Bob")); // Output: Hello, Bob!
console.log(greetPerson("Charlie")); // Output: Hello, Charlie!

Complex Expressions

In real-world applications, you'll often combine different types of expressions to create more complex ones:

javascript
// Combining arithmetic, logical, and assignment expressions
let age = 25;
let status = (age >= 18) ? "adult" : "minor";

console.log(status); // Output: adult

// Function expression with arithmetic and logical expressions
const calculateDiscount = (price, isMember) => {
return isMember ? price * 0.9 : price * 0.95;
};

let finalPrice = calculateDiscount(100, true);
console.log(finalPrice); // Output: 90

Expression Evaluation

When JavaScript encounters an expression, it evaluates it from left to right, following the rules of operator precedence (similar to math rules like PEMDAS).

javascript
// Operator precedence in action
let result = 2 + 3 * 4; // Multiplication happens first
console.log(result); // Output: 14, not 20

// Parentheses can change the order of evaluation
let modifiedResult = (2 + 3) * 4;
console.log(modifiedResult); // Output: 20

Practical Examples

Let's look at some practical examples of expressions in real-world scenarios:

1. Shopping Cart Total Calculation

javascript
const calculateTotal = (items, taxRate) => {
// Sum up all item prices (using array reduce expression)
const subtotal = items.reduce((sum, item) => sum + item.price, 0);

// Calculate tax amount
const taxAmount = subtotal * taxRate;

// Calculate final total
return subtotal + taxAmount;
};

const cartItems = [
{ name: "T-shirt", price: 15.99 },
{ name: "Jeans", price: 39.99 },
{ name: "Shoes", price: 59.99 }
];

const total = calculateTotal(cartItems, 0.08);
console.log(`Shopping cart total: $${total.toFixed(2)}`);
// Output: Shopping cart total: $125.45

2. Form Validation

javascript
const validateForm = (username, password) => {
// Username must be at least 5 characters
const isUsernameValid = username.length >= 5;

// Password must be at least 8 characters and contain a number
const hasNumber = /\d/.test(password);
const isPasswordLongEnough = password.length >= 8;
const isPasswordValid = isPasswordLongEnough && hasNumber;

// Return true only if both username and password are valid
return isUsernameValid && isPasswordValid;
};

console.log(validateForm("john", "pass123")); // Output: false (username too short)
console.log(validateForm("johndoe", "pass")); // Output: false (password too short)
console.log(validateForm("johndoe", "password")); // Output: false (no number in password)
console.log(validateForm("johndoe", "password123")); // Output: true

Side Effects in Expressions

Most expressions in JavaScript simply evaluate to a value without changing anything else. However, some expressions have side effects, meaning they change the state of your program.

javascript
let counter = 0;

// This expression has a side effect: it increments counter
counter++;
console.log(counter); // Output: 1

// Assignment expressions have side effects
let x = 5; // Side effect: variable x now stores the value 5

// Function calls may have side effects
function modifyArray(arr) {
arr.push(4); // Modifies the original array
}

let numbers = [1, 2, 3];
modifyArray(numbers);
console.log(numbers); // Output: [1, 2, 3, 4]

Summary

JavaScript expressions are the building blocks of code that evaluate to produce values. They can be as simple as a literal value or variable, or as complex as a combination of operators, function calls, and other elements. Understanding expressions is crucial for writing effective JavaScript code.

We've covered:

  • Basic types of expressions: arithmetic, string, logical, primary, assignment, and function expressions
  • How expressions are evaluated
  • Practical examples of expressions in real-world scenarios
  • Side effects in expressions

As you continue to learn JavaScript, you'll become more comfortable combining these expressions in creative ways to solve complex problems.

Additional Resources and Exercises

Resources

Exercises

  1. Temperature Converter: Write an expression that converts Celsius to Fahrenheit (formula: F = C * 9/5 + 32).

  2. String Manipulator: Create a function that takes a full name string and returns the initials.

  3. Calculator: Build a simple calculator function that takes two numbers and an operator string ('+', '-', '*', or '/') and returns the result of the calculation.

  4. Age Classifier: Write an expression using the ternary operator that classifies an age into categories: "Child" (0-12), "Teenager" (13-19), "Adult" (20-64), or "Senior" (65+).

  5. Challenge: Create a function that calculates the total price after applying a discount, but only if the purchase amount is above a certain threshold. Use a combination of logical and arithmetic expressions.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)