Logical & Conditional Operators Javascript


Logical & Conditional Operators Javascript


Javascript supports equality checking (==) and identity checking (===). Equality checks for equality regardless of type. Therefore 25 and '25' will evaluate as true. Identity checking checks not only for equality but type equality as well so 25 and '25' will evaluate as false because, while both are 25, one is a string and the other a number. Note that a single equal sign is an assignment statement! x=5 will assign 5 to x, while x==5 will see if x is equal to 5, and x===5 will check to see if x is identical to 5. 

In addition to == and ===, you can check for not equal (!=) and not identical (!==).
OperatorsDescription
=Assignment x=5; // assigns 5 to x
==Equality, is x==5?
===Identity, is x 5 and a number as well?
!=Not equal, is x unequal to 5?
!==Not identical, is x unequal to the Number 5?
!Not, if not(false) is true.
||OR, is (x==5) OR (y==5)
&&And, is (x==5) AND (y==5)
<Less than. is x less than 5?
<=Less than or equal. is x less than or equal to 5?
>Greater than. is x greater than 5?
>=Greater than or equal. is x greater than or equal to 5?          

CONDITIONAL STATEMENTS
  • IF
The if statement lets you execute a block of code if some test is passed.

var x=5;
if (x==5) {
   alert('x is equal to 5!');
}

You can also use an else clause to execute code if the test fails.

var x=5;
if (x==5) {
   alert('x is equal to 5!');
} else {
   alert('x is not equal to 5!');
}

An elseif statement also exists which allows for better formatting of long conditional tests.

var x=5;
if (x==1) {
   alert('x is equal to 1!');
} else if (x==2) {
   alert('x is equal to 2!');
} else if (x==5) {
   alert('x is equal to 5!');
} else {
   alert('x isn't 1, 2 or 5!');
}

  • SWITCH
If you're going to be doing a large number of tests, it makes sense to use a switch statement instead of nested ifs. Switches in javascript are quite powerful, allowing evaluations on both the switch and the case.

var x=5;
switch (x) {
   case 1: alert('x is equal to 1!'; break;
   case 2: alert('x is equal to 2!'; break;
   case 5: alert('x is equal to 5!'; break;
   default: alert("x isn't 1, 2 or 5!");
}

Note that if you omit the break statement that ALL of the code to the end of the switch statement will be executed. So if x is actually equal to 5 and there is no break statement, an alert for "x is equal to 5" will appear as well as an alert for "x isn't 1,2, or 5!".

Sometimes it makes more sense to do the evaluation in the case statement itself. In this case you'd use true, false, or an expression which evaluates to true or false in the switch statement.
var x=5;
switch (true) {
   case (x==1): alert('x is equal to 1!'; break;
   case (x==2): alert('x is equal to 2!'; break;
   case (x==5): alert('x is equal to 5!'; break;
   default: alert("x isn't 1, 2 or 5!");
}

  • Shorthand Assignment
Javascript supports more advanced constructs. Often you will see code like the following…

function doAddition(firstVar, secondVar) {
   var first = firstVar  ||  5;
   var second= secondVar || 10;
   return first+second;
}
doAddition(12);

Here Javascript uses a logical OR (||) to determine if the passed variables actually have a value. In the example we call doAddition with a value of 12 but we neglect to pass a second argument. When we create the first variable firstVar is a non-falsey value (IE it's actually defined) so Javascript assigns firstVar to first. secondVar was never passed a value so it is undefined which evaluates to false so here the variable second will be assigned a default value of 10.

You should note that zero evaluates as false so if you pass zero as either firstVar or secondVar the default values will be assigned and NOT zero. In our example above it is impossible for first or second to be assigned a zero.

In psuedo code...

var someVariable = (assign if this is truthy) || (assign this if first test evaluates false)

  • Ternary Operators
Ternary operators are a shorthand if/else block who's syntax can be a bit confusing when you're dealing with OPC (Other People's Code). The syntax boils down to this.
var userName = 'Bob';
var hello = (userName=='Bob') ? 'Hello Bob!' : 'Hello Not Bob!';

In this example the statement to be evaluated is (userName=='Bob'). The question marks ends the statement and begins the conditionals. If UserName is, indeed, Bob then the first block 'Hello Bob!' will be returned and assigned to our hello variable. If userName isn't Bob then the second block ('Hello Not Bob!') is returned and assigned to our hello variable. 

In psudeo code…

var someVariable = (condition to test) ? (condition true) : (condition false);

The question mark (?) and colon (:) tend to get lost in complex expressions as you can see in this example taken from wikipedia (but which will also work in Javascript if the various variables are assigned...)

for (i = 0; i < MAX_PATTERNS; i++)
   c_patterns[i].ShowWindow(m_data.fOn[i] ? SW_SHOW : SW_HIDE);

So while quick and efficient, they do tend to reduce the maintainability/readability of the code.
 
LOOP LOGICS

  • FOR
The for loop follows basic C syntax, consisting of an initialization, an evaluation, and an increment.

for (var i=0; (i<5); i++) {
   document.writeln('I is equal to '+i+'<br>');
}
// outputs:
// I is equal to 0
// I is equal to 1
// I is equal to 2
// I is equal to 3
// I is equal to 4

This is actually an extreme simplification of what a for statement can do. On the other end of the spectrum, consider this shuffle prototype which will randomly shuffle the contents of an array. Here, everything is defined, and executed within the context of the for statement itself, needing no additional block to handle the code. 

Array.prototype.shuffle = function (){
   for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--
i], this[i]=this[rnd], this[rnd]=tmp);
};

  • FOR/IN
Javascript has a variant of the for loop when dealing with Javascript objects.
 
Consider the following object…
 
var myObject = { 'animal'  : 'dog',
                 'growls'  : true,
                 'hasFleas': true,
                 'loyal'   : true }                

We can loop through these values with the following construct.
 
var myObject = { 'animal'  : 'dog',
                 'growls'  : true,
                 'hasFleas': true,
                 'loyal'   : true }
                
for (var property in myObject) {
   document.writeln(property + ' contains ' + myObject[property]+'<br>');
}                                 
// Outputs:
// animal contains dog
// growls contains true
// hasFleas contains true
// loyal contains true

What this essentially does is assign the property name to the variable property. We can then access myObject through an associative array style syntax. For instance the first itteration of the loop assigns animal to property and myObject["animal"] will return dog. 

There is a big caveat here in that properties and methods added by prototyping will also show up in these types of loops. Therefore it's best to always check to make sure you are dealing with data and not a function as such… 

for (var property in myObject) {
   if (typeof(myObject[property]) != 'function') {
      document.writeln(property + ' contains ' + myObject[property]+'<br>');
   }
}

The type of check to screen out functions will ensure that your for/in loops will extract only data and not methods that may be added by popular javascript libraries like Prototype.

  • WHILE
WHILE loops in Javascript also follow basic C syntax and are easy to understand and use. The while loop will continue to execute until its test condition evaluates to false or the loop encounters a break statement.

var x = 1;
while (x<5) {
   x = x +1;
}
var x = 1;
while (true) {
   x = x + 1;
   if (x>=5) {
      break;
   }
}

Sometimes it makes more sense to evaluate the test condition at the end of the loop instead of the beginning. So for this Javascript supports a do/while structure. 

var x=1;
do {
   x = x + 1;
} while (x < 5);


Comments

Popular posts from this blog

How to make Stylish and Animated Tabbed forms | with source code (VB.Net & C#)

How to Connect Android to Multiple WiFi Hotspots