How do I check if a variable is a string in JavaScript?
Alex K
alex k profile pic

To check if a variable is a string in JavaScript, you can use thetypeof operator and compare the result to the string value'string'. Here's how you can do it:

1
2
3
4
5
6
7
8
9
10

function isString(variable) {
  return typeof variable === 'string';
}

// Examples:
console.log(isString('Hello')); // Output: true
console.log(isString(123)); // Output: false
console.log(isString(true)); // Output: false
console.log(isString({})); // Output: false

In the example above, we define a functionisString that takes avariable as an argument. Inside the function, we use thetypeof operator to determine the type of the variable. We compare the result to the string'string' using the strict equality operator (===). If the variable's type is equal to'string', the function returnstrue, indicating that the variable is a string. Otherwise, it returnsfalse. You can use theisString function to check if a variable is a string in various scenarios. For example, you can use it to validate user input, ensure that the expected data type is met, or perform conditional operations based on the type of the variable.