Operators and Expressions
Operators and expressions are fundamental concepts in programming languages. They allow you to perform operations on data, make decisions, and control the flow of a program. Let's delve into the basics of operators and expressions:
Operators:
Operators are symbols or keywords that perform operations on one or more operands. Operands can be values or variables. Here are some common types of operators:
- Arithmetic Operators:
let a = 5; let b = 3; let sum = a + b; // Addition let difference = a - b; // Subtraction let product = a * b; // Multiplication let quotient = a / b; // Division let remainder = a % b; // Modulus - Comparison Operators:
let x = 10; let y = 5; console.log(x > y); // Greater than console.log(x < y); // Less than console.log(x === y); // Equal to console.log(x !== y); // Not equal to - Logical Operators:
let isTrue = true; let isFalse = false; console.log(isTrue && isFalse); // Logical AND console.log(isTrue || isFalse); // Logical OR console.log(!isTrue); // Logical NOT - Assignment Operators:
let num = 10; num += 5; // Equivalent to num = num + 5; num -= 3; // Equivalent to num = num - 3; - Unary Operators:
let count = 5; console.log(++count); // Increment by 1 (pre-increment) console.log(--count); // Decrement by 1 (pre-decrement) - Ternary (Conditional) Operator:
let age = 20; let result = (age >= 18) ? "Adult" : "Minor";
Expressions:
Expressions are combinations of values, variables, and operators that can be evaluated to produce a result. Expressions can be as simple as a single variable or as complex as a mathematical formula. Examples:
// Arithmetic expression
let result = 2 * (3 + 5);
// Comparison expression
let isGreaterThan = 10 > 5;
// Logical expression
let isValid = (userInput !== "") && (userAge >= 18);
// Assignment expression
let total = 0;
total += 10;
Expressions are an integral part of programming as they are used in conditions, assignments, function calls, and more.
Understanding how to use operators and expressions allows you to manipulate data, make decisions, and control the behavior of your programs. These concepts are applicable across various programming languages, though syntax details may vary.