JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if a variable is a string in JavaScript?

If you want to check if a variable is a string, then use the typeof operator.

The typeof operator returns "string" if a variable is a string.

On the other hand, if a variable is not a string, then the typeof operator returns a different value.

The syntax for using the typeof operator with a string is

typeof string

Let's understand the process with the help of an example:

let x = "JavaScript";
if(typeof x === "string"){
  console.log("Variable x is a string.");
  console.log("Variable x is not a string.");


Variable x is a string.

Recommended Posts