This is the last article in "The Power of Javascript" series covering operators. In this part, we discuss the logical operators, the operator typof, the void operator, the ternary operator :?, and operators' precedence and Associativity. You may not realize the power and usefulness of operators yet, but when we discuss how you can control your script flow of execution with if/else statements and loop statements, you will realize what operators can do for you, especially the logical operators and the comparison operators.
The Power of Javascript: Operators concluded - The Operator typeof (Page 3 of 5 )
The typeof Operator (written in lower case because Javascript is case-sensitive) is a special type of operator that we have not discussed yet. For now we can say that not all operators are symbols, and typeof is one example of that. The typeof operator returns the data type of its operand, but to use it you must place the operand between parentheses (we will talk about parentheses use throughout the series so don't worry about what it means right now) like this: typeof(operand) as in the following example.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> <script language="JavaScript" type="text/javascript"> var aNumber = 1; var aString = "I'm a string"; var aBoolean = true;
document.write("aNumber data type = " + typeof(aNumber) + "<br>"); document.write("aNumber data type = " + typeof(aString) + "<br>"); document.write("aNumber data type = " + typeof(aBoolean)+ "<br>"); </script> </head> <body> </body> </html>
When you save and load this code in your browser you will get the following text written to the Web page.
As you guessed the expressions typeof(aNumber), typeof(aString) and typeof(aBoolean) just return the data type of the operand (the variable result) of the typeof Operator. Note that the typeof Operator returns two more data types (object and function) but we will talk about that when the time comes.