Operators and Expressions
Expressions are combinations of values, variables, and operators that evaluate to a single value. They are a fundamental part of any programming language and are used to perform calculations, make comparisons, and assign values.
Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
%: Modulus (remainder)
Here’s an example of how to use these operators in an expression:
var result = 3 + 5; // 8 result = result * 2; // 16 result = result / 4; // 4 result = result % 3; // 1
Comparison operators are used to compare values and return a boolean value of
==: Equal to
!=: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
Here’s an example of how to use comparison operators in an expression:
var result = 3 > 5; // false result = 3 >= 3; // true result = "a" == "a"; // true result = "a" != "b"; // true
Logical operators are used to perform logical operations like
Here’s an example of how to use logical operators in an expression:
var result = true && true; // true result = true || false; // true result = !true; //false
Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (
=), which assigns a value to a variable.
There are also compound assignment operators that perform an operation and assign the result to a variable in a single step. These include:
+=: Addition assignment
-=: Subtraction assignment
*=: Multiplication assignment
/=: Division assignment
Here’s an example of how to use assignment operators in an expression:
var result = 0; result += 10; // 10 result -= 5; // 5 result *= 2; // 10 result /= 2; // 5
var result = 2 + 3 * 4;
will evaluate to
20, because the multiplication is performed before the addition.
You can use parentheses to specify the order in which operations should be performed, like this:
var result = (2 + 3) * 4;
This will evaluate to
20, because the addition is performed first inside the parentheses.
To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.