Useful JavaScript Operators
Nathan Pasko
Posted on November 15, 2020
What are operators? They can do all kinds of things and take many different forms. They turn up everywhere, so the goal of this article is to familiarize you with operators that you'll see and use frequently. There are a few different families of operators in JavaScript, but today we'll focus to those most useful for web dev.
Assignment operators
One type of operator you're probably familiar with is assignment operators. They assign the value on their right side to their left side, like we'd do declaring a variable: var variable = 0
. Besides =
there are a number of assignment operators that are useful shorthand.
// Assign a value to a new variable
var variable = 0;
// Shorthand to increase variable's value by 1
variable += 2;
// Shorthand to decrease the variable's value by 1
variable -= 1;
// Our variable is at 1
console.log(variable);
// Shorthand to multiply a value into variable
variable *= 2;
// Shorthand to divide variable by value
variable /= 2;
// Our variable is at 1
console.log(variable);
These shorthand assignment operators save us from having to write variable = variable + 1
out to add, write variable = variable - 1
to subtract, and so on.
Comparison Operators
Another family of operators called comparison operators are used to compare two values.
Greater & Less Than
These operators return true if the values on either side compare as written: greater than, less than, greater than or equal to, and less than or equal to.
// Assign a variable for comparison
var target = 4;
// Is variable greater than the target?
console.log(variable > target);
// Is variable less than the target?
console.log(variable < target);
// Assign the target to the variable
variable = target;
// Is the variable greater than or equal to the target?
console.log(variable >= target);
// Is it less than or equal to the target?
console.log(variable <= target);
Because operators return values, we're able to log to the console and see what's happening.
Note! |
---|
Remember in an operator, the = will always come last. Don't confuse >= with => , an arrow function declaration. |
Different Equals
The comparison operators above are fairly familiar, but the comparison of equality takes a couple different forms.
If you've read other JavaScript projects, you might wonder: what is the difference between ===
and ==
, between a triple equals and a double equals? Both perform similar comparisons, but the triple equals is used to ascertain strict equality, while the double equals is used to ascertain abstract equality. The main difference between these two is that ==
will compare both values after converting them to a common type, while ===
will compare the values without attempting to convert either one. Thus the term 'strict equality': it is not as loose in determining sameness.
// Let's start with a string a single number.
var str = '3';
// Abstract equals says an integer is equal to our string
console.log(str == 3);
// Strict equals recognizes that a string and an integer are
// are different types
console.log(str === 3);
// To return true, we can compare with a literal string
console.log(str === '3');
Arithmetic Operators
We can use arithmetic operators to manipulate values and return a number. One useful operators from this family is the remainder operator, %
, which returns the remainder of dividing the numbers given on its left and right.
// Get the remainder of 5 divided by 2
console.log(5 % 2);
There are also several useful shorthands that allow us to perform number manipulations effectively in place: ++
, --
, and -
.
// Shorthand to increase a number by 1
variable++;
console.log(variable);
// Shorthand to decrease a number by 1
variable--;
// Variable is back where we started
console.log(variable);
// Shorthand to negate a value
console.log(-variable);
A single +
is a unary operator to attempt a value's conversion into a number. We could use this to revisit our earlier example of strict and abstract equality.
We could replace this line:
console.log(str === 3);
which returns false
because str
is equal to '3'
, with this line:
console.log(+str === 3);
to return true
.
This works because we use the +
operator to convert str
to a number value before the comparison.
Logical Operators
You'll frequently logical operators that represent or and and to test multiple conditions at once. Or is written using ||
and will return true if either the left or right sides of the operator are true. And is written using &&
and will return true only if both sides of the operator are true. We might use these with if
to express the conditions under which we want to do something.
// a music track that can be in our library
var inLibrary = true;
// count how many times the track was played
var playCount = 0;
// Do something if we played the track or added it to library
if (inLibrary || playCount > 0) {
console.log('some interaction with this track');
}
// Do something else if we've both added to library & played
if (inLibrary && playCount > 0) {
console.log('track both played and in library');
}
else {
console.log('track either in library or played');
}
In the example above, we could have used comparison operators to write if (inLibrary === true ...
, but since inLibrary
is a boolean, we don't need to write === true
. It's redundant because merely accessing a boolean will give you its value of true or false.
Conditional (ternary) operator
The conditional operator is the only JavaScript operator that receives three operands (the others receive one or two), so it's also known as ternary. This operator is very useful, however it reads like something of a shorthand. The conditional operator is at work when you see something like this: var v = condition === true ? 4 : 7;
with ?
and ;
.
This syntax is a condensed form of something like this:
// declare a value
var val;
// set the value if a condition is met
if (condition === true) {
val = 4;
}
// else set the value differently
else {
val = 7;
}
We're testing a condition and doing one thing if the result is true, or a different thing if it's false. Using the conditional operator we can rewrite the above idea into something more condensed:
// declare a value by first testing a condition
var val = condition === true ? 4 : 7;
The ternary operator allows us to specify a condition to test, and separate outcomes to return if the condition proves true or false.
Here's another example. We have a toolbar HTML element that has a toggling open and a closed state. We have another HTML element with the nav
for our page. We want the nav
to appear when the toolbar is open, and disappear when the toolbar is closed. First we'll grab that nav
element in our JavaScript as navElement
. Then we can use the ternary operator to check the toolbar's status.
// declare a variable in accordance with navOpen's value
var showNav = navOpen ? true : false;
// we can add class active to show the nav or remove it to hide
if (showNav) {
navElement.classList.add('active');
}
else {
navElement.classList.remove('active');
}
Last Word
Operators allow us to express all kinds of relationships in JavaScript. They're trivial but crucial to familiarize yourself with as you learn how to read and write JavaScript. The conditional operator is an especially good addition to your tool belt. Of course, other operators exist outside of what's demonstrated in this article, but this is a collection of operators that are important to recognize and understand.
Posted on November 15, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024