Tips for utilizing a switch statement

I'm a beginner in JavaScript and recently learned about the switch statement. I have an exercise where I need to convert numbers 1-10 into words like "one", "two", "three"... This is what I have tried so far:

function sayNum(){
    let numberArray = [1,2,3,4,5,6,7,8,9,10]
    let word = '';
    for(let i=0;i<numberArray.length;i++){
        switch(numberArray[i]) {
            case 1:
                word = 'one';
                break;
            case 2:
                word = 'two';
                break;
            case 3:
                word = 'three';
                break;
            case 4:
                word = 'four';
                break;
            case 5:
                word = 'five';
                break;
             case 6:
                word = 'six';
                break;
            case 7:
                word = 'seven';
                break;
            case 8:
                word = 'eight';
                break;
            case 9:
                word = 'nine';
                break;
            case 10:
                word = 'ten';
                break;
        }
    }
    return word;
}
sayNum()

Answer №1

Here is one way to accomplish this task:

function convertNumbersToWords(){
  let numbersArray = [1,2,3,4,5,6,7,8,9,10];
  let resultArray = [];

  for(let i=0;i<numbersArray.length;i++) {
    switch(numbersArray[i]) {
        case 1:
            text = "one";
            break;
        case 2:
            text = "two";
            break;
        case 3:
            text = "three";
            break;
        case 4:
            text = "four";
            break;
        case 5:
            text = "five";
            break;
        case 6:
            text = "six";
            break;
        case 7:
            text = "seven";
            break;
        case 8:
            text = "eight";
            break;
        case 9:
            text = "nine";
            break;
        case 10:
            text = "ten";
            break;
    }

    resultArray.push(text);
  }

  return resultArray;
}

let wordedNumbers = convertNumbersToWords();
console.info(wordedNumbers);

This function will:

  • Add the corresponding textual representations of each number in the source array to a new array
  • Return this array containing the words back to the main program
  • Display the resulting array in the developer console for observation

Answer №2

When using the switch statement, an 'expression' is passed into it for comparison. This expression can be of various types such as string, number, float, boolean, etc. The comparison in a switch statement is strict, meaning it matches exactly. If your code is not working, it's likely due to this reason.

Initially, you were passing an undeclared variable 'numbers' as the switch expression. Instead, you should use the ith element from the nameNumber[i] array like this: switch(nameNumber[i]){ }

Additionally, each case clause should compare values to numbers rather than strings if the switch expression contains numbers. So, instead of case "1":, use case 1: for example.

To learn more about the switch-case statement, visit: Switch Statement

I have made the necessary adjustments to the code below based on the mentioned changes. Feel free to run the modified code snippet to observe the functionality. Best of luck!

function sayNum(){
    let nameNumber = [1,2,3,4,5,6,7,8,9,10]
    let text = '';
    for(let i=0;i<nameNumber.length;i++){
    switch(nameNumber[i]) {
        case 1:
            text = "one";
            break;
        case 2:
            text = "two";
            break;
        case 3:
            text = "three";
            break;
        case 4:
            text='four';
            break;
        case 5:
            text = "five";
            break;
        case 6:
            text = "six";
            break;
        case 7:
            text = "seven";
            break;
        case 8:
            text = "eight";
            break;
        case 9:
            text = "nine";
            break;
        case 10:
            text = "ten";
    }
    console.log(text);
    }
    return text;
}

sayNum();

Answer №3

To avoid using a switch statement, opt for an if statement instead. This is because the break statement can be utilized in a switch to exit out of a loop.

let text = '';

function sayNum() {
  let nameNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  
  
  for (let i = 0; i < nameNumber.length; i++) {
    if(nameNumber[i] == 1){
    text += `"one",`;
    
    }
    if(nameNumber[i] == 2){
      text += `"two",`;
    }
    if(nameNumber[i] == 3){
      text += `"three",`;
    }

    if(nameNumber[i] == 4){
      text += `"four",`;
    }

    if(nameNumber[i] == 5){
      text += `"five",`;
    }

    if(nameNumber[i] == 6){
      text += `"six",`;
    }

    if(nameNumber[i] == 7){
      text += `"seven",`;
    }

    if(nameNumber[i] == 8){
      text += `"eight",`;
    }

    if(nameNumber[i] == 9){
      text += `"nine",`;
    }

    if(nameNumber[i] == 10){
      text += `"ten"`;
    }

    
  }
  
}

sayNum();

console.log(text)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Ajax for Dynamically Filling a Dropdown Menu

My journey into the world of Ajax has led me to a state of confusion and frustration. The task at hand is to populate the first box with customer data from the database, then use the customerID to retrieve all vehicleID's using the select.php script. ...

Position the read more buttons in JavaScript at the bottom of the div

I designed three boxes in this section with content inside. To enhance the functionality, I added a feature that made the boxes smaller. Everything was functioning perfectly, but I encountered an issue with the alignment of the buttons at the bottom. Is th ...

When CSS is modified by inserting an extra div, it causes the positioning of other elements to shift towards

I'm currently working on adapting a method to make elements "sticky" for older browsers as discussed in this particular article. The basic idea involves implementing some JavaScript code that listens for scroll events. Upon detection of such an event ...

Step-by-step guide on integrating a JSON array fetched via Ajax from a Django/Python view with DataTable

Being a new developer, I am embarking on my first professional project using Django. My main challenge lies in loading data that I have extracted from the models.py into a DataTable within my view.py file. Below is the snippet of my code. Brief Overview ...

Error with Ant Design Autocomplete functionality when searching for a number

I am currently using ant design to develop a more advanced autocomplete component that will display data from multiple columns. In this particular scenario, I have two columns named tax_id and legal_name that users can search by. Everything works smoothly ...

Issue: Initialization for aggregate object expected to be in the form of '{...}'

Here is the code snippet that processes the payload[] array and stores its result in the myFinalShellcode[] array. #include <windows.h> #include <stdio.h> unsigned char payload[] = { 0xf0,0xe8,0xc8,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51, ...

Storing information within AngularJS

As a newcomer to the world of coding and Angular, I am currently working on developing a calculator-style web application that includes a rating section in the footer. My main concern revolves around saving data so that it can be accessed by other users. T ...

The heap limit has been reached in Github Actions, causing an allocation failure

Encountering a heap out of memory error in Github Action during the last "run: npm run build". FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory Error: Process completed with exit code 1. Showcasing the workflow file: name: ...

Including an anchor element with a specified URL, alongside passing the URL as a property

Having trouble passing a URL to href using a property. I'm attempting to pass the {props.github} value to href, but it's not working as expected. I've set up a property object with a field called github like this: export const projectList ...

Why is my showMap() function not executing when the button is clicked? How can I resolve this issue in JavaScript?

Why isn't the JavaScript code for showMap() running? How can this issue be resolved? <html> <title></title> <script> function showMap() { alert("rong"); } fun ...

What is the best way to develop a card stack swiper similar to Tinder using React?

After experimenting with various packages, I found that none were satisfactory for creating a customizable card swiper. As a result, I am now considering developing my own solution. What would be the best approach for adding animations, enabling draggable ...

Using Spring MVC and Thymeleaf to dynamically load new HTML pages on ajax calls

Hello there, I'm looking to dive into using thymeleaf for my web application. My goal is to create a simple website with HTML pages. Below is the URL of my landing page controller that returns the index.html page: @RequestMapping("/index") public Str ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Ensuring Node.js backend JavaScript waits for completion of my bash script before proceeding

Running three bash commands through a Node.js code snippet. Here's a portion of the script: exec(str, function(error, stdout, stderr){ console.log('stdout:'+stdout); console.log('stderr:'+stderr); if(error!=null){ ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

Use Javascript to display specific div elements by clicking a button

I could really use some assistance, When I attempt to display the select div by clicking the button, the "id" that PHP generates returns a null response in the console. The requirement is to only show the div when clicking on the "Quick Quote" button. Pro ...

Executing PHP function through AJAX

I have thoroughly researched various resources regarding my issue but still have not been able to find a solution. My goal is to retrieve the result of a PHP function using jQuery AJAX. function fetch_select(){ val_name = $('#name').val(); ...

Identifying whether a child component is enclosed within a specific parent using React

Is there a more elegant and efficient method to determine if the parent of SeminarCard is Slider? Currently, I am passing this information through a prop. The prop value (true/false) is used to provide additional padding. When used independently: <Semi ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...