JavaScript Operators
JavaScript Operators
The assignment operator (=) assigns a value to a variable. Assign values to variables and add them together:
var x = 5; // assign the value 5 to x
var y = 2; // assign the value 2 to y
var z = x + y;
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:
Much Like Algebra
In programming, just like in algebra, we use variables (like price1) to hold values. In programming, just like in algebra, we use variables in expressions (total = price1 + price2). From the example below, you can calculate the total to be 11.
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
** | Exponentiation (ES2016) |
/ | Division |
% | Modulus (Division Remainder) |
++ | Increment |
-- | Decrement |
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Operator | Example | Same as |
---|---|---|
= | x=y | x=y |
+= | x+=y | x=x+y |
-= | x-=y | x=x-y |
*= | x*=y | x=x*y |
/= | x/=y | x=x/y |
%= | x%=y | x=x%y |
**= | x**=y | x=x**y |
JavaScript String Operators
The + operator can also be used to add (concatenate) strings.When used on strings, the + operator is called the concatenation operator
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will return a string:
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
JavaScript Comparison Operators
Operator | Description |
---|---|
== | equal to |
=== | equal value and equal type |
!= | not equal |
!== | not equal value or not equal type |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
? | ternary operator |
JavaScript Logical Operators
Operator | Description |
---|---|
&& | logical and |
|| | logical or |
!= | logical not |
JavaScript Type Operators
Operator | Description |
---|---|
Typeof | Returns the type of a variable |
Instanceof | Returns true if an object is an instance of an object type |
JavaScript Type Operators
Operator | Description | Example | Same as | Result | Decimal | |
---|---|---|---|---|---|---|
& | AND | 5 & 1 | 0101 & 0001 | 0001 | 1 | |
| | OR | 5 | 1 | 0101 | 0001 | 0101 | 5 | |
~ | NOT | 5 ~ 1 | ~0101 | 1010 | 10 | |
^ | XOR | 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 | |
<< | Zero fill left shift | 5 << 1 | 0101 << 1 | 1010 | 10 | |
>> | Signed right shift | 5 >> 1 | 5 << 1 | 0101 >> 1 | 0010 | 2 |
<<< | Signed right shift | 5<<<1 | 5 <<< 1 | 0101 <<< 1 | 1010 | 2 |