Javascript Tutorial part 4 - Operators

In the last article of this Javascript tutorial series, we discussed about various Javascript Data-types, in this tutorial we will go through various Javascript operators that help us modify those data-types and values. We would discuss the most common types of Javascript operators for the brevity of the discussion. For detailed list of Operators supported by Javascript please check Mozilla Developer Guide.

Arithmetic Operators

Following are the common arithmetic Javascript operators which can work on Numerical operands and return Numerical value too:

(+, -, *, /, %, ++, --, unary -, unary +)

Javascript Operators for assignmen

Javascript operators which assign the right operand / expression value to the left operand are known as Assignment operators.

(=, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |=)

Bitwise Operators

Bitwise operators work on binary representations(0 and 1) of the operands. The returned value will be a Numerial value.

(&, |, ^, ~, <<, >>, >>>)

Logical Operators

Logical operators work on logical(boolean) operands and the value returned is always a true or false.
(&&, ||, !)

Logical AND and OR operators also exhibits short-circuit functionality. AND operator returns after evaluating the value of first false operand, while OR returns after evaluating value of first true operand, otherwise they both keep on evaluating till the last operand.

var i = 1;
var j = 2;
var k = 0;

console.log(i || k++); // evaluates till i only. returns true.
console.log(k); // k is still 0.
console.log(k || i++); // evaluates i++ too, as k is false.
console.log(i); // i is 2 now.
console.log(k++ && j++); // evaluates only till k as it is false.
console.log(j); // j is still 2.
console.log(k); // k is 1 now due to post-increment (++)

// Using short-circuit evaluation to avoid if-conditions
is_enabled && dothis(is_enabled); // call dothis() only if is_enabled is true.


Javascript Operators for String concatenation

Following operators in Javascript are used to concatenate strings.

(+ and +=)


At times, using '+' operator behaves weirdly when used with mixed operands e.g. String and Numbers.

var i = 1;   // A Number
var j = "2" // String
console.log(i + j); //would print 12, '+' is working as concatenation operator

// Typecasting j so that it behaves as number
console.log(i + Number(j)); // prints 3.

If you remember from our previous discussion on Javascript Objects, Number() behaves as constructor and returns a proper numerical value which when used with '+' operator, would result in Addition rather than concatenation.

// Using Unary plus operator to coerce a string as Number
console.log(i + +j); // prints 3.

Comparison Operators

To check the equality of values of left and right operand, you can use any of the following comparison operators:

(==, !=, ===, !==, >, >=, <, <=)


'===' and '!==' known as strict comparison operators. Let us have a look at some examples and see how '==' differs from '==='.

'0' == ''    // false
0 == '0' // true (surprise !!!)

'0' === '' // false
0 === '0' // false (perfect !!!)

'==' operator tries to compare Javascript primitive values, whereas '===' returns false if the types of the operands is different. This is the reason why 0 == '0' evaluates to true - left operand is a number and thus right operand gets type-casted to number also and the result evaluates to true. Strict equality operator simply returns false as the Data-types are different. For further understanding Mozilla Developer guide is a good resource.

conditional operators:

To execute certain portion of code under some conditions, you can use if-else blocks which is very similar to other programming languages. You can also use ternary operator to assign value to a variable based on some conditions. Another set of such Javascript operator is - switch - case clauses.

var var1 = true;
var var2 = false;

// You can use any boolean expression within if condition.
if (var1) {
// do something.
}

if (var2) {
// wont execute
}

// Assign 1 to assignme if var1 is true, else assign 0
var assignme = (var1) ? 1 : 0;

Loops

loops help in executing a statement multiple number of times. Javascript supports following loops:

For loop

Similar to other programming languages the syntax for Javascript for loop consists of four sections:

for ([initialization]; [conditions]; [iterations]) {
      [Body]
}

Initialization expression is executed only once before you enter the loop, conditions are always checked before commencing with the execution of loop body. Iterations are executed once all the statements within loop body are executed. Here is an example:

// this loop prints all the elements of an array.
for (var i = 0; i < arr1.length; i++) {
console.log("Element no. " + (i + 1) + ": " + arr1[i]);
}

// Element no. 1: 2
// Element no. 2: 5

While loop

If you remove initialization and iterations out of for loop syntax and do them manually, whatever is left is nothing but a while loop:

while ([conditions]) {
       [body]
}

The initialization and iterations are still needed. Generally, initializations are done before the while loop, while iterations are done as the last statements to be executed as a part of loop body.

var i = 0;
while (i < arr1.length) {
console.log("Element no. " + (i + 1) + ": " + arr1[i]);
i++;
}

do-while loop

This is very similar to the while loop, just that do-while loop is forced to execute the loop at least once.

do {
     [Body]
} while ([conditions]);

So, even if conditions are deliberately marked as false, still the loop will print the following line.

do {
// would print this only once.
console.log('I am there to be printed');
} while(false);

continue and break loops:

Another set of Javascript operators you must be aware of are - break and continue. Suppose, you want to search for a particular element within an array, it doesn't make sense to continue looping once you have found it. On the other hand, if you want to skip some specific value while looping - use continue to skip this iteration and move on with next element.


//Find the value - findme in arr1, ignore negative values.
var i = 0;
for (; i < arr1.length; i++) {
if (arr1[i] < 0) {
continue;
}

if (arr1[i] === findme) {
console.log("Found the value " + findme + "at index:" + i);
break;
}
}

And this brings us to put an end to this tutorial on Javascript Operators. As stated earlier, this is just the basic info to get you started. In the next article we will discuss Javascript Functions in more detail.

comments powered by Disqus