PASSWORD RESET

Your destination for complete Tech news

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

491 0
< 1 min read

To check if a variable is a string in JavaScript, you can use the typeof operator and the Object.prototype.toString.call method.

Here are some examples of how to use these methods to check if a variable is a string:

1. To check if a variable is a string using the typeof operator, you can use the following code:

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

console.log(isString('hello'));  // Outputs: true
console.log(isString(123));      // Outputs: false

This function returns true if the type of the val argument is 'string', and false otherwise.

2. To check if a variable is a string using the Object.prototype.toString.call method, you can use the following code:

function isString(val) {
  return Object.prototype.toString.call(val) === '[object String]';
}

console.log(isString('hello'));  // Outputs: true
console.log(isString(123));      // Outputs: false

This function returns true if the Object.prototype.toString method applied to the val argument returns the string '[object String]', and false otherwise.

Both of these methods can be used to check if a variable is a string in JavaScript. The typeof operator is simpler and faster, but it may not always return the expected results for certain types of values, such as objects or arrays that have been converted to strings. The Object.prototype.toString.call method is more reliable, but it is slightly slower and more verbose.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.