| by Arround The Web | No comments

How to Write isNumber() in JavaScript

There are some situations where the programmers need to write the custom “isNumber()” function in JavaScript, such as validating the user input to ensure that the values are of the expected type or not before performing any operations on them and so on.

This blog will define the way to write the “isNumber()” function in JavaScript.

How to Write isNumber() in JavaScript?

There are many ways to write a function in JavaScript to check if a given value is a number. Here is one example of a function that uses the “typeof” operator to check or verify the input value type.

Example

First, define a function that will take a value as an argument to check whether it is a number:

function isNumber(value){
 return typeof value === 'number';
}

 

This function uses the typeof operator to check if the input value is of the “number” type.

Call the “isNumber()” function and pass a value “1151”:

console.log(isNumber(1151));

 

Pass the value “‘55’” to the function to check whether it is a number or not:

console.log(isNumber('55'));

 

The output indicates that the “1151” is the number while the “‘55’” is not number as it acts as a string and the typeof operator returns “false”:

You can also use the JavaScript library “underscore.js” to write the isNumber() function in JavaScript to whether the given value/object is number or not:

<script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>

 

The “_.isNumber()” is a JavaScript pre-built method in JavaScript that is used with the “underscore.js” library.

Create an array of even numbers:

var array = [2, 4, 6, 8, 10, 12, 14, 16];

 

Call the “_.isNumber()” function in console.log() method and pass the array, an integer number and a floating point number as a parameter:

console.log(_.isNumber(arr));
console.log(_.isNumber(11));
console.log(_.isNumber(31.792));

 

The output displays “true” for the integer and floating point numbers and “false” for the array:

That was all about writing isNumber() in JavaScript.

Conclusion

To write the isNumber() function in JavaScript, use the “typeof” operator or the JavaScript library “underscore.js”. The isNumber() function can help to ensure that the code is robust, readable, and maintainable. It can also validate user input and data from external sources and ensure that the code performs the expected operations on the correct data types. This blog described the procedure to write the “isNumber()” function in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply