employing arrays in JavaScript

Hello there! I am new to programming and recently started learning JavaScript. I am working on a simple program where the user can select a name from a list of candidates and then choose a category to receive information about that candidate. However, the code I have written doesn't seem to be working properly, and I'm struggling to figure out why. Any assistance or guidance would be greatly appreciated. Thank you!

<html>
<head> 
<title>candidate-database</title>
<script type="text/javascript"> 
//<!CDATA[ 

//storing data about the applicants
  applicantName= new array ("Joe","Sarah", "Roger", "Mike"); 
  applicantCategory= new array ("University","Year","SAT","GPA"); 
  applicantInfo= new array ( 
  new array ("Stanford","Senior","2250","3.6"), 
  new array ("UC Berkeley","Junior","2100","3.9"),
  new array ("MIT","Junior","2200","3.3"), 
  new array ("Carnegie Mellon","Sophomore","2150","3.4") 
     ); 

   //this function evaluates the data provided 

     function getInfo (){ 
     var theApplicant=" "; 
     var menuA="Please choose an applicant by typing a number\n";
         menuA+="0)Joe\n"; 
         menuA+="1)Sarah\n"; 
         menuA+="2)Roger\n"; 
         menuA+="3)Mike\n"; 

         theApplicant=prompt(menuA); 
         return theApplicant; 

         var theCategory=" "; 
         var menuB="Please Choose a category by typing a number\n"; 
            menuB+="0)University\n"; 
            menuB+="1)Year\n"; 
            menuB+="2)SAT\n"; 
         menuB+="3)GPA\n"; 

     theCategory=prompt(menuB); 
     return theCategory;
      }//end function 

     //the main code evaluates the result and displays the correct info to the user 

      function main () { 
      var output=" "; 
      var name=getInfo() 
      var category=getInfo() 
      var result=applicantInfo [name] [category]; 

      output="The database related to" +applicantName; 
      output+="listens to" +result+ "in that specific category."; 

      alert(output);
      }//end main

      </script> 
      </head>
      <body> 
      </body> 
      </html>

Answer №1

The reason for the error is that your function contains two return statements. It is recommended to have separate functions for each return statement.

function getApplicant(){ 
 var theApplicant=" "; 
 var menuA="Please choose an applicant by typing a number\n";
     menuA+="0)Joe\n"; 
     menuA+="1)Sarah\n"; 
     menuA+="2)Roger\n"; 
     menuA+="3)Mike\n"; 

     theApplicant=prompt(menuA); 
     return theApplicant; 
    }
 function getCategory(){ 
     var theCategory=" "; 
     var menuB="Please Choose a category by typing a number\n"; 
        menuB+="0)University\n"; 
        menuB+="1)Year\n"; 
        menuB+="2)SAT\n"; 
     menuB+="3)GPA\n"; 

 theCategory=prompt(menuB); 
 return theCategory;
  }

 //main code evaluates the result, and returns the correct info to the user 

  function main () { 
  var output=" "; 
  var name=getApplicant(); 
  var category=getCategory() ;
  var result=applicantInfo [name] [category]; 

  output="The database belonging to" +applicantName; 
  output+="registers" +result+ "in that category."; 

  alert(output);
  }//end main

You can also define an array like this:

applicantName = ['A','B','C'];

or

applicantName  = new Array('A','B','C');

Answer №2

After thorough experimentation, I successfully resolved the issue at hand.

A crucial detail to note when working with Javascript arrays is that they are case-sensitive. Therefore, the accurate code should be as follows:

  var applicantName = new Array ("Joe","Sarah", "Roger", "Mike"); 
  var applicantCategory= new Array ("University","Year","SAT","GPA"); 
  var applicantInfo= new Array ( 
  new Array ("Stanford","Senior","2250","3.6"), 
  new Array ("UC Berkeley","Junior","2100","3.9"),
  new Array ("MIT","Junior","2200","3.3"), 
  new Array ("Carnegie Mellon","Sophomore","2150","3.4") 
     ); 

It is essential to remember that 'Array' in this context is indeed case sensitive. Additionally, it might be beneficial to utilize Firefox's debugging tools for further assistance.

Another issue that needs attention is ensuring that your code gets initiated. You can achieve this by including the following line within your body tag:

<body onload = "main()"> 

This modification ensures that the JavaScript you have developed actually begins execution.

I trust this information proves helpful in resolving your concerns!

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 JQuery's .Toggle function in conjunction with a stylish CSS transform button

I am trying to create a toggle menu that shows and hides itself without requiring the button to be clicked twice. I have added e.preventDefault(); which solves the issue, but now the button does not transform as intended. $(document).ready(function() { ...

Exploring the synergy between C++ stacks and multidimensional arrays

Developing a project that simulates a linked list using 2D arrays for stacks has been my recent focus. While I have the code implementation ready, I am struggling with how to effectively incorporate random numbers into the simulation. Despite searching o ...

Leveraging jQuery event listeners within a Javascript class initialization

Recently delving into OOP in JavaScript, I've been revamping some of my old code to make it more reusable. Instead of leaving them as inline scripts, I decided to encapsulate them within JavaScript classes. Here is an example of one of my classes: ...

What is the best way to access the URLs of files within a Google Drive folder within a React application?

I've been working on a react app that's relatively straightforward, but I plan to add a gallery feature in the future. To keep things simple for the 'owner' when updating the gallery without implementing a CMS, I decided to experiment ...

Issue with parsing Mongoose response accurately

I'm fairly new to working with mongoose and have been struggling to find a solution to my current issue. My goal is to query my MongoDB database (hosted on mlab) and pass an object literal to the front end template. I am using hoganjs for templating ...

Occasionally, a loading gif appears after a vanilla JS/AJAX call, but the output

While using AJAX to retrieve JSON data containing information on the next steps, I am implementing a CSS class hide/show to toggle images/wrapper and loading .png image. However, even after toggling show/hide on the image, updating the image src, and addi ...

Error occurred during Apple Login using Next_Auth: OAuthCallback issue

Attempting to log in with Apple using NextAuth. Authentication is successful, but it redirects to /?error=OAuthCallback. The URL being used is: https://appleid.apple.com/auth/authorize?client_id=com.wheeleasy.org&scope=name%20email&response_type= ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

Mastering the art of incorporating background image transitions and creating a seamless slider for navigation

Is there a way to create a navigation menu like the one on this theme? On this theme, when you hover over a menu item, the background image smoothly moves left or right to the item you are hovering on. If anyone knows of plugins that can achieve this eff ...

Is there a way to efficiently return an array of object and nested object keys with their full paths through recursion

My grasp of JS is still in its early stages, so understanding how the stack and recursion function can be challenging for me at this point. The task at hand involves displaying an array of object keys, including the parent object name if the object is nest ...

How can we avoid repeated evaluations by using memoization in a function?

Currently, I am working on a jQuery function designed to switch HTML elements based on specific viewports. The concept is quite simple: <div data-swap-for="#element" data-swap-on="phone"></div> This code snippet will insert the element with t ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

Is the ID "nodeName" specifically designated as reserved in the HTML5 language specifications?

I have an element with the following id: <span id="nodeName"></span> In my HTML code. Then, when using jQuery to do the following: $("#nodeName").html("someString"); I am getting an error in the console that says: Uncaught TypeError: Objec ...

Retrieve the link of a nearby element

My goal is to create a userscript that has the following functionalities: Add a checkbox next to each hyperlink When the checkbox is clicked, change the state of the corresponding hyperlink to "visited" by changing its color from blue to violet. However ...

Show a decimal value as an integer in Razor

Looking for assistance with razor code: @Html.DisplayFor(model => item.sepordan_melk_foroshes.ghamat_total) The current output is: 123.00 How can I remove the decimal and display it like this?: 123 Any help with this would be greatly appreciated. ...

Pass an image into an input field with the attribute type="filename" using JavaScript directly

My goal is to automate the process of uploading images by passing files directly to an input type="filename" control element using JavaScript. This way, I can avoid manually clicking [browse] and searching for a file in the BROWSE FOR FILES dialog. The re ...

The error message "Unexpected token" occurs when using async function prefix in TypeScript

Encountering an 'Unexpected token' issue in typescript while attempting to create an async function: async function test() { ... } Investigated the possibility of this error being caused by running an outdated version of node that doesn' ...

Having trouble loading CSS in an express view with a router

I am encountering an issue where I am unable to load my CSS into a view that is being rendered from a Router. The CSS loads perfectly fine for a view rendered from app.js at the root of the project directory. Below is my current directory structure, node_ ...

Is anyone else experiencing differences in the appearance of my mega menu between Safari, Firefox, and Chrome? It seems like

When viewing in Safari, the text overlaps for some reason. It works fine on Firefox and Chrome. Here's a screenshot of the issue: Safari: https://i.stack.imgur.com/hf7v2.png Firefox: https://i.stack.imgur.com/NrOOe.png Please use Safari to test th ...

Discover if a specific string is present within a given array

I am looking for a way to determine if the term 'Computer Science' exists within an array that contains values such as 'Computer Application' and 'Computer Science'. Array ( [0] => Computer Application [1] => ...