Search

JavaScript - Operators example

An operator is used for getting some process between operands.

JavaScript supports lots type of Operators We not going deeply on all operators but lets go through all type.

Arithmetic Operators
OperatorDescriptionExampleResult
+Addition
x=2
y=2
x+y
4
-Substraction
x=5
y=2
x-y
3
*Multiplication
x=5
y=4
x*y
20
/Division
x=15
y=5
x/y
3
%Modulus (division remainder)
x = 5
y = 2
x/y
1
++Increment
x=5
x++
6
--Decrement
x = 5
x--
4

Example:

<script language="JavaScript">

var a = 5;

++a;

alert("The value of a = " + a );

</script>
Assignment Operators
OperatorDescriptionExample
=Equal Assign
x = y
x = 10
+=Addition & Equal
x += y
x = x + y
-=Substraction & Equal
x -= y
x = x - y
*=Multiplication & Equal
x * = y
x = x * y
/=Division & Equal
x /= y
x = x / y
%=Modulation & Equal
x % y
x = x % y
   

Example:

<script language="JavaScript">

var a = 10;

var b = 2;

a+=b;

alert("The value of a +=b is = " + a );

</script>


Comparison  Operators
OperatorsDescriptionExampleResult
==Is equal to5 == 8false
===Is equal to (check for both value & type)
x = 5
y=*5*
x==y
x===y


true
false
!=Is not equal5!=8false
>Is greater than5>8false
<Is less than5<8true
>=Is greater than or equal to5>=8false
<=Is less than or equal to5<=8false

Example:

<script language="JavaScript">
var a = 5;
var b = 6;
a= a>b;
alert("The value of a = " + a );
</script>

Logical  Operators
OperatorDescriptionExampleResult
&&And
x=6
y=3
(x<10 && y>1)


true
||Or
x=6
y=3
(x == 5 || y == 5)
false
!Not
x=6
y=3
!(x == y)


false

Example:
<script language="JavaScript">

var userID;
var password;
userID = prompt("Enter User ID " , " ");

password = prompt ("Enter Password"," ");

if (userID == "Visions" && password == "Developer")
{
Alert ("Valid Login");
}
else
{
Alert(“Invalid Login”);
}
</script>

String  Operator
A string is most often text, for example “Hello Good Morning”. To Stick or join two or more string variables together use the + operator (String Operator).
Example :
                    Txt1 = "Visions"
                    Txt2 = "Developer"
                    Txt3 = Txt1 + " " + Txt2
Now the Txt3 Variable Contain Visions Developer
Conditional Operator
JavaScript is scripting language but still it contains a conditional operator that assign a value to a variable based on some condition.
                Syntax :  varname = (condition)?value1:value2
               
Example: Msg = (userId = "CEO")?"Welcome ABC":"Welcome"
If the variable userId is equal to "CEO", then put the string "Welcome ABC" in the variable named Msg. If the variable userID is not equal to "CEO", the put the string "Welcome" into the variable named greeting.

No comments:

Post a Comment