Home  >  Article  >  Web Front-end  >  How do you determine if a JavaScript variable is a number or a string?

How do you determine if a JavaScript variable is a number or a string?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 00:10:03419browse

How do you determine if a JavaScript variable is a number or a string?

Determining Variable Type in JavaScript: Numeral or String

To ascertain the data type of a variable in JavaScript, specifically whether it's a number or a string, consider the following approaches:

Literal Notation and typeof Operator:

For variables initialized using literal notation (e.g., "Hello World" or 123), use the typeof operator:

typeof "Hello World"; // string
typeof 123;           // number

Constructor Usage and typeof Operator:

When creating variables using constructors (e.g., var foo = new String("foo")), keep in mind that `typeof may return "object" for these variables.

Underscore.js Library:

For a more comprehensive method, utilize the isString method from the underscore.js library:

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

This method will accurately return true for both string literals and strings created using the constructor:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true

By employing these techniques, you can effectively determine whether a JavaScript variable is a number or a string, regardless of its initialization method.

The above is the detailed content of How do you determine if a JavaScript variable is a number or a string?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn