Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to handle invalid argument in JavaScript

4 Answers

0 votes
function processNumber(num) {
    if (typeof num !== 'number' || num < 0) {
        console.error("Invalid input: Must be a positive number.");
        return;
    }
    
    console.log("input ok:", num);
}

processNumber(3);  
processNumber(-7); 



/*
run:

input ok: 3
Invalid input: Must be a positive number.

*/

 



answered May 20, 2025 by avibootz
0 votes
function divide(a, b) {
    if (b === 0) throw new Error("Division by zero is not allowed.");
    return a / b;
}

try {
    console.log(divide(5, 0));
} catch (error) {
    console.error("Error:", error.message);
}



/*
run:

ERROR!
Error: Division by zero is not allowed.

*/

 



answered May 20, 2025 by avibootz
0 votes
function say(name) {
    name = name || "Guest"; // Default to "Guest" if falsy
    console.log("Hello, " + name + "!");
}

say(); 
say("Bob"); 



/*
run:

Hello, Guest!
Hello, Bob!

*/

 



answered May 20, 2025 by avibootz
0 votes
function addNumbers(a, b) {
    if (typeof a !== "number" || typeof b !== "number") {
        throw new TypeError("Both arguments must be numbers.");
    }
    return a + b;
}

console.log(addNumbers(6, "abc")); // Throws TypeError



/*
run:

ERROR!
main.js:3
        throw new TypeError("Both arguments must be numbers.");
        ^

TypeError: Both arguments must be numbers.
    at addNumbers (main.js:3:15)

*/

 



answered May 20, 2025 by avibootz

Related questions

4 answers 217 views
4 answers 241 views
4 answers 194 views
4 answers 200 views
3 answers 175 views
3 answers 174 views
...