JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 18

What does the 'typeof' operator do in JavaScript?

Answer:

The 'typeof' operator returns a string indicating the type of the unevaluated operand. It is useful for type checking and debugging. The possible return values of the 'typeof' operator are: 'undefined', 'object', 'boolean', 'number', 'string', 'symbol', and 'function'. This operator helps in determining the type of a variable or expression, aiding in writing more robust and error-free code.

Here is an example demonstrating the use of the 'typeof' operator:

let name = 'John';
let age = 30;
let isMarried = true;
let car = null;
let address;
let sym = Symbol('symbol');
let person = { name: 'John', age: 30 };
let greet = function() { console.log('Hello'); };

console.log(typeof name); // 'string'
console.log(typeof age); // 'number'
console.log(typeof isMarried); // 'boolean'
console.log(typeof car); // 'object' (this is a known quirk)
console.log(typeof address); // 'undefined'
console.log(typeof sym); // 'symbol'
console.log(typeof person); // 'object'
console.log(typeof greet); // 'function'

In this example, we use the 'typeof' operator to check the type of various variables, illustrating its use in type checking.

Recent job openings