javascript And Or Operators

And operator is "&&", or operator is "||". They are used in condition statements.


Show numbers that not 3 and % 3 = 0 in following array:
var arr = new Array(1,3,5,2,4,7,8,12,32);
for (var i=0; i<arr.length; i++)
{
if (arr[i] % 3 == 0 && arr[i] != 3)
{
//when both condition satisfied
alert(arr[i]);
}
}


Show numbers that equal 3 or % 5 = 0 in following array:
var arr = new Array(1,3,5,2,4,7,8,12,32);
for (var i=0; i<arr.length; i++)
{
if (arr[i] % 5 == 0 || arr[i] == 3)
{
//when one condition satisfied
alert(arr[i]);
}
}


"||" operator can be used in variable assignment.
var b=false;
var a=8;
var c = b || a; //c=8
c = null || a; //c=8
b = true;
c = b || a; //c=true
b = 2;
c = b || a; //c=2
if (c)
{
...
}
else
{
alert("Error! b is not null!");
}

The variable c will be assigned value 8 only when b is false (false can be represented as 0, false, undefined, null, NaN or ""). These tests can ensure that variable b is nullified.


endmemo.com © 2017  Terms of Use | Home