Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript operators

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

Arithmetic operations between and/or values.

With y=5, the table below explains these 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:

txt1="What a very"; txt2="nice day"; txt3=txt1+txt2;

txt3 The result is as follows:

What a verynice day

Try it »

To add a space between two strings, you need to insert the space into one of the strings:

Example

txt1="What a very "; txt2="nice day"; txt3=txt1+txt2;

After the statements above are executed, the variable txt3contains the value:

What a very nice day

Try it »

Or insert the space into the expression::

Example

txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2;

After the statements above are executed, the variabletxt3 contains the value:

What a very nice day

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=5+5; y="5"+5; z="Hello"+5;

x,y, and LinkedHashMap, among others. z The output result is:

10
55
Hello5

Try it »

Rule:If you add a number and a string, the result will be a string!