Operators and Expressions
What Is an Expression?
An expression is a piece of code that produces a value. Think of it like a little math problem that JavaScript solves for you. When you write an expression, JavaScript evaluates it and gives you an answer. For example:
15 + 3This expression uses the addition operator (+) to combine the numbers 5 and 3. When evaluated, it gives the value 8.
Arithmetic Operators
Arithmetic operators let you perform basic math calculations. The most common ones are:
- Addition (+): Combines two numbers. Example: 5 + 3 gives 8.
- Subtraction (-): Finds the difference between two numbers. Example: 10 - 4 gives 6.
- Multiplication (*): Multiplies two numbers. Example: 4 * 2 gives 8.
- Division (/): Divides one number by another. Example: 20 / 5 gives 4.
- Remainder (%): Gives the remainder after division. Example:** 7 % 3** gives** 1**.
Combining Operators in Expressions
You can combine values and operators to build more complex expressions. For instance, if you write:
1(10 + 5) * 2JavaScript first calculates the expression in parentheses (10 + 5 equals 15), and then multiplies that result by 2, giving 30.
Using Expressions with Variables
Often, you’ll use expressions with variables to update values. For example:
1let counter = 0;
2counter = counter + 1;
3console.log(counter);Here, the expression counter + 1 adds 1 to the current value of counter, and then we update counter with the new value.
Exercises
Learn to hack — start here
Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.