OneBite.Dev - Coding blog in a bite size

use typeof in javascript

Code snippet for how to how to use typeof in javascript with sample and detail explanation

JavaScript comes with various features that help developers perform several tasks efficiently. One of these features is the typeof operator. This article will provide a detailed explanation of how to use typeof operator in JavaScript.

Using the typeof operator

Here is a simple snippet representing how the typeof operator works in JavaScript.

var data = 'Hello World';
console.log(typeof data);

// Output: string

Code Explanation

Let’s dissect the code, line by line to understand how the typeof operator works in JavaScript.

In the first line of code, we declare a variable named ‘data’ and set its value to be a string, ‘Hello World’.

var data = 'Hello World';

‘var’ is the keyword that tells JavaScript to declare a variable. ‘data’ is the name we’ve given to our variable, and ‘Hello World’ is the string value that we’ve assigned to it. The semi-colon at the end of the line indicates that we’ve finished declaring the variable.

In the second line, we call upon JavaScript’s built-in console.log function to print something out to the console - in this case, the type of the variable ‘data’.

console.log(typeof data);

‘console.log’ is JavaScript’s way of ‘printing’ or ‘logging’ something out. Inside the parentheses, we’ve written ‘typeof data’. Here ‘typeof’ is an operator. It’s a special keyword in JavaScript that returns the type of the expression following it.

The expression following ‘typeof’ in our code is the variable ‘data’. Hence, ‘console.log(typeof data)’ will print out the type of ‘data’ to the console, which, since ‘data’ is a string, will be ‘string’.

Therefore, the output of this code snippet will be ‘string’.

Using typeof in JavaScript is straightforward. It’s a crucial part of JavaScript that you’ll likely use often, especially when debugging your code, to check the data type of your variables. It returns the type of argument its given. The returned type is in the form of a string. The argument can be any sort of object, function, or variable.

javascript