Module 3: Operators and User Interaction
Special Operators: typeof, instanceof, delete
typeof
Operator:
Returns a string indicating the type of its operand.
console.log(typeof 42); // "number" console.log(typeof "hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof null); // "object" (a known quirk in JavaScript) console.log(typeof {}); // "object" console.log(typeof []); // "object" (arrays are a type of object) console.log(typeof function(){});// "function"
instanceof
Operator:
Checks if an object is an instance of a particular class or constructor function. Returns true
or false
.
let arr = []; let date = new Date(); console.log(arr instanceof Array); // true console.log(date instanceof Date); // true console.log(date instanceof Object); // true (Date inherits from Object) console.log(arr instanceof Date); // false
delete
Operator:
Removes a property from an object. It does not affect variables or functions declared with var
, let
, or const
directly.
let user = { name: "Alice", age: 30 }; console.log(user.age); // 30 delete user.age; console.log(user.age); // undefined console.log(user); // { name: "Alice" } let globalVar = 10; delete globalVar; // In strict mode, this throws an error. In non-strict mode, it returns false (cannot delete non-configurable properties).
The delete
operator is primarily used for object properties. Using it on array elements will leave an undefined
hole in the array, not re-index it.