JavaScript operators and expressions
2 min
The previous chapter covered how to declare and use variables in JavaScript, along with the data types available. This chapter explores operators and expressions, which let you work with those variables and types in more advanced ways. We will also see how control flow statements run code depending on specific conditions.
Operators in JavaScript
In JavaScript, operators are symbols that stand for a mathematical or logical operation to perform on variables or values. Here are some of the operators used most often in JavaScript:
Arithmetic operators
These operators perform basic maths: addition, subtraction, multiplication and division. Here is how they are used:
let a = 5;
let b = 2;
let c = a + b; // c is 7
let d = a - b; // d is 3
let e = a * b; // e is 10
let f = a / b; // f is 2.5Comparison operators
These operators compare two values and return a boolean (true or false) depending on the result of the comparison. Here is how they are used:
let a = 5;
let b = 2;
console.log(a > b); // Prints "true"
console.log(a < b); // Prints "false"
console.log(a >= b); // Prints "true"
console.log(a <= b); // Prints "false"
console.log(a == b); // Prints "false"
console.log(a != b); // Prints "true"Note that the equality operator (==) checks whether the values of the variables are equal, while the inequality operator (!=) checks whether they differ. There is also the strict equality operator (===) and the strict inequality operator (!==), which check both the values and the types of the variables. For example:
let a = 5;
let b = '5';
console.log(a == b); // Prints "true"
console.log(a === b); // Prints "false"
console.log(a != b); // Prints "false"
console.log(a !== b); // Prints "true"Logical operators
These operators combine boolean expressions with AND (&&) and OR (||). Here is how they are used:
let a = true;
let b = false;
console.log(a && b); // Prints "false"
console.log(a || b); // Prints "true"Expressions in JavaScript
An expression in JavaScript is a combination of values, variables and operators that returns a value. The expression “5 + 2”, for instance, returns the value “7”. You can use expressions in the body of your code to compute something and assign the result to a variable, as in the following example:
let a = 5;
let b = 2;
let c = a + b; // c is 7Used with judgement, operators and expressions let you work with variables and data very precisely, and build complex programs.
Conclusion
This chapter covered the operators and expressions available in JavaScript and how to use them to work with variables and data in more advanced ways. The next chapter looks at control flow statements, which run code depending on specific conditions. These concepts will serve you well when writing larger and faster JavaScript programs.