JavaScript Operators

JavaScript addition operator

The JavaScript addition operator ( + ) serves two main purposes in JavaScript.

The first is to perform a simple addition on numbers.

The second operation is to perform string concatenation (combine strings).

1. Addition

<script>

    var a = 3;

    var b = 2;

    var c = a + b;

    document.write(c);

</script>


addition-operator-in-javascript.png

2. String Concatenation

<script>

    var user = "Henry";

    var country = "USA";

    var output = user + " is from " + country;

    document.write(output);

</script>


string-operator-in-javascript.png

JavaScript subtraction operator

The JavaScript subtraction operator ( - ) also serves two purposes in your code.

The first is to perform simple subtraction on numbers (6 - 2).

The second operation is to specify negative numeric values (-20).

1. Subtraction

<script>

    var a = 10;

    var b = 3;

    var c = a - b;

    document.write(c);

</script>


subtraction-operator-in-javascript.png

2. Assigning negative values 

<script>

    var a = 10;

    var b = -10;

    var c = a + b;

    document.write(c);

</script>


negative-operator-in-javascript.png

JavaScript multiplication operator

The JavaScript multiplication operator ( * ) is used to multiply numbers. 

<script>

    var a = 4;

    var b = 3;

    var c = a * b;

    document.write(c);

</script>


multiply-operator-in-javascript.png

JavaScript division operator

The JavaScript division operator ( / ) is used to divide numbers. 

<script>

    var a = 8;

    var b = 4;

    var c = a / b;

    document.write(c);

</script>


division-operator-in-javascript.png

JavaScript increment operator

The JavaScript increment operator ( ++ ) is used to increase a number by 1. 

Example 1

<script>

    var i = 0;

    i++;

    document.write(i);

</script>


increment-operator-1-in-javascript.png

Example 2 

<script>

    for (var i = 0; i < 5; i++)

    {

      document.write(i + "<br />");

    }

</script>


increment-operator-2-in-javascript.png

JavaScript decrement operator

The JavaScript decrement operator ( -- ) is used to decrease a number by 1.

Example 1 

<script>

    var i = 1;

    i--;

    document.write(i);

</script>


decrement-operator-1-in-javascript.png

Example 2 

<script>

    for (var i = 10; i > 0; i--)

    {

      document.write(i + "<br />");

    }

</script>


decrement-operator-2-in-javascript.png

JavaScript modulus operator

The JavaScript modulus operator ( % ) is used to calculate the remainder of two values if they were divided.

Modulus produces the remainder value only. It is very useful for seeing if values are divisible by a specified number, check Example 2 below to see it in action that way.

Example 1 

<script>

    var a = 10;

    var b = 3;

    var c = a % b;

    document.write(c);

</script>


modulus-operator-1-in-javascript.png

We get the value of "1" as the modulus when 10 is evaluated against 3 because the remainder of dividing those numbers would be "1".

Evaluating 10 against 3 gives us an answer of "3 with remainder of 1".

If you have "10" divided by "5" you get a modulus of "0" since there would be no remainder, 5 goes into 10 twice with no remainder left over so we would get modulus of "0".

Example 2 

<script>

    for (var i = 1; i <= 20; i++)

    {

        if (i % 2 == 0)

        { // if value is divisible by the number 2 make it red

         document.write("<span style='color:red;'>" + i + "</span><br />");

        }

        else

        {

         document.write(i + "<br />");

        }

    }

</script>


modulus-operator-2-in-javascript.png

JavaScript equal operator

The JavaScript equal comparison operator ( == ) is used to compare whether the operand on the left is equal to the operand on the right.

The expression created will then return a value of either "true" or "false" to you.

left_operand == right_operand 

<script>

    var a = 4;

    var b = 3;

    document.write(a == b);

</script>


equal-operator-1-in-javascript.png

You will see it in use most commonly within if...else condition statements.

<script>

    var a = 4;

    var b = 3;

    if (a == b)

    {

       document.write("YES THAT IS TRUE");

    }

    else

    {

       document.write("NO THAT IS FALSE");

    }

</script>


equal-operator-2-in-javascript.png

JavaScript strict equal operator

The JavaScript strict equal comparison operator ( === ) is similar to the normal equal operator, except that it evaluates the object types also.

If the values are the same but the object types are not the same, this will return false whereas the normal equal operator will return true.

left_operand === right_operand 

<script>

    var v1 = "5";

    var v2 = 5;

    if (v1 === v2)

    {

      document.write("TRUE");

    }

    else

    {

      document.write("FALSE");

    }

</script>


strict-equal-operator-1-in-javascript.png

Now run the same exact code using the normal equal operator.

You will notice that it does not take object type into consideration at all, and will return a value of true even though the left operand is a string object and the right operand is a number object.

<script>

    var v1 = "5";

    var v2 = 5;

    if (v1 == v2)

    {

      document.write("TRUE");

    }

    else

    {

      document.write("FALSE");

    }

</script>


strict-equal-operator-2-in-javascript.png

JavaScript not equal operator

The JavaScript not equal comparison operator ( != ) is used to check if the operand on the left is not equal to the operand on the right.

The expression created will then return a value of either "true" or "false".

left_operand != right_operand 

<script>

    var v1 = 30;

    var v2 = 50;

    document.write(v1 != v2);

</script>


not-equal-operator-in-javascript.png

JavaScript strict not equal operator

The JavaScript strict not equal comparison operator ( !== ) is used to check if the operand on the left is not equal to the operand on the right, as well as evaluating their object types in the comparison.

The expression created will then return a value of either "true" or "false" to you.

left_operand !== right_operand 

<script>

    var v1 = "50";

    var v2 = 50;

    document.write(v1 !== v2);

</script>


strict-not-equal-operator-1-in-javascript.png

"50" does not strictly equal 50 because the first is a string object and the second is a number object.

Even though the values match, the object types do not.

Now run the same exact code using the normal "not equal" operator to see how it does not take object type into consideration in the comparison.

<script>

    var v1 = "50";

    var v2 = 50;

    document.write(v1 != v2);

</script>


strict-not-equal-operator-2-in-javascript.png

JavaScript less than operator

The JavaScript less than comparison operator ( < ) is used to see if the operand on the left is less than the operand on the right.

The expression created will then return a value of either "true" or "false" to you.

left_operand < right_operand 

<script>

    var v1 = 4;

    var v2 = 7;

    document.write(v1 < v2);

</script>


or

<script>

    var v1 = "abc";

    var v2 = "def";

    document.write(v1 < v2);

</script>


That will work on strings as well.

less-than-operator-in-javascript.png

JavaScript greater than operator

The JavaScript greater than comparison operator ( > ) is used to see if the operand on the left is greater than the operand on the right.

The expression created will then return a value of either "true" or "false" to you.

left_operand > right_operand 

<script>

    var v1 = 4;

    var v2 = 7;

    document.write(v1 > v2);

</script>


or

<script>

    var v1 = "abc";

    var v2 = "def";

    document.write(v1 > v2);

</script>


Will work on strings as well.

greater-than-operator-in-javascript.png

JavaScript less than or equal operator

The JavaScript less than or equal to comparison operator ( <= ) is used to evaluate if the operand on the left is less than or equal to the operand on the right.

The expression created will then return a value of either "true" or "false" to you.

left_operand <= right_operand 

<script>

    var v1 = 5;

    var v2 = 5;

    document.write(v1 <= v2);

</script>


or

<script>

    var v3 = "c";

    var v4 = "d";

    document.write(v3 <= v4);

</script>


Will work on strings as well.

less-than-or-equal-operator-in-javascript.png

JavaScript greater than or equal operator

The JavaScript greater than or equal to comparison operator ( >= ) is used to evaluate if the operand on the left is greater than or equal to the operand on the right.

The expression created will then return a value of either "true" or "false" to you.

left_operand >= right_operand

<script>

    var v1 = 100;

    var v2 = 50;

    document.write(v1 >= v2);

</script>


or

<script>

    var v3 = "ghi";

    var v4 = "def";

    document.write(v3 >= v4);

</script>


Will work on strings as well.

greater-than-or-equal-operator-in-javascript.png

JavaScript ternary operator

The JavaScript ternary operator ( ? ) is sort of like a conditional statement.

A ternary operation is one that requires three parameters. It will return the value on the left of the colon ( : ) if the expression is true, and return the value on the right of the colon if the expression is false.

(expression) ? "output for true" : "output for false"

<script>

    var a = 5;

    var b = 3;

    var result = (a > b) ? "that is true" : "that is false";

    document.write(result);

</script>


ternary-operator-1-in-javascript.png

Here is a more advanced example that will show you how to fire off functions in place of returning simple strings.

<script>

    var a = 5;

    var b = 3;

    function funcForTrue()

    {

      document.write("Executed function for a TRUE result");

    }

    function funcForFalse()

    {

      document.write("Executed function for a FALSE result");

    }

    var result = (a > b) ? funcForTrue() : funcForFalse();

</script>


ternary-operator-2-in-javascript.png

JavaScript append operator

The JavaScript append string operator ( += ) serves two separate purposes in our scripts.

First we use it to append to or compound variable data.

Secondly we use it is as mathematical shorthand to make the left operand equal to the value of both the right and left operands of the expression.

left_operand += right_operand


Append to a string or variable 

<script>

    var myVar = "<h2>Welcome to my how-to page</h2>";

    myVar += "<h3>I Will Explain How To Do This Thing</h3>";

    myVar += "<p>First, grab yourself a new clean ...<p>";

    myVar += "<p>Second, be sure to insert it firmly into ...<p>";

    document.write(myVar);

</script>


append-operator-1-in-javascript.png

Simple shorthand arithmetic example 

<script>

    var a = 2;

    var b = 3;

    document.write(a += b);

</script>


append-operator-2-in-javascript.png

JavaScript assignment operator

The JavaScript assignment operator ( = ) is used to assign the value of the right operand as the new value of the left operand.

It is probably the most commonly used operator of them all. Each time you assign values in this way, the existing value that the left operand contained is overwritten with a new value.

To append to a variable use the string append operator instead:

left_operand = right_operand 

<script>

    var myVar = "Welcome to the circus!";

    document.write(myVar);

    document.write("<hr />");

    myVar = "Welcome to the zoo!";

    document.write(myVar);

</script>


assignment-operator-in-javascript.png

JavaScript logical or operator

The JavaScript logical or ( || ) operator is used to group values or sub-expressions into one evaluation expression.

It makes perfect sense if you replace the characters "||" with the word "or" when you read script that has this in place.

It could help save you a few lines of code here and there by allowing you to group expressions or values.

(value || value) 

<script>

    if ((8 || 35 || 14) < 10)

    { // if 8 or 35 or 14 is less than 10

      document.write("At least one value is less than 10");

   }

   else

    {

      document.write("No values are less than 10");

    }

</script>


logical-or-operator-1-in-javascript.png

Here is an example evaluating some string variable data lengths as a group:

<script>

    var u1 = "John";

    var u2 = "Sara";

    var u3 = "Kate";

    if ((u1.length || u2.length || u3.length) == 4)

    {

      document.write("All names have exactly 4 letters in them.");

    }

  else

    {

      document.write("At least one name does not have 4 letters.");

    }

</script>


logical-or-operator-2-in-javascript.png

Here is an example that shows sub-expressions that are grouped together as one expression.

Each sub-expression can be wrapped in parenthesis like I did below but that is not a requirement unless your expression logic demands parenthesis grouping. 

<script>

    var sky = "blue";

    var blood = "green";

    var sun = "yellow";

    if ((sky != "blue") || (blood != "red") || (sun != "yellow"))

    {

      document.write("Uh Oh! At least one thing is wrong in the world!");

    }

  else

    {

      document.write("Everything is normal in the world.");

    }

</script>


logical-or-operator-3-in-javascript.png

JavaScript logical and operator

The JavaScript logical and ( && ) operator is used to group values or sub-expressions where the left and right operands must both evaluate to the same result.

It makes good sense if you replace the characters ( && ) with the word "and" when you see that symbol sequence in scripts to get a mental grasp of it.

(value && value && value && etc...) 

<script>

    if ((3 && 5 && 12) < 10)

    {

      document.write("All values are less than 10");

    }

  else

    {

      document.write("Not all of the values are less than 10");

    }

</script>


logical-and-operator-1-in-javascript.png

Here is an example evaluating string data.

This script is ready to perform a check to make sure all values are present before the program can continue. 

<script>

    var uname = "Josh";

    var email = "[email protected]";

    var country = "";

    if ((uname.length && email.length && country.length))

    {

      document.write("We can now proceed because all values are present");

    }

  else

    {

      document.write("We seem to be missing a value we need, try again");

    }

</script>


logical-and-operator-2-in-javascript.png

JavaScript logical not operator

The JavaScript logical not ( ! ) operator is used to evaluate a single operand or expression.

It will return true if the operand is empty, and returns false if the operand has some value in it.

( !value ) 

<script>

    var uname = "";

    if (!uname)

    {

      document.write("Username has no value.");

    }

  else

    {

      document.write("Username is: " + uname);

    }

</script>


logical-not-operator-in-javascript.png

JavaScript comma operator

The JavaScript comma ( ! ) operator can be used to apply multiple parameters or arguments to a loop statement.

It can be used to establish and iterate multiple variables in a loop, as well as establishing multiple arguments in functions and arrays.

( param, param ) 

<script>

    var myArray = ["Joe", "Paul", "Katherine", "Susan"];

    for (var i = 0, x = 3; i < 2; i++, x--)

    {

      document.write(myArray[i] + " loves " + myArray[x] + "<br />");

    }

</script>


comma-operator-in-javascript.png

JavaScript this operator

The JavaScript this special operator is used to dynamically access all of an object's properties.

If passed through an HTML element, the element passing it becomes the dynamic object of focus in any functions or methods that the element is invoking in JavaScript. 

<a onclick="alert(this.innerHTML)" href="#" onmousedown="return false">

    If you click me I will kick you in the teeth

</a>


this-operator-1-in-javascript.png

This example really shows how to gain access to all properties of an element dynamically.

<script type="text/javascript">

    function learnAbout(x)

{

    var result = "Element ID --- "+x.id+"<br />";

    result += "Element Content --- "+x.innerHTML+"<br />";

    result += "Element Title --- "+x.title+"<br />";

    result += "Element --- "+x;

    document.getElementById("status").innerHTML = result;

}

</script>

<button onclick="learnAbout(this)" id="myBtn" title="cricker">

  please click me

</button>

<a onclick="learnAbout(this)" href="#" id="myLink" title="linker" onmousedown="return false">

  click me too please

</a>

<p id="status"></p>


this-operator-2-in-javascript.png


this-operator-3-in-javascript.png

this-operator-4-in-javascript.png

JavaScript new operator

The JavaScript new special operator is used when we define new instances of custom objects that we create, or when we explicitly define built in objects like String, Array, Number, Date, Etc.

When you create instances of your custom object you must use the new operator in order for the object to be created properly.

In this code example below we have created a custom object constructor named character for defining and managing game characters.

You can create your custom objects to have any properties you wish, and also apply custom methods to them.

<script>

    function character(name, type, age, strength, charisma, wisdom)

{

    this.name = name;

    this.type = type;

    this.age = age;

    this.strength = strength;

    this.charisma = charisma;

    this.wisdom = wisdom;

}

var player1 = new character("Brutus", "Fighter", 32, 10, 5, 6);

var player2 = new character("Sticky Fingers", "Thief", 25, 7, 8, 8);

var player3 = new character("Abracadabrus", "Wizard", 67, 4, 6, 10);

var playerArray = [player1, player2, player3];

document.write("<h1>Adventuring Party</h1>");

for (var player in playerArray)

{

    document.write("<h3>"+playerArray[player].name+"</h3>");

    document.write("Type : "+playerArray[player].type+"</br>");

    document.write("Age : "+playerArray[player].age+"</br>");

    document.write("Strength : "+playerArray[player].strength+"</br>");

    document.write("Charisma : "+playerArray[player].charisma+"</br>");

    document.write("Wisdom : "+playerArray[player].wisdom+"</br>");

}

</script>


new-operator-in-javacsript.png

JavaScript in operator

The JavaScript in special operator is used to see if a property is available in an object, or to check if an array has a specific index number available in it.

It will return a value of true if the property exists in the object scope, and returns false if the property cannot be found in the object. 

<script>

    var adam = new Object();

    adam.quote = "I love to party";

    adam.age = 72;

    adam.nature = "Chaotic Neutral";

    if ("nature" in adam)

    {

      document.write("That property is there: " + adam.nature);

    }

    else

    {

      document.write("That property is NOT in the object scope.");

    }

</script>


in-operator-1-in-javascript.png

Here is an example using the in operator to see if an array index exists.

<script>

    var girls = new Array("Lisa", "Michelle", "Tracy");

    document.write((0 in girls) + "<br />");

    document.write((1 in girls) + "<br />");

    document.write((2 in girls) + "<br />");

    document.write((3 in girls) + "<br />");

    document.write((4 in girls) + "<br />");

</script>


in-operator-2-in-javascript.png

JavaScript delete operator

The JavaScript delete special operator is used to delete user defined properties of custom created objects.

It can also delete values from specified indexes of an array, but it will not remove the array element itself.

To remove array elements completely use the array shift() method.

Delete properties from user created custom objects 

<script>

    var adam = new Object();

    adam.quote = "I love dorky stuff";

    adam.nature = "Evil";

    document.write(adam.nature + "<hr />");

    delete adam.nature

    document.write(adam.nature);

</script>


delete-properties-in-javascript.png

Delete array values at specified indexes 

<script>

    var girls = new Array("Lisa", "Michelle", "Tracy");

    document.write(girls + " | Array Length: " + girls.length);

    document.write("<hr />");

    delete girls[0];

    delete girls[1];

    document.write(girls + " | Array Length: " + girls.length);

</script>

delete-array-in-javascript.png

JavaScript typeof operator

The JavaScript typeof special operator is used to return the data type of an object.

You can also access the constructor property of objects to see the constructor function they use.

<script>

    var v1 = "Welcome Partner";

    var v2 = 50;

    var v3 = new Object();

    var v4 = Function();

    var output = "<h3>Determine object types</h3>";

    output += "v1 &bull; " + typeof (v1) + " &bull; " + v1.constructor + "<br />";

    output += "v2 &bull; " + typeof (v2) + " &bull; " + v2.constructor + "<br />";

    output += "v3 &bull; " + typeof (v3) + " &bull; " + v3.constructor + "<br />";

    output += "v4 &bull; " + typeof (v4) + " &bull; " + v4.constructor + "<br />";

    document.write(output);

</script>


typeof-operator-in-javascript.png

JavaScript instanceof operator

The JavaScript instanceof special operator evaluates whether or not the left operand explicitly matches the data type you specify as the right operand in the expression. 

<script>

    var myVar = new String("abcdefghi");

    if (myVar instanceof String)

    {

      document.write("Yes it is string type : " + myVar.constructor);

    }

  else

    {

      document.write("No that is not string type : " + myVar.constructor);

    }

</script>


instanceof-operator-in-javascript.png

JavaScript void operator

The JavaScript void special operator will run an expression but give no return value.

You can see the contrast by running an expression without void first, then run the same expression using void.

It processes the expression but where there is normally a return value, it is void. 

<script>

    var a = 2;

    var b = 3;

    document.write(c = a + b);

    document.write("<br />" + c);

    document.write("<hr />");

    var c = 2;

    var d = 3;

    document.write(void (e = c + d));

    document.write("<br />" + e);

</script>


void-operator-in-javascript.png

Summary

This article provides much more practical knowledge than theoretical knowledge.

Up Next
    Ebook Download
    View all
    Learn
    View all