Home > Web Front-end > JS Tutorial > 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
Release: 2024-11-08 00:10:03
Original
539 people have browsed it

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
Copy after login

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]';
}
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template