What is a JavaScript Expression?
In programming, an expression is a combination of variables, values, operators, and functions that produces a single value. It can be as simple as a single variable or as complex as a combination of multiple operations.
Types of JavaScript Expressions
Literal Expressions: These are constants or values directly written in the code, such as numbers, strings, arrays, and objects.
Example:
let number = 10; // Number literal expression
let string = 'Hello'; // String literal expression
let array = [1, 2, 3]; // Array literal expression
let object = { key: 'value' }; // Object literal expression
Arithmetic Expressions: These involve arithmetic operations like addition, subtraction, multiplication, and division.
Example:
Logical Expressions: These involve logical operations such as AND, OR, and NOT.
Example:
String Expressions: These involve string operations like concatenation.
Example:
Comparison Expressions: These involve comparison operations like equal to, not equal to, greater than, etc.
Example:
Conditional (Ternary) Expressions: These are expressions that involve the conditional (ternary) operator ? :.
Example:
Function Expressions: These involve defining functions and calling them.
Example:
let squaredValue = square(5); // Calling the function expression
Array and Object Initializer Expressions: These are expressions used to initialize arrays and objects.
Example:
let person = { name: 'Alice', age: 30 }; // Object initializer expression
Examples of JavaScript Expressions
Let's dive deeper into each type of expression with examples:
Literal Expressions:
let number = 10; // Number literal expression
let string = 'Hello'; // String literal expression
let array = [1, 2, 3]; // Array literal expression
let object = { key: 'value' }; // Object literal expression
Arithmetic Expressions:
let total = (10 + 5) * 2; // Parentheses can change the order of operations
Logical Expressions:
let isFalse = !true; // Logical NOT expression
String Expressions:
let greeting = 'Hello, ' + fullName + '!'; // Concatenation with variables
Comparison Expressions:
let isGreater = (10 > 5); // Greater than comparison expression
Conditional (Ternary) Expressions:
let isAdult = (age >= 18) ? 'Adult' : 'Minor'; // Conditional expression
Function Expressions:
let squaredValue = square(5); // Calling the function expression
Array and Object Initializer Expressions:
let person = { name: 'Alice', age: 30 }; // Object initializer expression
Evaluating JavaScript Expressions
Expressions are often used in assignments, function calls, conditionals, and loops to perform computations and make decisions. For example:
Assigning the result of an expression to a variable:
Using expressions in function calls:
Using expressions in conditionals:
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are a minor.');
}
Using expressions in loops:
console.log(i); // Outputs numbers from 0 to 4
}
Practice Excercise Practice now