JavaScript If Else with Return - javascript

Still doing the Codecademy training for JavaScript and I've hit a road block.
Here's the code:
var isEven = function(number) {
if (isEven % 2 === 0) {
return true;
} else {
return false;
}
};
isEven(2);
So I'm referencing the variable "isEven." Then, I'm telling it to check the number and cross-check it with the modulo to check the remainder against 2 to find out if it's even. If it is, for example, 2 like in the example it should return a remainder of zero, therefore the if is true and it returns true. But it returns false every time. There's no warning messages in the code but when I hit save and it checks it it gives me this message:
"Oops, try again. Looks like your function returns false when number = 2. Check whether your code inside the if/else statement correctly returns true if the number it receives is even."

I think you had the wrong variable name:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
}
return false;
};
isEven(2);

you could also do:
var isEven = function(number) {
return number % 2 === 0
};

Your function and variable have the same name. Name the function or the variable differently and it will work.

You need change varible isEven to number, like:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
isEven(2);

Related

Check if number is divisible by another number in JS

I am pretty new at this stuff, and I am solving a series of questions, but I've got lost in this one.
I have to verify if a number can be divided by other, and the answer must be true or false.
I got his
function solucao(numero, x) {
solucao(numero % x);
if (solucao === 0) {
resultado = true;
}else{
resultado = false;
}
}
But I'm getting runtime error and can't see whats is missing.
So you want to check if a number numero is divisible by x. The modulo operator can help. Try this:
function solucao(numero, x){
if (numero % x == 0){
return true
}
else {
return false
}
}
function solucao(numero, x) {
let resultado;
if (numero % x === 0) {
resultado = true;
}else{
resultado = false;
}
return resultado;
}
I think you get confused at some point. You are calling the function, inside of itself. You should do like this, and also, declare the result variable.
I am sure this will help:
function checkIfDivided(){
// in this section the variables come from an html document
var number=parseInt(document.getElementById("number").value);
var divisor=parseInt(document.getElementById("divisor").value);
if(number%divisor==0)
return true;
else return false;
}
or
function checkIfDivided(number,divisor){
//in the function the variable are given as parameters
if(number%divisor==0)
return true;
else return false;
}
Looks like two things to me:
You haven't declared your 'resultado' variable ( this can be as simple as just typing 'let resultado;' without the single quotes
You haven't returned your 'resultado' variable after the if/else statement
Right now, your function is using an undeclared variable and not returning anything, so that is why you are getting an error. Fix the two above steps and you should be good! :)
You clearly understand that the modulus operator is the way to go. Using it we discover that 12 is divisible by 3 because 12 % 3 return zero. Zero is considered a "falsy" value while any other number is considered "truthy".
Given this then if 12 % 3 returns a "falsey" value (zero) we can't use the result directly. But what if we can "flip" false to true? We can, using the not operator (!).
Using the ! operator on the result of a math problem requires the use of parentheses around the math problem itself.
So the problem in code becomes (12 % 3) and to 'flip' it with the ! operator it becomes
!(12 % 3).
This is proven below with:
console.log(!(12 % 3)) --> logs true
console.log(!(12 % 5)) --> logs false
The function implementation of that is simple and also proven:
console.log(isDivisible(12,3)); --> logs true
console.log(isDivisible(12,5)); --> logs false
console.log(!(12 % 3))
console.log(!(12 % 5))
function isDivisible(number, x){
return !(number % x);
}
console.log(isDivisible(12,3));
console.log(isDivisible(12,5));
There is one other way to do so and i think its much cleaner.
console.log(Number.isInteger(10/2)) //true
console.log(Number.isInteger(4/2)) // false
//a must be greater than b
function check(a,b) {
console.log(Number.isInteger(a/b))
return Number.isInteger(a/b)
}
check(10,5)//true
check(8,3)//false

Possibility to declare variable from function in IF statement?

I'm back again. I had this little question about a possibility that I could declare a variable in the IF condition from a function, and to use it inside the statement itself.
Ok so, I'm curious to see if there's a way to declare a variable inside an IF statement's condition, and use that further along the statement as follows:
function SomeFunc() {return true}
if (let n = SomeFunc()) {
console.log(n); // true
// n is truthy
} else {
// Would never run, because it always returns true.
// This is just an example though, where it can return a truthy or falsy value dependent on the input context I could give it.
console.log(n); // false (if it actually returned 'false')
// n is falsy
}
Is there any way to do this, without having to run the function twice and not have it run outside the IF statement?
(Not like this though):
let n = SomeFunc();
if (n) { ... } else { ... }
// Or this:
if (SomeFunc()) {
let n = SomeFunc();
} else { ... }
I'd like to have one function being declared inside the condition, to minimalise line usage and have it - for me - clean. I hope there's a way to declare a variable inside of an IF condition.
Thank you in advance.
~Q
The syntax does not allow let, const or var to appear at that position.
But you could just define the variable (without initialisation) and then do the if:
let n;
if (n = SomeFunc()) {
// n is truthy
} else {
// n is falsy
}
If you want to limit the scope of that variable just to that if, then put it inside a block:
// other code...
{
let n;
if (n = SomeFunc()) {
// n is truthy
} else {
// n is falsy
}
}
// other code...
Of course, if your function has no other code, then no extra block is needed: the function's block will apply.
Many will disagree with you that an assignment within an if condition is clean. Best practice is to avoid such side effects in a condition, although opinions differ on this. Still, it does not take more characters to write it as follows, and it looks cleaner to me:
{
let n = SomeFunc();
if (n) {
// n is truthy
} else {
// n is falsy
}
}
As function expression
One other approach is to use an immediately invoked function expression, to which you provide the function's return value as argument:
(n => {
if (n) {
// n is truthy
} else {
// n is falsy
}
})(SomeFunc());
Ternary Operator
For a terse syntax use ternary operator:
var/const/let variable = (condition) ? value if true : value if false
The parenthesis wrapped around the condition are optional.
Demo
/*
Condition: if (number is greater than 10) ?
return true
: else return false
*/
const gTTen = number => { return (number > 10) ? true : false; }
console.log(gTTen(11));
console.log(gTTen(9));
function ternary(number) {
/*
Using the previous function then store its return in a
variable
*/
const tenFilter = gTTen(number);
/*
Condition: if (previous value is true AND the number is
less than 20) ?
range is 30
: else range is 0
*/
let range = (tenFilter && number < 20) ? 30 : 0;
/*
Condition: if (range = 30) ?
result is (the first string)
: else result is (the last string)
*/
let result = range === 30 ? `${number} is within range` : `${number} is not within range`;
return result;
}
console.log(ternary(50));
console.log(ternary(15));
Ah! I figured this out a few days ago, but didn't have time to respond. I could use local variables that I only overwrite while performing the statements.
Here's an example.
function retClone(bool) {
return bool; // Returns same input context for example.
}
if (t = retClone(true)) {
console.log(t); // true
// t is truthy, because we get `true` returned.
}
if (t = retClone(false)) {
// Wouldn't run.
// t is falsy.
} else {
console.log(t); // false
}
Thank you all who responded. ~Q

Javascript - every() method to check isInteger on array elements

I want to check return true if an array contains all integers or false if not. I am trying to use the every method MDN docs every.
So if given '1234' it will return true and if given '123a' it would return false.
function validatePIN (pin) {
pinArray = pin.split("");
if (pinArray.length === 4 || pinArray.length === 6) {
if (pinArray.every(Number.isInteger()) === true;) {
return true
}};
How does every pass the element to isInteger so it can test it?
Even if you fix syntax error and pass Number.isInteger as a function this won't work.
function wrongValidatePIN (pin) {
var pinArray = pin.split(""); // <-- array of strings
if (pinArray.length === 4 || pinArray.length === 6) {
if (pinArray.every(Number.isInteger)) { // <-- isInteger works with numbers
return true
}}
return false
}
console.log(wrongValidatePIN('1234'))
You need something like this
function validatePIN (pin) {
var pinArray = pin.split(""); // <-- array of strings
return (pinArray.length === 4 || pinArray.length === 6)
&& pinArray.every(char => !Number.isNaN(Number.parseInt(char, 10)))
}
console.log(validatePIN('1234'), validatePIN('123a'))
Or you could use regexp
function validatePin(pin) {
return /^(\d{4}|\d{6})$/.test(pin)
}
console.log(validatePin('1234'), validatePin('123456'),
validatePin('12345'), validatePin('123a'))
As the comments stated, the isInteger function can be passed as an argument by calling pinArray.every(Number.isInteger) instead of calling it a single time, (or by providing it inside a function .every(c=>Number.isInteger(c)) , but passing the function itself is more concise)
However, it's unlikely to provide the result you expect, because isInteger checks if the value is an actual integer, not if the value can be parsed to one.
That could be resolved with something like pinArray.map(parseFloat).every(Number.isInteger);
but then it would be easier to use !pinArray.some(isNaN)
That could make the function:
function validatePIN (pin) {
return (pin.length === 4 || pin.length === 6)
&& ![...pin].some(isNaN);
}
But as a final note, regular expressions are made for this type of check and could be preferable here
Your pin.split("") will never work when you pass number eg. 1234 as argument. Convert to string first then split pin.toString().split("").
Now inside .every() function we cast our string to number by doing +number.
return pinArray.every(number => Number.isInteger(+number));
.every() returns true or false.
Here is working example.
function validatePIN(pin) {
var pinArray = pin.toString().split("");
if (pinArray.length === 4 || pinArray.length === 6) {
// returns true or false
// +number casts string into number
return pinArray.every(number => Number.isInteger(+number));
}
// We assume that every PIN is not valid
return false;
};
console.log('test1', validatePIN(1234)); // true
console.log('test2', validatePIN('1234')); // true
console.log('test3', validatePIN('123a')); // false
console.log('test4', validatePIN('0001')); // true

Eloquent JavaScript 2nd Edition recursion exercise solution

I attempted to solve the recursion exercise of the online book eloquentjavascript 2nd edition:
Here is what the question states:
We’ve seen that % (the remainder operator) can be used to test whether
a number is even or odd by using % 2 to check if it’s divisible by
two. Here’s another way to define whether a (positive, whole) number
is even or odd:
Zero is even.
One is odd.
For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description.
The function should accept a number parameter and return a boolean.
Test it out on 50 and 75. See how it behaves on -1. Why? Can you think
of a way to fix this?
Here is what I have attempted and it works:
function isEven(number) {
if (number == 0) {
return true;
} else {
return (-number % 2 == 0) ? true : false;
}
return isEven(number - 2);
}
console.log(isEven(-1));
But, it seems to be a wrong answer because as I understood the author wants me to use - 2 method. I am wondering if this is indeed the correct answer or if it is wrong could someone point me in the right direction.
I think the reason you are getting confused is because you're not understanding how recursion works. The reason it is n-2 is, it is taking the number and subtracting 2 until it is either a zero or one. Therefore giving us a true or false.
Hope that helps. Read over how the process of recursion works.
The alternative solution that doesn't use the modulos operator % or any other built in functions in JavaScript is provided below. This solution instead relies on using another recursion to change negative value of the number.
function isEven(number) {
if (number < 0) {
return isEven(-number);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else {
return isEven(number - 2);
}
}
console.log(isEven(50)); // true
console.log(isEven(75)); // false
console.log(isEven(-1)); // false
We call isEven(number -2) to go back to the top of the function with the number that was inputed intially but 2 less than before and it will keep doing that until the number is 1 or 0 and then it will be able to return the boolean true or false (even or odd).
I think the problem is to create an isEven function without using a mod/%/remainder operation
function isEven(number) {
if (number < 0) {
number = Math.abs(number);
}
if (number===0) {
return true;
}
if (number===1) {
return false;
}
else {
number = number - 2;
return isEven(number);
}
}
I guess it is important to add to this
it doesn't handle strings
it doesn't handle floats
don't put this into a production application
function isEven(n) {
n = Math.abs(n);
if (n==0)
return true;
else if (n==1)
return false;
else
return isEven(n-2);
}
console.log(isEven(-50)); // → true
console.log(isEven(75)); // → false
console.log(isEven(-75)); // → false
console.log(isEven(-1)); // → false
var isEven = function(n) {
// Get the absolute value of the number
// so we don't have to bother with negatives
n = Math.abs(n);
// We know that if we subtract 2 from our number
// until it is equal to zero, our number was even
// If our number isn't zero, this statement will be skipped
if(n === 0) return true;
// We know that if we subtract 2 from our number
// and it reaches a value of 1, it isn't even
// If our number isn't 1, this statement will be skipped
if(n === 1) return false;
// We subtract 2 from our original number and pass it
// back in to this function to check it over and over again
// until one of the conditions is met and the function can
// return a result
return isEven(n - 2);
}
// We test our function here
console.log(isEven(-21));
This is the leanest method I could come up with. Notice we call our isEven function from within itself and pass in the value of n - 2. This will constantly subtract 2 from our number and check to see if it is equal to 0 or 1 until we get a proper result and return the corresponding boolean.
I hope this clears things up a little.
How about the below code? Seems to work for me.
/*if > 1 keep looking, otherwise return reverse boolean value.
If negative value, inverse, to answer the last part of the question...
Also needed to use parseInt as the text value I used,
was considered a string value!
This being a recursive function which really isn't necessary,
means that in javascript we will get a
stack size exceeded error when the number becomes too large.*/
function isEven(x) {
return (x>1)?isEven(x-2):(x>=0)?!x:isEven(-x);
}
The book wants the following console.log outputs for such values
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-2));
// → ??
The hint says "When given a negative number, the function will recurse again and again, passing itself an ever more negative number, thus getting further and further away from returning a result. It will eventually run out of stack space and abort." So I'm not sure if what I got represents that but my code and console.log outputs is shown below:
let isEven = function(num) {
if (num ===0) {
return true
} else if (num===1){
return false
} else {
return isEven(num-2)
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-2));
// → RangeError: Maximum call stack size exceeded (line 3 in function isEven)```
The question requires that you don't' not to use the modulus operator (%).
// Your code here.
var isEven = function(a){
if (a == 0){ //case 1 : zero is even
return true;
}
else if(a == 1){ //case 2: one is odd
return false;
}
else {
return isEven(Math.abs(a-2)); //solves case 3 (negative numbers)
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ?? ....false
This is the "correct" answer from the website. I say "correct" in quotes because I don't understand the 2nd 'else if' statement's return isEven(-n). Why did the author include the option to turn n into a positive number?
function isEven(n) {
if (n == 0)
return true;
else if (n == 1)
return false;
else if (n < 0)
return isEven(-n);
else
return isEven(n - 2);
}
Anyways, thought I'd share since I didn't see anybody post THIS answer.
//define recursive function isEven takes a positive whole number
//returns true if even
function isEven(x) {
//define innner function to loop over value
function find(current) {
//check if value == 0, return true
if (current == 0) {
return true
//check if value == 1 return false
} else if (current == 1) {
return false
//loop over value, subtracting 2 each time until either 0 or 1
//which returns the approriate true/false value based on evenness
} else {
console.log(current)
return find(current -2)
}
}
return find(x)
}
If the number is 1 or -1 so ODD, the function returns false,
If the number is 0 so EVEN, it returns true,
If then number nor 1,-1 nor 0 we have to first check if the number is positive or negative,
If the number is negative and less than -1 we call the function again but increase the number by 2 until we get -1 or 0;
If the number is positive and greater than 1 we call the function again but decrease the number by 2 until we get 1 or 0;
So for example, the number is 5 ->it`s positive and greater than 1 so call the function over and over again and decrease the number by 2 until the result will be 0 or 1:
5->3->1 //->false
function isEven(num) {
if (num == 1 || num == -1) {
return false;
} else if (num == 0) {
return true;
} else {
if (num < -1) {
return isEven(num + 2);
} else {
return isEven(num - 2);
}
}
}
Test result:
console.log(`-35 is even: ${isEven(-35)}`); //-> false
console.log(`-1 is even: ${isEven(-1)}`); //-> false
console.log(`0 is even: ${isEven(0)}`); //-> true
console.log(`32 is even: ${isEven(32)}`); //-> true
I see quite a few examples above using math functions and modulo operator. But I guess the author expects a simple recursive function to make the reader understand the functioning of the same and how if not properly defined it can lead to repetitive function calls and eventually lead to overflow of stack. I believe this code below can help you understand:
function isEven(n){
if(n==0){
return true;
} else if(n==1){
return false;
} else {
return isEven(n-2);
}
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
function isEven(num){
if(num %2 == 0) {
return true;
} else {
return false;
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
function isEven(number) {
while(number>= -1)
{
return isEven(number-2) == 0 && number>-1 ? true : false;
}
}
console.log(isEven(-1));
I hope this helps:
const evenOrOdd = (N) => {
if (Math.abs(N) === 0) {
return console.log('Even');
} else if (Math.abs(N) === 1) {
return console.log('Odd');
}
evenOrOdd(Math.abs(N) - 2);
};
Google Chrome Console code results:
It utilizes all three given arguments on the problem. It can handle negative integers. It does not use the modulo operator. Lastly, I wasn't able to see any code snippet similar to what I provided thus I am enticed to share what I can.

How to check if a variable is an integer in JavaScript?

How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:
<html>
<head>
<script type="text/javascript">
var data = 22;
alert(NaN(data));
</script>
</head>
</html>
That depends, do you also want to cast strings as potential integers as well?
This will do:
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
With Bitwise operations
Simple parse and check
function isInt(value) {
var x = parseFloat(value);
return !isNaN(value) && (x | 0) === x;
}
Short-circuiting, and saving a parse operation:
function isInt(value) {
if (isNaN(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
Or perhaps both in one shot:
function isInt(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}
Tests:
isInt(42) // true
isInt("42") // true
isInt(4e2) // true
isInt("4e2") // true
isInt(" 1 ") // true
isInt("") // false
isInt(" ") // false
isInt(42.1) // false
isInt("1a") // false
isInt("4e2a") // false
isInt(null) // false
isInt(undefined) // false
isInt(NaN) // false
Here's the fiddle: http://jsfiddle.net/opfyrqwp/28/
Performance
Testing reveals that the short-circuiting solution has the best performance (ops/sec).
// Short-circuiting, and saving a parse operation
function isInt(value) {
var x;
if (isNaN(value)) {
return false;
}
x = parseFloat(value);
return (x | 0) === x;
}
Here is a benchmark:
http://jsben.ch/#/htLVw
If you fancy a shorter, obtuse form of short circuiting:
function isInt(value) {
var x;
return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x);
}
Of course, I'd suggest letting the minifier take care of that.
Use the === operator (strict equality) as below,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
Number.isInteger() seems to be the way to go.
MDN has also provided the following polyfill for browsers not supporting Number.isInteger(), mainly all versions of IE.
Link to MDN page
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
Assuming you don't know anything about the variable in question, you should take this approach:
if(typeof data === 'number') {
var remainder = (data % 1);
if(remainder === 0) {
// yes, it is an integer
}
else if(isNaN(remainder)) {
// no, data is either: NaN, Infinity, or -Infinity
}
else {
// no, it is a float (still a number though)
}
}
else {
// no way, it is not even a number
}
To put it simply:
if(typeof data==='number' && (data%1)===0) {
// data is an integer
}
You could check if the number has a remainder:
var data = 22;
if(data % 1 === 0){
// yes it's an integer.
}
Mind you, if your input could also be text and you want to check first it is not, then you can check the type first:
var data = 22;
if(typeof data === 'number'){
// yes it is numeric
if(data % 1 === 0){
// yes it's an integer.
}
}
You can use a simple regular expression:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
In ES6 2 new methods are added for Number Object.
In it Number.isInteger() method returns true if the argument is an integer, otherwise returns false.
Important Note: The method will also return true for floating point numbers that can be represented as integer. Eg: 5.0 (as it is exactly equal to 5 )
Example usage :
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(99999999999999999999999); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(NaN); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger('10'); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Number.isInteger(5.0); // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true
First off, NaN is a "number" (yes I know it's weird, just roll with it), and not a "function".
You need to check both if the type of the variable is a number, and to check for integer I would use modulus.
alert(typeof data === 'number' && data%1 == 0);
Be careful while using
num % 1
empty string ('') or boolean (true or false) will return as integer. You might not want to do that
false % 1 // true
'' % 1 //true
Number.isInteger(data)
Number.isInteger(22); //true
Number.isInteger(22.2); //false
Number.isInteger('22'); //false
build in function in the browser. Dosnt support older browsers
Alternatives:
Math.round(num)=== num
However, Math.round() also will fail for empty string and boolean
To check if integer like poster wants:
if (+data===parseInt(data)) {return true} else {return false}
notice + in front of data (converts string to number), and === for exact.
Here are examples:
data=10
+data===parseInt(data)
true
data="10"
+data===parseInt(data)
true
data="10.2"
+data===parseInt(data)
false
The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:
function isInteger(x) { return (x^0) === x; }
The following solution would also work, although not as elegant as the one above:
function isInteger(x) { return Math.round(x) === x; }
Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.
Or alternatively:
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }
One fairly common incorrect solution is the following:
function isInteger(x) { return parseInt(x, 10) === x; }
While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:
> String(1000000000000000000000)
'1e+21'
> parseInt(1000000000000000000000, 10)
1
> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false
Why hasnt anyone mentioned Number.isInteger() ?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Works perfectly for me and solves the issue with the NaN beginning a number.
if(Number.isInteger(Number(data))){
//-----
}
Check if the variable is equal to that same variable rounded to an integer, like this:
if(Math.round(data) != data) {
alert("Variable is not an integer!");
}
ECMA-262 6.0 (ES6) standard include Number.isInteger function.
In order to add support for old browser I highly recommend using strong and community supported solution from:
https://github.com/paulmillr/es6-shim
which is pure ES6 JS polyfills library.
Note that this lib require es5-shim, just follow README.md.
The Accepted answer not worked for me as i needed to check for int/float and alphabet. so try this at will work for both int/float and alphabet check
function is_int(value){
if( (parseInt(value) % 1 === 0 )){
return true;
}else{
return false;
}
}
usage
is_int(44); // true
is_int("44"); // true
is_int(44.55); // true
is_int("44.55"); // true
is_int("aaa"); // false
You could use this function:
function isInteger(value) {
return (value == parseInt(value));
}
It will return true even if the value is a string containing an integer value.
So, the results will be:
alert(isInteger(1)); // true
alert(isInteger(1.2)); // false
alert(isInteger("1")); // true
alert(isInteger("1.2")); // false
alert(isInteger("abc")); // false
Use the | operator:
(5.3 | 0) === 5.3 // => false
(5.0 | 0) === 5.0 // => true
So, a test function might look like this:
var isInteger = function (value) {
if (typeof value !== 'number') {
return false;
}
if ((value | 0) !== value) {
return false;
}
return true;
};
Number.isInteger() is the best way if your browser support it, if not, I think there are so many ways to go:
function isInt1(value){
return (value^0) === value
}
or:
function isInt2(value){
return (typeof value === 'number') && (value % 1 === 0);
}
or:
function isInt3(value){
return parseInt(value, 10) === value;
}
or:
function isInt4(value){
return Math.round(value) === value;
}
now we can test the results:
var value = 1
isInt1(value) // return true
isInt2(value) // return true
isInt3(value) // return true
isInt4(value) // return true
var value = 1.1
isInt1(value) // return false
isInt2(value) // return false
isInt3(value) // return false
isInt4(value) // return false
var value = 1000000000000000000
isInt1(value) // return false
isInt2(value) // return true
isInt3(value) // return false
isInt4(value) // return true
var value = undefined
isInt1(value) // return false
isInt2(value) // return false
isInt3(value) // return false
isInt4(value) // return false
var value = '1' //number as string
isInt1(value) // return false
isInt2(value) // return false
isInt3(value) // return false
isInt4(value) // return false
So, all of these methods are works, but when the number is very big, parseInt and ^ operator would not works well.
You could tryNumber.isInteger(Number(value)) if value might be an integer in string form e.g var value = "23" and you want this to evaluate to true. Avoid trying Number.isInteger(parseInt(value)) because this won't always return the correct value. e.g if var value = "23abc" and you use the parseInt implementation, it would still return true.
But if you want strictly integer values then probably Number.isInteger(value) should do the trick.
var x = 1.5;
if(!isNaN(x)){
console.log('Number');
if(x % 1 == 0){
console.log('Integer');
}
}else {
console.log('not a number');
}
What about large integers (bigint)?
Most of these answers fail on large integers (253 and larger): Bitwise tests(e.g. (x | 0) === x), testing typeof x === 'number', regular int functions (e.g. parseInt), regular arithmetics fail on large integers. This can be resolved by using BigInt.
I've compiled several answers into one snippet to show the results. Most outright fail with large integers, while others work, except when passed the type BigInt (e.g. 1n). I've not included duplicate answers and have also left out any answers that allow decimals or don't attempt to test type)
// these all fail
n = 1000000000000000000000000000000
b = 1n
// These all fail on large integers
//https://stackoverflow.com/a/14636652/3600709
console.log('fail',1,n === parseInt(n, 10))
//https://stackoverflow.com/a/14794066/3600709
console.log('fail',2,!isNaN(n) && parseInt(Number(n)) == n && !isNaN(parseInt(n, 10)))
console.log('fail',2,!isNaN(n) && (parseFloat(n) | 0) === parseFloat(n))
console.log('fail',2,!isNaN(n) && (function(x) { return (x | 0) === x; })(parseFloat(n)))
//https://stackoverflow.com/a/21742529/3600709
console.log('fail',3,n == ~~n)
//https://stackoverflow.com/a/28211631/3600709
console.log('fail',4,!isNaN(n) && parseInt(n) == parseFloat(n))
//https://stackoverflow.com/a/41854178/3600709
console.log('fail',5,String(parseInt(n, 10)) === String(n))
// These ones work for integers, but not BigInt types (e.g. 1n)
//https://stackoverflow.com/a/14636725/3600709
console.log('partial',1,typeof n==='number' && (n%1)===0) // this one works
console.log('partial',1,typeof b==='number' && (b%1)===0) // this one fails
//https://stackoverflow.com/a/27424770/3600709
console.log('partial',2,Number.isInteger(n)) // this one works
console.log('partial',2,Number.isInteger(b)) // this one fails
//https://stackoverflow.com/a/14636638/3600709
console.log('partial',3,n % 1 === 0)
console.log('partial',3,b % 1 === 0) // gives uncaught type on BigInt
Checking type
If you actually want to test the incoming value's type to ensure it's an integer, use this instead:
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(''))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt([]))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(true))
console.log(isInt(NaN))
console.log(isInt('1'))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
Without checking type
If you don't care if the incoming type is actually boolean, string, etc. converted into a number, then just use the following:
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(NaN))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
// gets converted to number
console.log(isInt(''))
console.log(isInt([]))
console.log(isInt(true))
console.log(isInt('1'))
My approach:
a >= 1e+21 → Only pass for very large numbers. This will cover all cases for sure, unlike other solutions which has been provided in this discussion.
a === (a|0) → if the given function's argument is exactly the same (===) as the bitwise-transformed value, it means that the argument is an integer.
a|0 → return 0 for any value of a that isn't a number, and if a is indeed a number, it will strip away anything after the decimal point, so 1.0001 will become 1
const isInteger = n => n >= 1e+21 ? true : n === (n|0);
// tests:
[
[1, true],
[1000000000000000000000, true],
[4e2, true],
[Infinity, true],
[1.0, true],
[1.0000000000001, false],
[0.1, false],
["0", false],
["1", false],
["1.1", false],
[NaN, false],
[[], false],
[{}, false],
[true, false],
[false, false],
[null, false],
[undefined, false],
].forEach(([test, expected]) =>
console.log(
isInteger(test) === expected,
typeof test,
test
)
)
Besides, Number.isInteger(). Maybe Number.isSafeInteger() is another option here by using the ES6-specified.
To polyfill Number.isSafeInteger(..) in pre-ES6 browsers:
Number.isSafeInteger = Number.isSafeInteger || function(num) {
return typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num &&
Math.abs( num ) <= Number.MAX_SAFE_INTEGER;
};
you can also try it this way
var data = 22;
if (Number.isInteger(data)) {
console.log("integer");
}else{
console.log("not an integer");
}
or
if (data === parseInt(data, 10)){
console.log("integer");
}else{
console.log("not an integer");
}
Just try this:
let number = 5;
if (Number.isInteger(number)) {
//do something
}
The 'accepted' answer is wrong (as some comments below point out).
this modification can make it work:
if (data.toString() === parseInt(data, 10).toString())
alert("data is a valid integer")
else
alert("data is not a valid integer")
You can use regexp for this:
function isInteger(n) {
return (typeof n == 'number' && /^-?\d+$/.test(n+''));
}
From http://www.toptal.com/javascript/interview-questions:
function isInteger(x) { return (x^0) === x; }
Found it to be the best way to do this.
function isInteger(argument) { return argument == ~~argument; }
Usage:
isInteger(1); // true<br>
isInteger(0.1); // false<br>
isInteger("1"); // true<br>
isInteger("0.1"); // false<br>
or:
function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }
Usage:
isInteger(1); // true<br>
isInteger(0.1); // false<br>
isInteger("1"); // false<br>
isInteger("0.1"); // false<br>

Categories