Moving on in our journey of the JavaScript language, we can now take a look at some additional building blocks of our JavaScript code, and that would be in the form of JavaScript Operators and Expressions. Much like peanut butter and jelly, or Celebrities and The Paparazzi, operators and expressions go together. So let’s go ahead and jump right into JavaScript Operators and Expressions.
JavaScript Expressions
One of the main things we do with programs is to evaluate a condition and take action based on that condition. When we write a line of code that can be evaluated to a value, this is what’s called an expression. Even the simplest lines of code can be an expression. Extremely simple expressions are called primary expressions yet the more complex expressions are what we are more interested in. We can build these complex expressions using various combinations of primary expressions.
JavaScript Operators
We need to make use of operators in our code so that we can update, move, and modify our data. We do this with operators. Operators are simply the symbols used for this purpose. Let’s check them out.
JavaScript Arithmetic Operators
Like all programming languages, we need a way to perform math and of course JavaScript has the addition, subtraction, multiplication, and divide by as shown here:
+ – * /
JavaScript Assignment Operator
In any of the C based languages, JavaScript included, it is easy to mistake the assignment operator for the comparison operator. The =
is strictly for assignment only. Make sure to remember that =
is assignment, ==
is equality comparison, and ===
is strict equality comparison. You never want to run into a situation where you mistakenly use the wrong symbol like this:
var x = 3;
var y = 10;
if ( x = y ) {
// always true no matter what!
}
This will lead to unexpected results and bugs.
You’ll often see assignments like this:
points = points + 5;
or maybe something like
count = count + 3;
These types of assignments happen so frequently that we have been given shorthand assignment operators. It’s easy to use these shorthand assignment operators, and they work for addition, subtraction, multiplication, and division. The examples above could be more easily written as
points += 5;
and
count += 3;
This shorthand technique works with addition, subtraction, multiplication, and division.
+= -= *= /=
JavaScript Operator Precedence
Some operator symbols are given more importance than others. This is what we call operator precedence. Multiplication and division are given more importance than addition or subtraction. In the following example, 3 is multiplied by 10, and that product is added to 7 which gives the result of 37.
result = 7 + 3 * 10;
If there was a need to change the operator precedence we could rewrite the expression like so to alter the result to 100. The main idea is to remember that by using parentheses, you can set the precedence in your JavaScript as needed. In the following table, the operators at the top have the highest precedence, and the lowest, of course, have the lowest precedence.
result = (7 + 3) * 10;
Operator Precedence |
|
. [] ( ) | Refinement and invocation |
delete new typeof + – ! | Unary operators |
* / % | Multiplication, division, modulo |
+ – | Addition/concatenation, subtraction |
>= <= > < | Inequality |
=== !== | Equality |
&& | Logical and |
|| | Logical or |
?: | Ternary |
JavaScript Comparison Operators
Let’s review, the =
, ==
, and ===
operators one more time. They are key in getting our programs to work correctly!
= assignment
== equality
=== strict equality
The Full Table of JavaScript Operators
Operator |
Operation |
++ | Pre- or post-increment |
– – | Pre- or post-decrement |
– | Negate number |
+ | Convert to number |
~ | Invert bits |
! | Invert boolean value |
delete | Remove a property |
typeof | Determine type of operand |
void | Return undefined value |
* / % | Multiply, divide, remainder |
+ – | Add, subtract |
+ | Concatenate strings |
<< | Shift left |
>> | Shift right with sign extension |
>>> | Shift right with zero extension |
< <= > >= | Compare in numeric order |
< <= > >= | Compare in alphabetic order |
instanceof | Test object class |
in | Test whether property exists |
== | Test for equality |
!= | Test for inequality |
=== | Test for strict equality |
!== | Test for strict inequality |
& | Compute bitwise AND |
^ | Compute bitwise XOR |
| | Compute bitwise OR |
&& | Compute logical AND |
|| | Compute logical OR |
?: | Choose 2nd or 3rd operand |
= | Assign to a variable or property |
*= /= %= += | Operate and assign |
-= &= ^= |= | Operate and assign |
<<= >>= >>>= | Operate and assign |
Testing Operators and Expressions with the Firebug Console
With JavaScript being a client-side language, we have the added benefit of being able to test small snippets of code very easily from the console of our web browser. In Firefox, you can install firebug and it works like a charm in this testing and debugging. Google Chrome has an implementation of this functionality that is just as, if not, more powerful than the firebug tool in it’s Chrome Developer Tools. Since I’m used to Firebug, we’ll stick with the first option for these simple examples.
Firebug Tip: As you may know, you can run firebug in the browser while visiting any website. A simple word of caution here. If you are opening the console of firebug to try and test or debug some of your own JavaScript snippets, make sure you are visiting a bare-bones HTML webpage on your own local server! Websites on the internet have all manner of large JavaScript in them, and Firebug will have this data in memory as you begin to try and debug your snippets. You will get all kinds of unexpected and random behavior in the browser and console if you begin to run your JavaScript code on top of what is already in the browser’s JavaScript engine, and your debugging will be painful!
Here is a simple example of an expression taking a string and putting it into a variable:
var website = 'http://www.vegibit.com';
console.log(website);
How do we know it is a string? Well, by the fact that the characters are inside single quotes, we can believe the data is a string. Don’t take my word for it however, test your types using the typeof keyword:
var website = 'http://www.vegibit.com';
console.log(typeof(website));
var number = 1.61803398875;
console.log(typeof(number));
var undefined;
console.log(typeof(undefined));
var bool = true;
console.log(typeof(bool));
var funky = function () {
return 'I do stuff';
}
console.log(typeof(funky));
var numbers = [1,2,3,4,5];
console.log(typeof(numbers));
var state = { "state" : "hungry" };
console.log(typeof(state));
Hey, wait a minute! Why are there two objects shown in the debug output? It looks like we created an array and assigned it to the numbers variable. What is happening here? According to the Mozilla Developers Network an Array is actually an object.
Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array’s size length grow or shrink at any time, JavaScript arrays are not guaranteed to be dense. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.
It’s just one of the many quirks in the JavaScript language that may not seem to make total sense. We’ll revisit this concept further when we take some time to dedicate to a full examination of JavaScript Arrays and Objects.