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 |
|
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 |
|
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 |
|
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 |
|
Read more¶
Related Reading
Pages 188 - 189
Hands on Work¶
Labs
- Lab08: Unary Operators
- unit02/labs/lab-08-unaryOperators.html