3

Say I'm creating a function to add some numbers together, and I want to verify they are all actually numbers.

I am doing this:

function addNumbers(x, y) {     
    if (typeof x == 'number' || typeof y == 'number') {
        // do something..
    }        
}

It seems unpractical if I had more than two numbers. What would be a better way to check for multiple numbers?

4
  • 1
    Pass them into the function as an array to begin with, so that you can easily loop over it …? Commented Sep 12, 2019 at 9:00
  • did you tried adding like addNumbers(10,11) ? Commented Sep 12, 2019 at 9:01
  • Please also include the inputs, how and where you are storing their values, and how you are calling the addNumbers function with those values. We can help you a lot quicker that way. Commented Sep 12, 2019 at 9:02
  • I'll clarify, i want the addNumbers function to take in any amount of values (for the purpose of learning, not any real application), and if any of them is not a number it will throw an error. So for instance, addNumber(1, 2, 3, 'twenty') Commented Sep 12, 2019 at 9:10

5 Answers 5

3

You can put them in an array and use a Boolean flag to check if all are numbers, using Array.prototype.every (and check for NaNs, because typeof NaN === 'number'):

function addNumbers(...args) {
  var all_numbers = args.every(a => typeof a == 'number' && !isNaN(a));
  if (all_numbers) {
    var sum = 0;
    args.forEach(n => sum += n);
    console.log(sum);
  } else {
    console.log('something is not right!');
  }
}

addNumbers(5, 6);
addNumbers(5, 6.2);
addNumbers(5, 6, NaN);
addNumbers(5, 6, []);
addNumbers(5, 6, {});
addNumbers(5, '6');
addNumbers('5', 6);

Sign up to request clarification or add additional context in comments.

10 Comments

I am not sure how this is solving the problem when there are more than two inputs.
@GhassenLouhaichi Using ...args solves this problem.
try using isNaN instead
also try using "every" instead
also its the best usecase for reduce
|
1

I think its more readable form, use Array.prototype.every, Number.isInteger and Array.prototype.reduce.

I'm not sure what you want to do with errors, so we just logging them (and the result);

// consider floating point
const isNumber = n => typeof n == 'number' && !isNaN(n)

const addNumbers = (...args) => {
  const isValid = args.every(isNumber);
  // const isValid = args.every(Number.isInteger);
  if (!isValid) {
    console.log('Error');
    return;
  }
  const sum = args.reduce((sum, curr) => sum + curr, 0);
  console.log(sum);
  return sum;
}

addNumbers(5, 6);
addNumbers(5, 6, NaN);
addNumbers(5, '6');
addNumbers('5', '6');
addNumbers('5', 6);
addNumbers(5.5, 6);
addNumbers(5.5, 6, 6.4, 65);
addNumbers(5.5, 6, {});

1 Comment

Doesn't work for floating point numbers Number.isInteger(5.2) is false.
1

You can use get your inputs as an array using the ... rest parameter syntax then use Array.prototype.reduce to sum them and while doing so you can convert the elements to numbers using the + operator and add them:

function addNumbers(...nums) {     
    return nums.reduce((sum, num) => sum + +num)
}
console.log(addNumbers(1, 2, "3", 4));

Or if you want to skip the non-numbers (which will produce NaN if you use the first code snippet) just check the type before adding, if number you're good else replace that with a 0:

function addNumbers(...nums) {     
  return nums.reduce((sum, num) => sum + (!(typeof(num) === "number") ? 0 : +num));
}
console.log(addNumbers(1, 2, "3", 4, "non-number"));

2 Comments

What if he want to protect against accidental inclusion of text inputs? Your solution this way returns a NaN.
@GhassenLouhaichi yes, I realized my mistake added a second version
0

You can push all your numbers into and array and run a loop over that array and add them.

let arr = [1,2,3,4]; #be it your array

function addNumbers(arr) {
let sum=0;
arr.map(item => {
if(typeof item === 'number') {
sum=sum+item;
}
else {
return item+' is not a number in given array';
}
return sum;
});

Comments

0

If performance not the issue here:

function testN(){
    if(!Array.from(arguments).every((d)=>typeof d === "number")){
        return;
    }
    console.log("pass");
    //do something;
}

replace "do something" with whatever you want to do. Can use negated "some" method, that'll terminate earlier. Whichever fits you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.