Skip to content

Unary Operators

The Unary Operators

Operator Function
++ Increments a Number by 1
-- Decrements a Number by 1
typeof Returns a string representing the data type

Important

The JavaScript community is moving away from using the unary operators. However, we need to learn them as there is a lot of code that uses them.

Using the Unary Operators

These are a few handy shortcuts.

Unary means that there is only one variable or value involved with the operator. Usually we have to have something on either side of the operator, like the plus sign. But, these just have one. Practice pronouncing "unary". Say it out loud! It is pronounced like "YEW-nair-y". You already can say "binary" (BI-nair-y) and unary is the same except for the "u".

The ++ Operator

Here's the first way we've seen to add one to a number
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Addition with the +
let myCount;

myCount = 5;

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

myCount = myCount + 1;

document.write("myCount: " + myCount);

But this is too much typing!
myCount = myCount + 1;
Fortunately, we have a shortcut. This does the same thing.
myCount++; // Increment by one
We use it like this.
1
2
3
4
5
6
7
8
// Incrementing with ++
let myCount = 5;

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

myCount++;

document.write("myCount: " + myCount);


The -- Operator

I bet you can guess what this one does!
myCount--; // ???
That's right, it subtracts one from myCount
1
2
3
4
5
6
7
8
// Decrementing with -- 
let myCount = 5;

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

myCount--;

document.write("myCount: " + myCount);


The typeof operator

We're only going to look at one other unary operator: typeof(). It looks like a call to a function with parentheses. It tells us what type of data we have. It actually returns the strings "number", "string", and "boolean".

typeof(5) <-- this will be "number"
Using typeof
1
2
3
4
5
6
// Demo of typeof()
document.write("The type of 10 is: \"" + typeof(10) + "\"");
document.write("<br />");
document.write("The type of \"10\" is: \"" + typeof("10") + "\"");
document.write("<br />");
document.write("The type of (5 == 5) is: \"" + typeof(5 == 5) + "\"");

Read more

Related Reading

Pages 188 - 189

Hands on Work

Labs

  1. Lab08: Unary Operators
    • unit02/labs/lab-08-unaryOperators.html