"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-12
Browse:624

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3