Check whether variable is number or string in JavaScript
If you're dealing with literal notation, and not constructors, you can use typeof:.
typeof "Hello World"; // string
typeof 123; // number
If you're creating numbers and strings via a constructor, such as var foo = new String("foo")
, you should keep in mind that typeof
may return object
for foo
.
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
This returns a boolean true
for the following:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
Check if a variable is a string in JavaScript
You can use typeof
operator:
var booleanValue = true;
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"
Example from this webpage. (Example was slightly modified though).
This won't work as expected in the case of strings created with new String()
, but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.
- The Google JavaScript Style Guide says to never use primitive object wrappers.
- Douglas Crockford recommended that primitive object wrappers be deprecated.
How can I check if a string is a valid number?
2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".
":
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
To check if a variable (including a string) is a number, check if it is not a number:
This works regardless of whether the variable content is a string or number.
isNaN(num) // returns true if the variable does NOT contain a valid number
Examples
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false
Of course, you can negate this if you need to. For example, to implement the IsNumeric
example you gave:
function isNumeric(num){
return !isNaN(num)
}
To convert a string containing a number into a number:
Only works if the string only contains numeric characters, else it returns NaN
.
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
Examples
+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
To convert a string loosely to a number
Useful for converting '12px' to 12, for example:
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
Examples
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.
Floats
Bear in mind that, unlike +num
, parseInt
(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt()
because of this behaviour, you're probably better off using another method instead):
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
Empty strings
Empty strings may be a little counter-intuitive. +num
converts empty strings or strings with spaces to zero, and isNaN()
assumes the same:
+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
But parseInt()
does not agree:
parseInt('') // NaN
parseInt(' ') // NaN
How to check if a variable is an integer in JavaScript?
Use the === operator (strict equality) as below,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
How do you easily check whether a Variable is number or not in JavaScript?
First version =>
-- simply use isNaN()
: sum+(isNaN(val)?0:Number(val)
Second version (asked in comment here) =>
-- just use a strict comparison. to get only numeric type values.
const calculation =(...numbers)=> // (n1,n2 , ...numbers)=>
numbers.reduce((sum,val)=>
sum + (Number(val)===val ? val : 0) // sum+(isNaN(val)?0:Number(val))
, 0);
console.log( calculation(5,6,7,'gg','',null, NaN, undefined, null,8,9,5.4,'10') )
how to check whether a var is string or number using javascript
The line
var number = "1234";
creates a new String object with the value "1234". By putting the value in quotes, you are saying that it a string.
If you want to check if a string only contains numeric digits, you can use regular expressions.
if (number.match(/^-?\d+$/)) {
alert("It's a whole number!");
} else if (number.match(/^-?\d+*\.\d+$/)) {
alert("It's a decimal number!");
}
The pattern /^\d+$/
means: at the start (^
) of the string, there is an optional minus sign (-?
), then a digit (\d
), followed by any more digits (+
), and then the end of the string ($
). The other pattern just looks for a point between the groups of digits.
what is the best way to check variable type in javascript
The best way is to use the typeof
keyword.
typeof "hello" // "string"
The typeof
operator maps an operand to one of six values: "string"
, "number"
, "object"
, "function"
, "undefined"
and "boolean"
. The instanceof
method tests if the provided function's prototype is in the object's prototype chain.
This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types.
Check that variable is a number
I'd go with
isFinite(String(foo))
See this answer for an explanation why. If you only want to accept integer values, look here.
How to check If the value of an input is number or string in react js?
The simplest way will be to convert the string to a number and then check if its valid. As the value of inputs is always a string
even if u use type="number"
, tho it is good to use it if u just want numbers as the input.
You can use isNaN(+value)
. Here +
will convert a string to a number.
<input
type="text"
onChange={(e) => {
const value = e.target.value;
console.log(!isNaN(+value)); // true if its a number, false if not
}}
/>;
Some test cases:
console.log(!isNaN(+"54"));
console.log(!isNaN(+"23xede"));
console.log(!isNaN(+"test"));
JavaScript check if variable exists (is defined/initialized)
The typeof
operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof
operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null
will return "object"
. We have to be careful to avoid the mistake of initializing a variable to null
. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison ===
instead of simple equality ==
, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Related Topics
Function Declarations Inside If/Else Statements
JavaScript - Arrow Functions This in Event Handler
Firestore Update Single Item in an Array Field
Assigning Prototype Methods *Inside* the Constructor Function - Why Not
Jquery Get Specific Option Tag Text
Using Node.Js, How to Read a JSON File into (Server) Memory
Javascript: Passing Parameters to a Callback Function
Angularjs Passing Data to $Http.Get Request
Variable === Undefined VS. Typeof Variable === "Undefined"
Why Is [1,2] + [3,4] = "1,23,4" in JavaScript
Regex for JavaScript to Allow Only Alphanumeric
Handling Errors in Promise.All
How to Compare Software Version Number Using JS? (Only Number)
Difference Between 'Return Await Promise' and 'Return Promise'
Phantomjs Not Waiting for "Full" Page Load
Get File Size Before Uploading
How to Resize Images Proportionally/Keeping the Aspect Ratio