Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditioning a Function (JS)

I’m trying to return a message if one of the argument is not a number. Otherwise continue with the function.
I’m trying this but it’s not working as I’m expecting.. ..Please, any help?

function findingPairs(arr, value){
            if(isNaN(arr) || isNaN(value)){
                return "Please, introduce just numbers" 
            }
            let sum = 0;
            let finalOutput = [];
            for(let i = 0; i < arr.length; i++){
                    let numA = arr[i]
                    console.log(numA)
                } for(let j = 1; j < arr.length; j++){
                    let numB = arr[j]
                    console.log(numB)
                }
            }
        
       findingPairs([1,3,7], 9)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use Number.isInteger to check if something is a number.
And Array.every over the array to check all the array.

Also I’m throwing an Error instead of returning a value because that’s what is expected usually.

Error Docs

function findingPairs(arr, value) {
  if (!arr.every(Number.isInteger) || !Number.isInteger(value)) {
    throw new Error("Please, introduce just numbers");
  }

  let sum = 0;
  let finalOutput = [];

  for (let i = 0; i < arr.length; i++) {
    let numA = arr[i];
    console.log(numA);
  }
  for (let j = 1; j < arr.length; j++) {
    let numB = arr[j];
    console.log(numB);
  }
}

const value = findingPairs([1, 3, 7], 9);
const value2 = findingPairs([1, "a", 7], 9); // Will throw
const value2 = findingPairs([1, 23, 7], "hey"); // Will throw

console.log(value);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading