The Randomizer consistently yields the initial value each time

My mom works as a teacher, and I planned to surprise her with a random student picker for her 2nd-grade class. However, there seems to be an issue as it always selects the same student - Daniel. Despite setting up logging for the random numbers generated, I can't seem to figure out why Daniel is consistently chosen even when the random number doesn't correspond to his selection. What seemed like a simple task has turned into a puzzling problem. For context, my mother teaches in Denver where there is a diverse range of names among the 26 students in her class.

function studPick() {  
  var random = Math.random() * 100 / 3.84615384615;  

  var rand = Math.ceil(random*1)/1;
  console.log("rand = " + rand + ".");
  let student = "";
  if (rand === 1) {
    student = "Daniel";
  }
  else if (rand === 2) {
    student = "Judge";
  }
  else if (rand === 3)
  {
    student = "Jonathan";
  }
  ...
  // Code for other student names omitted for brevity
  ...
  else if (rand === 26) {
    student = "Stella"
  }
  else {
    alert("An error has occurred");
  }
  alert("Randomly picked student: " + student + ".")
}

Edit: I suspect that I may be redefining variables causing the issue. I will investigate further and remove this question if that resolves the problem.

Answer №1

The primary error you are making is confusing = with ==. Using rand = 8 assigns the value of 1 to the variable rand, whereas you should be using rand == 8 to check if rand equals 8.

Your code could be simplified and made more efficient by utilizing arrays:

var students = ["Emily", "Michael", "Sara"];
var randomStudentIndex = Math.floor(Math.random() * students.length);
var student = students[randomStudentIndex];

(It's worth noting that JavaScript also has a strict equality operator === which can be safer to use over == in certain situations. It's advisable to understand the differences between them before implementing either.)

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

Retrieve all files from a directory that include a specific string, store the file names in an array, and then return the array using

Exploring a new challenge, I am attempting to scan a specific directory for files that contain a particular string in their contents and compile a list of their names. Here is the code snippet I have developed up to this point: const dirname = path.res ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

Top recommendation: Utilizing Typescript to allow a customer to enhance an application using their own tailored code

Our application framework is built on Angular 9, providing customers the ability to customize applications with different fields and layouts. This functionality works smoothly. However, we now face a situation where a customer wants to incorporate special ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

Scanner (IE5) impact on page load speeds

I have developed an MVC project which is designed as a single-page application (SPA) utilizing knockoutjs and sammy frameworks. The following script is placed in the head section of the page: <script> var startTime = (new Date()).getTime(); </ ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...

Utilize JavaScript to extract information from an HTTP Response and insert both values into a <div> element

As a novice in Javascript, I am currently grappling with the task of extracting two specific cell values from an HTTP Response provided by the Google Sheets API and inserting them into separate HTML Div elements. I am struggling with modifying my code to e ...

Combine div elements with identical class

Is there a way to utilize jQuery in order to enclose groups of elements with the same class within a div? I have been searching for a solution, but haven't found one yet. Here's an example of the HTML: <div class="view-content"> < ...

How do I assign a variable to a session in Express.js?

I am currently working on a login form that prompts users to enter their username, password, and company name. The company name corresponds to the database name, so I need to store this information in the session during the login post request. In my opini ...

Converting Integers to Integers in Javascript: A Step-by-Step

Let's say I have a Method written in JavaScript in GWT(JSNI) which accepts the wrapper data type Integer and I need to convert it into a Primitive Data type inside JS. public static native void nativeMethod(Integer index)/*-{ // What is the best ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

Utilizing Three.js Texture with shaderMaterial

I'm encountering an issue where I can't seem to load a texture onto my shader material, resulting in just black dots appearing. Here's the code snippet from my shader.js: THREE.ShaderLib['cloud'] = { uniforms: { textu ...

What are the steps for implementing timezone-js?

I found a project on GitHub that claims to convert one timezone to another. I've been trying to get it to work without success. After downloading and extracting the files, I created an HTML file with the following code: <html xmlns="http://www.w3. ...

A guide to showing the value of a selected checkbox in Vue.js

Here is a link to the reference: https://jsfiddle.net/8xom729c/ <div class="checkbox-alignment-form-filter"> <input type="checkbox" id="HR 3502 : 2004" class="vh-product" value="HR 3502 : 2004" v-model="checkboxestwo[0]" v-on:click="checkAllt ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Encountering a build time issue while incorporating Redis into Next.js

Incorporating Redis into my Next.js project has been beneficial overall. However, during the build process (next build), an error arises when it attempts to connect to Redis, resulting in the following message: Collecting page data ..[ioredis] Unhandled e ...