Determining Type: typeof vs instanceof
The typeof operator tells if a variable is a primitive type. It tells if a variable is a string, number, Boolean, or undefined. If the value is an object or null, then typeof returns "object":
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var s = "JavaScript";
var b = true;
var i = 22;
var u;
var n = null;
var o = new Object();
document.writeln(typeof s); //string
document.writeln(typeof i); //number
document.writeln(typeof b); //boolean
document.writeln(typeof u); //undefined
document.writeln(typeof n); //object
document.writeln(typeof o); //object
</script>
</head>
<body>
</body>
</html>
To know is what type of object it is JavaScript provides the instanceof operator. Its syntax:
result = variable instanceof constructor
The instanceof operator returns true if the variable is an instance of the given reference type.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var person = new Object();
var colors = new Array();
document.writeln(person instanceof Object); //is the variable person an Object?
document.writeln(colors instanceof Array); //is the variable colors an Array?
</script>
</head>
<body>
</body>
</html>
Home
JavaScript Book
Language Basics
JavaScript Book
Language Basics
Variables:
- Primitive and reference values
- Determining Type: typeof vs instanceof
- Execution Context And Scope
- No Block-Level Scopes
- Variable Declaration with var