Home > Web Front-end > JS Tutorial > How to Determine if a Variable is a Number or a String in JavaScript?

How to Determine if a Variable is a Number or a String in JavaScript?

Mary-Kate Olsen
Release: 2024-11-09 19:43:02
Original
201 people have browsed it

How to Determine if a Variable is a Number or a String in JavaScript?

Identifying Variable Type: Number vs. String in JavaScript

Determining whether a variable in JavaScript represents a number or a string can be crucial for various operations. In this article, we explore multiple methods to effectively check variable types.

Using typeof Operator

For literal values, the typeof operator provides a basic way to distinguish between numbers and strings. It returns "string" for string literals and "number" for numeric literals.

typeof "Hello World"; // string
typeof 123;           // number
Copy after login

Handling Constructed Variables

When dealing with variables created using constructors (e.g., var foo = new String("foo")), the typeof operator may return "object." To address this, consider the following approach:

var toString = Object.prototype.toString;

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

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

This method leverages the toString method of the Object prototype to determine the object type. It returns a boolean value, indicating whether or not the variable is a string.

By employing these techniques, you can reliably check the type of JavaScript variables and ensure correct data handling in your code.

The above is the detailed content of How to Determine if a Variable is a Number or a String in JavaScript?. 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