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

What is the significance of including the *dispatch* variable in the *dependency array* for the useEffect function?

While reviewing the source code of a ReactJS project, I noticed that the dispatch variable is included in the dependency array of the useEffect hook. Typically, I'm familiar with including useState() variables in this context, so I am curious about th ...

"Incorporating a hyperlink into a newly added table row with the help

When utilizing jQuery, I am able to dynamically add rows to a table with each row containing an anchor tag. However, when attempting to populate the anchor tags with links using jQuery, the links do not appear as expected. Strangely enough, the other data ...

Steps for Deactivating Past Dates on JQuery Datepicker1. Open your

I've been working on a custom JQuery Calendar for selecting appointments, with the requirement to disable dates prior to the current date and highlight available dates in an orange color (#f48024). Unfortunately, my attempt using minDate hasn't b ...

Vue.js: The href attribute in a link is different from the data

Having <a> href tag below, clicking will redirect to www.duckduckgo.com, with the value of page.publicWebsite being displayed as well. {{page.publicWebsite}} shows www.duckduckgo.com. Is everything functioning correctly? https://i.stack.imgur.com/ ...

The Jquery ajax get method is malfunctioning

I've been trying out this code but it doesn't seem to be working. Apologies for the basic question, but I'm curious to understand why it's not functioning as expected. $(document).ready(function(){ $("button").click(function(){ ...

Saving MongoDB query results to a file using the built-in Node.js driver

I have been attempting to save the output of a MongoDB query to a file using the native Node.js driver. Below is my code (which I found on this post: Writing files in Node.js): var query = require('./queries.js'); var fs = require('fs' ...

Leveraging XML data encoded into JSON with PHP

I recently developed a PHP file to retrieve data from an API. A typical response from the API would look like this: { @attributes: { Status: "OK" }, Errors: { }, Warnings: { }, RequestedCommand: "checking", CommandResponse: { @attributes: { ...

Can a rotation animation be incorporated into an image in next.js when it is clicked?

Looking to enhance a next.js image with an animation? How about making it rotate 360 degrees upon each click? Despite my attempts at toggling classes, I can't seem to achieve the desired outcome. Any guidance would be greatly appreciated. Thank you in ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Implement two different styles within an element's style properties

Welcome everyone, I have a question regarding adding marquee effects to a table row along with highlighting it. Is it possible to include moving text from left to right in the same active row? For example, let's say that the current time is 12:45 AM. ...

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

Searching for data in Node.js using Mongoose and dates

I'm in search of a way to execute a specific query with mongoose. In my mongodb database, I have data structured like this: "startDateTime" : ISODate("2017-03-22T00:00:00.000Z"), "endDateTime" : ISODate("2017-03-27T00:00:00.000Z"), My goal is to r ...

When using CSS float:left and overflow:visible, the text may get cropped-off at

I'm currently experimenting with creating a color gradient in javascript using numerical values within some of the divs to indicate scale. However, I've run into an issue where as the values get larger, they are cut off due to the float:left prop ...

If the user confirms it with a bootstrap dialog box, they will be redirected to the corresponding links

Firstly, I am not interested in using javascript confirm for this purpose. Please read on. For example, adding an onClick attribute to each link with a function that triggers a system dialog box is not what I want. Instead of the standard system dialog bo ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

"Learn how to dynamically update the user interface in express.js using handlebars without having to refresh the

As a newcomer to using express.js and Handlebars, I am faced with the challenge of implementing autocomplete functionality. Specifically, I want to enable autocompletion in a text input field without triggering a page refresh when users interact with it. C ...

The asynchronous ajax function fails to work properly when setInterval is activated

My issue is that only the initial execution of the updateProgress function happens while waiting for the completion of syncDNS. All subsequent calls made via setInterval remain on hold until syncDNS finishes. Can anyone explain why this is happening? $( ...