by Dinesh Thakur Category: JavaScript Tutorial

An JavaScript Operators, as the name suggest, performs some action. JavaScript Programming languages would be virtually useless if they did not provide the programmer with JavaScript Operators to use. An JavaScript Operators is a symbol or word that performs some sort of calculation, comparison, or assignment on one or more values. In some cases, an JavaScript Operators provides a shortcut to shorten the code so that you have less to type.

Common calculations include finding the sum of two numbers, combining two strings, or dividing two numbers. Some common comparisons might be to find out if two values are equal or to see if one value is greater than the other. A shortcut assignment operator might be used to assign a new value to a variable so that the variable name does need to be typed twice.

Types of JavaScript Operators

JavaScript Mathematical Operators

The most obvious category of JavaScript Operators is mathematical operators. Mathematical operators, also called Javascript arithmetic operators, perform basic mathematical operations.

          Arithmetic operators

Arithmetic operators take numeric literals, variables, or properties of existing objects as their operands. They always return a single numeric value, based on their operands’ values.

Addition Operator

operand1 + operand2

The addition operator is a simple mathematical Javascript operator. It adds two numbers of any type and evaluates to their sum.
–5 + 3       // evaluates to –2
2.4 + 3.6 // evaluates to 6
1.1 + 7.8 // evaluates to 8.9

Subtraction Operator

operand1 - operand2

Another simple Javascript mathematical operator is the subtraction operator. It subtracts one number from another.
8 – 2  // evaluates to 6
16.3 – 56 // evaluates to –39.7
13.3 – 13.3 // evaluates to 0

Multiplication Operator

operand1 * operand2

The javascript multiplication operator takes two numbers as its operands, and performs the usual arithmetic conversion.
4 * 3 // evaluates to 12
1.2 * 30 // evaluates to 36
20.4 * 6.7 // evaluates to 136.68

 Division Operator

operand1 / operand2

The javascript division operator also performs the usual arithmetic conversion. However, since JavaScript is loosely typed, this javascript operator does not act exactly as in C, Perl, and other strictly typed programming languages. In those languages, integer division is different from floating-point division in that the result of integer division is always an integer number.

JavaScript, on the other hand, does not explicitly distinguish between integers and real-valued numbers, and therefore, the result of a division operation is not guaranteed to be an integer number. In fact, most floating-point numbers are the result of a javascript division operator.

While debugging a script, it may be helpful to remember that the division operation in JavaScript generates the same value as your pocket calculator. You should also remember that the remainder of a division operation is never discarded.

When the operands are floating-point numbers and cannot be represented in binary notation, division expressions often evaluate to inaccurate results. The following demonstrates the behavior of JavaScript’s division operator:

3 / 4 // evaluates to 0.75
3.6 / 0.1 // evaluates to 36
–20 / 4 // evaluates to –5
11.1 / 2.22 // evaluates to 4.999999999999999

Modulus Operator

operand1 % operand2

The modulus operator returns the remainder of a division operation. The division is performed, but only the remainder is kept. The sign of the result is the sign of the quotient. The modulus Javascript operator is also different from the one in other programming languages.

It operates not only on integers but also on floating-point numbers. You should be aware that the javascript modulus operator occasionally returns inaccurate results. The modulus’ inaccuracies stem from the division operation, which sometimes returns inaccurate results:

12 % 5 // evaluates to 2
12.3 % 4 // evaluates to 0.3000000000000007 (inaccuracy)
0 % 99 // evaluates to 0
12.75 % 4.25 // evaluates to 0
11.1 % 2.22 // evaluates to 2.219999999999999

The Nonexistent Integral Division Javascript Operator

JavaScript does not feature an integral division (also called div) operator. In fact, many JavaScript programmers get by just fine without it. However, if you feel the absolute need to create such an operator, you can do so with the following function:

{
return (op1 / op2 – op1 % op2 / op2)
{

The keyword return instructs the function to return a value, so the function call itself evaluates to a value, just like an expression consisting of an operator. Now we can define the newly created div syntax:

div(operand1, operand2)

Here are a few examples:
var a = div(23, 3) // a is assigned 7
var b = div(12, 4) // b is assigned 3

The function evaluates to the quotient of its arguments, with the remainder discarded. The sign of the result is the sign of the quotient.

Increment Operator

operand1++ or ++operand1

The increment Javascript operator is unary operators that can be used in either suffix or prefix notations. It increments the operand’s value by 1. If used after the operand (suffix), the javascript operator returns the value of the operand before incrementing it. If used before the operand (prefix), the javascript operator returns the value of the operand after incrementing it.

Understanding these differences is important when you use such operations as side effects of other statements, such as assignment statements. The following set of statements outlines this concept:

var a = 1

var b = ++a // prefix
document.write("a is ", a, ", b is ", b) // a is 2, b is 2

The first statement assigns the value 1 to a. The second statement performs two different actions: Increments a to 2. Assigns a’s new value to b.

The javascript increment operator in suffix notation performs the actions in reverse order, and therefore the results differ. Suffix notation is demonstrated in the following code:

var a = 1

var b = a++ // suffix
document.write("a is ", a, ", b is ", b) // a is 2, b is 1

b is assigned the value of a, and then a is incremented.

Generally, you should avoid using such side effects. The previous code would be simpler had it looked like:

var a = 1

var b = a a++
document.write("a is ", a, ", b is ", b) // a is 2, b is 1

The javascript increment operator can only be used with a variable or a property of an existing object, but not on a literal. It is natural to come to a conclusion that incrementing is the same as adding 1 to the value:

var a = 1

var b = 1
a++
b = b + 1 // equivalent to b += 1 (see Javascript assignment operators)

This is true as far as correctness of the script is concerned. It is incorrect if performance is important. The advantage of incrementing is that it is much faster than standard assignment (fourth line in above code section). You should always increment when you want to add 1 to a variable (or to a property of an object). It is not so important when the addition operation is done a few times.

You will definitely feel the difference when you have 100,000 addition operations. Another benefit of the javascript increment operator is that it is much easier to understand a statement like countTemp++ than countTemp = countTemp + 1.

It is important to remember that Boolean expressions are equivalent to 1 and 0 in certain situations. The following statements show the effect of incrementing Boolean variables:

var a = true

var b = false
a++
b++
document.write("a is ", a, ", b is ", b) // a is 2, b is 1

Javascript Decrement Operator

operand1-- or --operand1

The javascript decrement operator is similar to the javascript increment operator. It decreases the value of the operand by 1, whereas the increment operator increases it by 1.

Javascript Negation Operator

-operand1

Negation is the programming equivalent to shouting “IS NOT!” and can be quite handy. The negation javascript operator precedes a numeric value (a variable, a property of an existing object, or a numeric literal). By placing this javascript operator before its operand (do not insert any space characters), JavaScript evaluates a positive number as its corresponding negative number and vice versa. As before, you might think that this javascript operator can be replaced by a statement in which the operand is multiplied by –1.

Once again, this is a mistake. Due to the internal structure of the JavaScript interpreter, and the negation javascript operator specifically, negating a numeric value using the negation javascript operator is faster than multiplying it by –1. If you are a traditional Pascal programmer, it might take you a while to get used to the negation and increment operators, but it is worth the effort!

var a = 3
var b = 9
–a + b // evaluates to 6
–b // evaluates to –9

String Concatenation

Concatenation is a very common string operation, and works as shown here:

operand1 + operand2

The javascript string operator’s syntax is identical to that of the javascript addition operator. They differ in the type of operands they operate on. This javascript operator accepts any values as operands, provided that at least one of them is a string. A string is actually an object, so it can be said that the javascript string operator operates on string objects. It joins them together, as in:

"Ladies " + "and " + "gentlemen"

The javascript string operator can operate on more than two operands, but it is still a binary javascript operator because of the way it works. It concatenates the first two strings, then concatenates the third string to the accumulated string, and so on. If one of the operands is not a string, it is automatically cast to a string. The string javascript operator is also called a concatenation operator.

An expression consisting of numerous javascript string operators evaluates to a single string. Based on that, here are two different statements:

document.write("I have " + 2 + " cookies.")

document.write("I have ", 2, " cookies.")

At first, you might think that these statements are equivalent. They aren’t, because the first one uses the javascript string operator, and the second one uses commas to delimit strings and numbers. They differ more than in style. In the first statement, the expression between the parentheses is evaluated to a single string—“I have 2 cookies.”

Therefore, the document.write() method in this statement prints only one expression. The second statement prints multiple expressions. The literals are not evaluated to a single value as in the first statement but rather are printed independently. Both statements print the same HTML to the page, but they do it in different ways. In order to understand how each statement works, take a look at the following sequences of statements. The first sequence is equivalent to the first statement in the previous set, and the second sequence is equivalent to the second statement.

// sequence #1

var stringToPrint = "I have " + 2 + " cookies."
document.write(stringToPrint)
// sequence #2
document.write("I have ")
document.write(2)
document.write(" cookies.")

A common mistake made by beginners is to forget spaces in strings. A space is a character just like any other. Forgetting a space character is not a severe error, because you can easily locate where to add it. You should use one of the following statements to print two consecutive numbers with a separating space character in between:

document.write (16 + " " + 18) // first possibility

document.write (16, " ", 18) // second possibility

The first statement is valid because of the automatic casting method used by JavaScript’s interpreter.

Javascript Bitwise Operators

Bitwise javascript operators are the javascript operators used in bit-oriented operations. A bit is the smallest unit of information, usually represented by 0 or 1. Bit manipulations are used to control the machine at the lowest level.

In JavaScript you won’t be using  javascript bitwise operators to control the machine at a low level but rather for other purposes such as encrypting and encoding. Eight consecutive bits form a byte. There are 256 (28) byte variations. That is, a byte can be one of 256 eight-bit sequences. For example, 11010001 is one of these 256 possibilities. A byte is represented by a character in programming languages that support character data types, such as C,C++, and Pascal.

Hexadecimal notation is convenient for representing binary data because each hexadecimal digit represents four binary bits. Bitwise operators enable the scripter to work on individual bits. The bitwise (bit) javascript operators are listed in Table

 Bitwise operators in JavaScript

Assignment Operators

Assignment javascript operators are binary operators handling arithmetic, string, or bitwise javascript operators. They perform the regular operation on the operands and assign the result to the first operand. The assignment operators are as follows:

Javascript Relational Operators

Relational Javascript operators, also called comparison operators, compare two values and return a Boolean result. All relational javascript operators are binary, because they compare two values. These javascript operators are often used in conditional statements. Here is the complete list of JavaScript’s relational operators:

Short-Circuit Logical JavaScript Operators

Short-circuit logical operators, also called Boolean operators or logical operators are binary operators that accept Boolean values as their operands. They group multiple relational expressions together. There are three logical operators: Short-Circuit Logical Operators in JavaScript

More Logical Javascript Operators

The Javascript conditional operator and the comma operator are also logical operators.

Javascript Conditional Operator

condition ? true Alternative : false Alternative

The conditional JavaScript operator is unique because it is trinary (takes three operands) and because it returns values of all types. It can return a numeric value, a string, a Boolean value, and so on. The first operand is the condition. The condition must be an expression that evaluates to a Boolean value, either true or false.

The second  Javascript operator holds the value that the javascript operator should return if the condition is true. The third operand is the value that the expression evaluates to if the condition is false. The javascript conditional operator is often used with an javascript assignment operator. For example: var level = (points > 500) ? "Second Level" : "First Level"

The variable level is assigned either "First Level" or "Second Level", depending on the value of the Boolean expression points > 500. If the value of points is greater than 500, the conditional expression evaluates to the string "Second Level", which in turn is assigned to the variable level. If the value of points does not exceed 500, the string "First Level" is assigned to the variable. The first operand (the condition) must be Boolean (a single Boolean value or an expression that evaluates to a single Boolean value). The other operands can be of any type.

Comma JavaScript Operator

operand1, operand2, operand3,...

The JavaScript comma operator is rarely used. You can use it to force the evaluation of a set of expressions. The comma JavaScript operator is also called a parameter delimiter because it does just that. You probably recall that we used the comma javaScript operator in functions when we wanted a function to accept multiple arguments. In this example, the comma operator delimits the method’s arguments:

var beerNum = 99

document.write(beerNum, " bottles of beer on the wall")
Here is another example:
var a = (b = "Hello", alert("Hi"), "Howdy")

The comma JavaScript operator forces the evaluation of all expressions in the statement. Only the last expression is returned, so the value of a would be "Howdy". This statement is equivalent to the following set of statements:

b = "Hello"

alert("Hi")
var a = "Howdy"

Data Type JavaScript Operator

typeof operand1
ortypeof (operand1)

JavaScript provides an operator to check the data type of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type. The expression includes the word typeof followed by the literal or identifier. Here are some examples:

typeof foo == "undefined" // when foo is undefined

typeof eval == "function" // eval is a built-in function
typeof null == "object" // null is an object
typeof 3.14 == "number"
typeof true == "Boolean"
typeof "a string" == "string"
// all of the expressions are true, of course

The typeof operator is very useful for debugging. Until strong debugging tools are available, you must do all debugging by hand, and detecting the data type of a structure is sometimes essential.

Void JavaScript Operator

void operand1

void (operand1) or
javascript:void operand1
javascript:void (operand1)

The void operator, like typeof, is quite extraordinary. It specifies an expression to be evaluated without returning a value. Take a look at the following script:

function foo(){

   alert("Function entered")
   return true}
   alert(foo())

The preceding script segment displays two alert boxes with the following strings:

1. Function entered

2. true

Now take a look at another function and call:

function foo()

{

alert("Function entered")
return true }
alert(void foo())

This script also generates two alerts, but the second one reads “undefined” because the void operator evaluates the function without returning a value. A more important use of this operator comes with hypertext links, where it is used to evaluate a JavaScript expression. The expression is evaluated but is not loaded in place of the current document.

The following link does nothing because the expression 0 has no effect in JavaScript:

<A href="javascript:void(0)">Click here to do nothing</A>

The following code generates an alert box when the link is clicked:

<A href="javascript:void(alert('Wow'))">Click here to display message</A>

The parentheses are optional, so it’s up to you to decide whether to use them. Some scripter specify them in HTML and omit them in JavaScript for no particular reason.

JavaScript Operator Precedence

You probably remember that 2 + 6 * 9 is 56 and not 72, because multiplication precedes addition. That is exactly the meaning of operator precedence. It is not necessary to remember the precedence rules because parentheses can be used to force evaluation in the desired order. The expressions are evaluated according to the precedence rules. Operators at the same level are evaluated from left to right. The following table will help you when you want to define complex expressions. Operator precedence in JavaScript





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.