4. JavaScript: Conditions

Conditions are very important in all programming languages including javaScript. Condition operator compare two values and helps us in taking some decision.

These are few examples, if a student got 80% marks, then he should get A grade. If amount in bank account is less than 900 but greater than 800 then member is Gold member and so on.

javaScript provides following operators and you will see how you can use them one by one.

1.  AND  operator which is represented by “&&”
2.  OR operator which is represented by “||”
3.  Equality operator “==”
4.  Greater than operator “>”
5.  Less than operator “<”
6.  Greater than equal “>=”
7.  Less than equal “<=”

if and else if statements

To create the condition in javaScript you can use “if” statement with two brackets “( )”.

var studentMarks = 89
// marks are greater than equal to 80
if(studentMarks >= 80)

you can create multiple “if” statements with combination of “else” and curly brackets {}. All lines of code come within these brackets  are called code block.

var studentMarks = 89
if(studentMarks >= 80){
}else if (studentMarks > 70){

AND (&&) operator

If you are using AND (&&) operator which means that you want to validate two conditions. If first and the second conditions are true then code block will be executed. If one condition will be false, the code block will be skipped. Experiment with following code by changing variable amount.

var amount = 1000
if(amount <=1500 && amount > 900 ){
    alert("Gold Member")
}else if (amount <= 900 && amount >= 800){
    alert("Silver Member")
     alert("Not a member")

OR (||) operator

If you are using OR (||) operator then you want to validate at least one condition. If only one condition will be true, the code block will be executed.  Experiment with following code by changing value of variables “amount” and “savings”. You can also add more if statement with OR operator

var amount = 1000
var savings = 800
if(amount > 1200 || savings > 700){
    alert("Gold Member")
   alert("Not a member")

Equality operator

For equality there are two different operators, one is “==” and second is “===”

== operator compares only value

if(5 == '5')
  alert ("Values are equal")
  alert ("values are not equal")

=== operator is special type of operator, it checks 2 things, value and the type of the variable. 5 === ‘5’ is not valid because 5 is integer type and ‘5’ is string type

if(5 === '5')
  alert ("Value and type both are same")
  alert ("value and type are not same")

Not Equal Operator !=

Not equal operator is simply opposite of equal operator. If you want to see if your value is not equal to other value then you can use != operator.

var myvalue = 10;
if(myvalue != 5){
alert("My Value is not Equal to 5");
} else {
alert("My Value is Equal to 5");


Download file from GitHub