Operators

JavaScript can perform mathematical operations. They are performed by logical operators and comparison operators.

These are:

Sign Description Example Returned value
== equality sign 2 == 4 false
!= inequality sign 2 != 4 true
> greater than 2 > 4 false
< less than 2 < 4 true
>= greater than or equal to 2 >= 4 false
<= less than or equal to 4 <= 4 true
&& and ((2<10) && (3>1)) true
|| or ((5 == 5) || (3 == 5)) true
! negation !(5 == 3) true

In addition, you can also use standard mathematical operators such as: +, -, *, /.

In JavaScript, there is a modulo operator (remainder of division). It is extremely useful when you want to check if the element is even. This operator is described by the percent sign (%).

9 % 2; // will return 1, because 9/2 is 4, and 1 is the remainder

Here's an example on which you can experiment:

Run an example of modulo

Excercise 1

In the JavaScript code you will find several variables containing the result of comparison of numbers, i.e. logical values (boolean) known to you from the previous lesson. For better readability, comparison operations are in brackets. Replace equality signs with the appropriate operators so that the results below return true in each case. Go to the first exercise:

Run exercise #1

Tip:

var exN = (5 <= 8); // returns true, because 5 is less than or equal to 8
var exN = (5 >= 8); // returns false, because 5 is not greater than nor equal to 8

Result of example 1: false
Result of example 2: false
Result of example 3: false
Result of example 4: false

Excercise 2

This task is analogous to the previous one. Replace signs of inequality in variables with appropriate operators so that the equations below return false in each case.

Proceed to the second exercise: Run exercise #2

Result of example 1: true
Result of example 2: true
Result of example 3: true
Result of example 4: true

Excercise 3

Moving on to more complicated topics, we introduce logical operators. Let's discuss the example below:

var exN = (5 <= 8) && (1 > 3);
The value in the exN variable will be false. Why? Because the computer will do the following:

Run exercise #3

In the JavaScript code replace the equality or inequality signs with appropriate operators, so that the equations return true in each case. Do not change logical operators!

Result of example 1: false
Result of example 2: false
Result of example 3: false

Excercise 4

This task is analogous to the previous one. In JavaScript code, replace the operators with appropriate ones so that the results below return false in each case.

Run exercise #4

Result of example 1: true
Result of example 2: true
Result of example 3: true

Next chapter: Conditional statements IF »