JavaScript Operators
The operator = is used for assignment.
The operator + is used to add value.
The operator = is used to assign values to JavaScript variables.
The arithmetic operator + is used to add up values.
Example
Specify the variable value and add the values:
y=5;
z=2;
x=y+z;
After the above statement is executed, the value of x is:
7
JavaScript Arithmetic Operators
The following table explains these arithmetic operators:
Operator | Description | Example | x - Result | y - Parameter | Try it! |
---|---|---|---|---|---|
+ | Addition | x=y+2 | 7 | 5 | |
- | Subtraction | x=y-2 | 3 | 5 | Try It! |
* | Multiplication | x=y*2 | 10 | 5 | Try It! |
/ | Division | x=y/2 | 2.5 | 5 | Try It! |
% | Modulo (Remainder) | x=y%2 | 1 | 5 | Try It! |
++ | Self-increasement | x=++y | 6 | 6 | Try It! |
x=y++ | 5 | 6 | Try It! | ||
-- | Self-decrement | x=--y | 4 | 4 | Try It! |
x=y-- | 5 | 4 | Try It! |
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 | Formular | Equivalent | Result | Try It! |
---|---|---|---|---|
= | x=y | x=5 | Try It! | |
+= | x+=y | x=x+y | x=15 | Try It! |
-= | x-=y | x=x-y | x=5 | Try It! |
*= | x*=y | x=x*y | x=50 | Try It! |
/= | x/=y | x=x/y | x=2 | Try It! |
%= | x%=y | x=x%y | x=0 | Try It! |
+ Operator for strings
The + operator is used to add (concatenate) text values or string variables.
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 results of the txt3 operation are as follows:
What a verynice day
To add a space between two strings, you need to insert the space into a string:
Example
txt1="What a very "; txt2="nice day"; txt3=txt1+txt2;
After the above statement is executed, the value contained in the variable txt3 is:
What a very nice day
Insert spaces into the expression::
Example
txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2;
After the above statement is executed, the value contained in the variable txt3 is:
What a very nice day
Add Strings and Numbers
Add two numbers, return the sum of the numbers, if the number is added to the string, return the string, as in the following example:
Example
x=5+5; y="5"+5; z="Hello"+5;
The output of x , y , and z is:
10
55
Hello5
Important: If you add a number to a string, the result will become a string!