Need help with JS problem solving

Hello everyone,
I’m working on a problem to sharpen my JS skills. The problem is:

  • Write a function called addTwoNumbers that accepts two numeric arguments and returns the sum of those two numbers.

  • If either argument is not a number, return the value of NaN.

My Solution is:

function addTwoNumbers(num1, num2) {
  if (num1 || num2 < 0) {
    return NaN;
  } else {
    return num1 + num2;
console.log(addTwoNumbers(10, 2));

After running the program I only get NaN. My Logic is if either of the numbers is less than 0, then return Nan. Where am I getting wrong?

You are not quite checking correctly to see if the values passed in are numbers.

I would recommend you do a google search for “Javascript check if number”. You should find plenty of help on how to correctly check if both of those values passed in are actually numbers.

if (num1 || num2 < 0) {

This first checks if num1 is “truthy”. So unless num1 is one of the seven “falsy” values, function is always going to return NaN.

1 Like

This condition equals if (num1 === true || num2 < 0), and since num1 is a number and thus truthy, the function returns NaN

Firstly if you want both conditions to be true (if argument is a number) you should use && (and) instead of || (or).
I think your logic keeps you thinking about: if condition of (arr1 or arr2).
As people have mentioned here you should think of : if condition1… and if condition2… return sum else NaN

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.