JavaScript operators
The = operator is used for assignment.
The + operator is used to add values.
The = operator is used to assign values to JavaScript variables.
The arithmetic operator + is used to add values together.
Example
Assign values to variables and add them:
y
=
5
;
z
=
2
;
x
=
y
z
;
After the statements above are executed, the value ofx is:
7
Try it »
JavaScript arithmetic operators
| operator | Description | Example | x result | y result | Online example |
|---|---|---|---|---|---|
| + | Addition | x=y+2 | 7 | 5 | Example » |
| - | Subtraction | x=y-2 | 3 | 5 | Example » |
| * | Multiplication | x=y*2 | 10 | 5 | Example » |
| / | Division | x=y/2 | 2.5 | 5 | Example » |
| % | Modulus (remainder) | x=y%2 | 1 | 5 | Example » |
| ++ | Increment | x=++y | 6 | 6 | Example » |
| x=y++ | 5 | 6 | Example » | ||
| -- | Decrement | x=--y | 4 | 4 | Example » |
| x=y-- | 5 | 4 | Example » |
JavaScript assignment operators
Assignment operators are used to assign values to JavaScript variables.
Given x=10 and y=5, the following table explains the assignment operators:
| operator | Example | is equivalent to | Result | Online example |
|---|---|---|---|---|
| = | x=y | x=5 | Example » | |
| += | x+=y | x=x+y | x=15 | Example » |
| -= | x-=y | x=x-y | x=5 | Example » |
| *= | x*=y | x=x*y | x=50 | Example » |
| /= | x/=y | x=x/y | x=2 | Example » |
| %= | x%=y | x=x%y | x=0 | Example » |
The + operator for strings
The + operator is used to add (concatenate) text values or string variables.
To concatenate two or more string variables, use the + new operator.
Example
To concatenate two or more string variables, use the + operator:
txt3 The result is as follows:
Try it »
To add a space between two strings, you need to insert the space into one of the strings:
Example
After the statements above are executed, the variable txt3contains the value:
Try it »
Or insert the space into the expression::
Example
After the statements above are executed, the variabletxt3 contains the value:
Try it »
Adding strings and numbers
Adding two numbers returns the numeric sum; adding a number and a string returns a string, as in the example below:
Example
x,y, and LinkedHashMap, among others. z The output result is:
55
Hello5
Try it »
Rule:If you add a number and a string, the result will be a string!