• Jobs
  • About Us
  • Jobs
    • Home
    • Jobs
    • Courses and challenges
  • Businesses
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

254
Views
Need to calculate the number of zeros, positive and negative nos in an array using Switch Case in Javascript

I tried the below code, but the switch case isn't working as I expected it to. Can you please tell me where I'm going wrong?

    function counter() {
 //   const arr = prompt("Enter numbers").split(",");
 let arr = [1,2,3,-1,0];
 console.log(arr.length);
    const neg=0, pos=0, zero=0;
    for (var i = 0; i < arr.length; i++) {
        let val = arr[i];
        console.log(val);
        switch (val) {
            case (val === 0):
                zero += 1;
                console.log("zero");
                break;  
            case (val < 0):
                neg += 1;
                console.log("neg");
                break;
            case (val > 0):
                pos += 1;
                console.log("pos");
                break;
            default:
                console.log("not working");
                break;
        }
    }
    document.write("Negatives: " + neg+"<br>");
    document.write("Positives: " + pos+"<br>");
    document.write("Zeroes: " + zero+"<br>");
}
over 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You cannot re-assign a const. Something like this will throw an error:

const num = 0;
num += 1; // Uncaught TypeError: Assignment to constant variable.

Another problem: In your case statements you are using expressions which evaluate to either true or false (the expressions will be evaluated before matching), so you'll have to use switch(true) instead of switch(val):

function counter() {
    // const arr = prompt("Enter numbers").split(",");
    let arr = [1,2,3,-1,0];
    let neg=0, pos=0, zero=0;
    for (var i = 0; i < arr.length; i++) {
        let val = arr[i];
        switch (true) {
            case (val === 0):
                zero += 1;
                console.log("zero");
                break;  
            case (val < 0):
                neg += 1;
                console.log("neg");
                break;
            case (val > 0):
                pos += 1;
                console.log("pos");
                break;
            default:
                console.log("not working");
                break;
        }
    }
    document.write("Negatives: " + neg+"<br>");
    document.write("Positives: " + pos+"<br>");
    document.write("Zeroes: " + zero+"<br>");
}

counter()

over 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Show me some job opportunities
There's an error!