Ad

Ad

Sunday, 4 May 2014

JavaScript Operators

= is used to assign values.
+ is used to add values.

The assignment 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;
The result of x will be:
7

Try it Yourself »


JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
OperatorDescriptionExampleResultResultTry it
+Additionx = y + 2y = 5x = 7Try it »
-Subtractionx = y - 2y = 5x = 3Try it »
*Multiplicationx = y * 2y = 5x = 10Try it »
/Divisionx = y / 2y = 5x = 2.5Try it »
%Modulus (division remainder)x = y % 2y = 5x = 1Try it »
++Incrementx = ++yy = 6x = 6Try it »
x = y++y = 6x = 5Try it »
--Decrementx = --yy = 4x = 4Try it »
x = y--y = 4x = 5Try it »


JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
OperatorExampleSame AsResultTry it
=x = yx = yx = 5Try it »
+=x += yx = x + yx = 15Try it »
-=x -= yx = x - yx = 5Try it »
*=x *= yx = x * yx = 50Try it »
/=x /= yx = x / yx = 2Try it »
%=x %= yx = x % yx = 0Try it »


The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

Example

To add two or more string variables together, use the + operator.
txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + txt2;
The result of txt3 will be:
What a verynice day

Try it Yourself »
To add a space between the two strings, insert a space into one of the strings:

Example

txt1 = "What a very ";
txt2 = "nice day";
txt3 = txt1 + txt2;
The result of txt3 will be:
What a very nice day

Try it Yourself »
or insert a space into the expression:

Example

txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + " " + txt2;
The result of txt3 will be:
What a very nice day

Try it Yourself »


Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

Example

x = 5 + 5;
y = "5" + 5;
z= "Hello" + 5;
The result of x, y, and z will be:
10
55
Hello5

Try it Yourself »
The rule is: If you add a number and a string, the result will be a string!

No comments:

Post a Comment