Using Operators in JavaScript

Leave a Comment

The assignment operator, =, is used to assign values to JavaScript variables, as shown in the first two lines of the following code.

The arithmetic operator, +, is used to add values together, as shown in the last line of the following code.
y = 5;
z = 2;
x = y+z;
The value of x, after the execution of the preceding statements is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y = 5, the following table explains the arithmetic operators.

Operator
Description
Example
Result
+
Addition
x = y+2
7
-
Substraction
x=y-2
3
*
Multiplications
X=y*2
10
/
Division
X=y/2
2.5
%
Modulus
X=y%2
1
++
Increment
X=++y
6
--
Decrement
X=--y
4


JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.
Given that x = 10 and y = 5, the following table explains the assignment operators:

Operator
Example
Same As
Result
+
X=y

X=5
+=
X+=y
X=x+y
X=15
-=
x-=y
X=x-y
X=5
/=
X/=y
X=x/y
X=2
%=
X%=y
X=x%y
X=0
*=
X*=y
X=x*y
X=50


The + Operator Used on Strings

The + operator also can be used to concatenate string variables or text values together. To concatenate two or more string variables together, use the + operator:
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the preceding statements, the variable txt3 contains “What a verynice day”.

To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
Or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the preceding statements, the variable txt3 contains:
“What a very nice day”

Adding Strings and Numbers

The rule is as follows:

If you add a number and a string, the result will be a string!
<html>
<body>
<script type="text/javascript">
x=5+5;
document.write(x);
document.write("<br />");
x="5"+"5";
document.write(x);
document.write("<br />");
x=5+"5";
document.write(x);
document.write("<br />");
x="5"+5;
document.write(x);
document.write("<br />");
</script>
<p>The rule is: If you add a number and a string, the result will be a string.</p>
</body>
</html>

0 comments:

Post a Comment