What is the proper way to incorporate this if statement into a function?

I need assistance with converting the provided if else code into a function. The main goal is to transfer the arrays from local scope to global scope. However, whenever I attempt to enclose the code within a function, I encounter a reference error stating "code is not defined". It's evident that I must figure out a way to return these arrays from the local scope to the global scope.


if (randomnum == 1) {
    var codes = ["qjyreu", "achin", "eralnrde", "hiwel", "eW", "ni"];
    var words = ["jquery", "china", "learned", "while", "We", "in"];
    var finalAnswer = "Welearnedjquerywhileinchina";
} 
else if (randomnum == 2) {
    var codes = ["oegs", "yob", "nignadc", "hTe", "ightn", "veery"];
    var words = ["goes", "boy", "dancing", "The", "night", "every"];
    var finalAnswer = "Theboygoesdancingeverynight";
}

To provide context, the random number (randomnum) is determined by the rando function:


function rando() {
  return (randomnum = Math.floor(Math.random() * 2) + 1);
}
rando();

Answer №1

function randomWord() {
  var randomNumber = Math.floor(Math.random() * 2) + 1;
  var result, codes, words;

  if (randomNumber == 1) {
      codes = ["qjyreu", "achin", "eralnrde", "hiwel", "eW", "ni"];
      words = ["jquery", "china", "learned", "while", "We", "in"];
      result = "We learned jquery while in china";
    } else if (randomNumber == 2) {
      codes = ["oegs", "yob", "nignadc", "hTe", "ightn", "veery"];
      words = ["goes", "boy", "dancing", "The", "night", "every"];
      result = "The boy goes dancing every night";
    }

  return [result, words, codes];
}

randomWord();

The issue was that the return statement should be outside of the if-else statement block to ensure it is always executed. Also returning an array with all values instead of just the final answer.

Updated Function

If you want to return all values:

function randomWord() {
  var randomNumber = Math.floor(Math.random() * 2) + 1;
  var result, codes, words;
  
  if (randomNumber == 1) {
      codes = ["qjyreu", "achin", "eralnrde", "hiwel", "eW", "ni"];
      words = ["jquery", "china", "learned", "while", "We", "in"];
      result = "We learned jquery while in china";
    } else if (randomNumber == 2) {
      codes = ["oegs", "yob", "nignadc", "hTe", "ightn", "veery"];
      words = ["goes", "boy", "dancing", "The", "night", "every"];
      result = "The boy goes dancing every night";
    }
    
  return [result, words, codes];
}

randomWord();

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

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

Navigate to the following tabindex after submitting the form again

How can I enhance the user experience by allowing them to easily update generic names (name1, name2, name3) with more meaningful ones without being redirected back to the previous name? Look for the comment WHAT GOES HERE? below. Example HTML layout: < ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

What is the best way to have a component in React "wait" for state updates?

Currently, I am using React to develop a battleship game. One issue I encountered is when the component loads and I try to map the board array, React throws an error stating "cannot read property board of undefined". After some debugging with console loggi ...

JavaScript Control for Embedding Facebook Videos (Start / Stop)

I need assistance on how to correctly utilize this API with the code provided in the following URL: https://developers.facebook.com/docs/plugins/embedded-video-player/api/#control-reference https://i.sstatic.net/jQQeN.png window.fbAsyncInit = function() ...

What are some alternative ways to link a local MongoDB database to my Android Studio application instead of using MongoLab?

Can someone please help me figure out how to connect my Android Studio project to a MongoDB database stored locally on my PC? I've been searching for solutions that don't involve using MLab, but I haven't had any luck. I've attempted f ...

What is the best way to include a div element with a dynamic animation on a webpage?

I'm attempting to create a laser beam that can shoot enemies on the screen, much like in classic games such as Space Invaders or Galaga. However, I am encountering difficulties getting the laser to move when I click the button. Below is the code I hav ...

Implementing async and await after making a fetch request

I am in the process of updating my code from using callbacks to utilize async and await. However, I am a bit confused on how to properly implement it within my current setup. The current setup involves: Clicking a button that triggers the clicker functi ...

Creating a Yo Meanjs project seems like an insurmountable challenge

As I embark on this online tutorial journey, I encountered an issue. All the necessary installations and preparations have been completed, but when instructed to run 'yo meanjs', an error message appeared: https://i.sstatic.net/0dCB4.png Could ...

unable to retrieve the value of this.table property within a JavaScript class

In my JavaScript code, I have created a class that generates a MySQL model like so: class Model { constructor(options = {}, table) { this.options = options; this.table = table; this.create(); } create() { let queryString = `INSERT INT ...

Pressing the ENTER key does not submit the text box data in Rails/Bootstrap, but clicking the SUBMIT button does

I need assistance with my Rails 4 and Bootstrap 3 project. I have implemented an email address field on my page (localhost:3000) where users can enter their email and click the SUBMIT button to send it to the MongoDB database. However, pressing the ENTER k ...

Exploring the functionality of scrollTo in React

I'm currently working on developing a carousel feature that should scroll when the user interacts with the navigation buttons. However, despite my efforts, I am facing an issue where the scrolling functionality is not working as expected in my code sn ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Retrieve JSON data from a Postgres table without including field names

Is there a way to convert Postgres table data into JSON without repeating field names in the JSON result? Currently, when using PostgreSQL's json functions, the output looks something like this: [{"id":"1234","name":"XYZ"},....]. However, having all f ...

Determining if an element is present in a JavaScript array and returning true

I've come up with this code so far: var isMatch = viewedUserLikedUsersArray.indexOf(logged_in_user); if (isMatch >=0){ console.log('is match'); } else { console.log('no match'); } When an element is ...

How can I create a floating thumbnail gallery that displays extra content when hovered over? Is there a way to make the hovered thumbnail overlap its neighboring

I am currently working on a gallery of thumbnail images. Each image is accompanied by a title below it: <div class='gallery'> <div class='thumb'> <div class='thumbimage'></div> <div class ...

Tips on creating a search feature with JavaScript and AJAX

I'm currently facing an issue with my search functionality. I have successfully loaded data from a JSON file, but the search feature is not working as expected. I've reviewed my code multiple times and can't identify any mistakes. I believe ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

What distinguishes the memory utilization of these two arrays in JavaScript?

In my array, the elements are indexed consecutively with a gap of 1 between each index. let noGap = []; noGap[0] = 0; noGap[1] = 1; On the other hand, I have a separate array where the indexes are much more spread out. let gap = []; gap[0] = 0; gap[1000 ...