JavaScript Operators
Operator = is used for assignment.
Operator + is used for addition.
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 together:
y=5;
z=2;
x=y+z;
After the above statements are executed, the value of x is:
7
JavaScript Arithmetic Operators
Arithmetic operations between/among values.
Given y=5, the table below explains the 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 table below explains the assignment operators:
Operator | Example | Same As | 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) string values or string variables together.
To concatenate two or more string variables, use the +
operator.
Example
To concatenate two or more string variables, use the +
operator:
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 is:
What a verynice day
To add a space between two strings, insert the space into one of the strings:
Example
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
After the above statements are executed, the variable txt3 contains:
What a very nice day
Or insert the space in the expression:
Example
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the above statements are executed, the variable txt3 contains:
What a very nice day
Adding Strings and Numbers
Adding two numbers returns the sum, but adding a number and a string returns a string, as shown in the following example:
Example
x=5+5;
y="5"+5;
z="Hello"+5;
The results for x, y, and z are:
10
55
Hello5
Rule: If you add a number and a string, the result will be a string!