What is the method for updating the value of a character using a function in JavaScript?

I'm currently working on a function that is designed to take in a character and output a corresponding digit.

Below is the code I have written:

function getNumber(char)  {
  if (char == "A"||"a") {
    return char = 5
  } else if (char == "B"||"b") {
    return char = 4
  } else if (char == "C"||"c") {
     return char = 3
  } else if (char == "D"||"d") {
     return char = 2
  } else if (char == "F"||"f") {
     return char = 0
  }
}

However, when testing it with different characters, it always seems to give me a 5 as the output.

Can anyone provide assistance or guidance?

Answer №1

Each condition test must be self-sufficient and complete. While char == "A" qualifies, "a" does not meet the criteria. The incorporation of logical operators such as && and || does not alter this rule.

Furthermore, when returning a value, do so without assignment.

The corrected code should resemble:

function get (char)  {
  if (char == "A"|| char == "a") {
    return 5;
  } else if (char == "B"|| char == "b") {
    return 4;
  } else if (char == "C"|| char == "c") {
     return 3;
  } else if (char == "D"|| char == "d") {
     return 2;
  } else if (char == "F"|| char == "f") {
     return 0;
  }
}

console.log(get("A"));
console.log(get("b"));
console.log(get("C"));
console.log(get("d"));
console.log(get("f"));

To simplify the process, it is recommended to convert the input to either uppercase or lowercase before testing. This way, you only need to assess the string and not the case sensitivity:

function get (char)  {
  char = char.toLowerCase();
  if (char == "a") {
    return 5;
  } else if (char == "b") {
    return 4;
  } else if (char == "c") {
     return 3;
  } else if (char == "d") {
     return 2;
  } else if (char == "f") {
     return 0;
  }
}

console.log(get("A"));
console.log(get("b"));
console.log(get("C"));
console.log(get("d"));
console.log(get("f"));

Alternatively, for a more concise approach that eliminates the need for if/then statements altogether, you can directly return the index position of the match in an array.

let scores = ["f","","d","c","b","a"];
function get (char)  {
  return scores.indexOf(char.toLowerCase());
}

console.log(get("A"));
console.log(get("b"));
console.log(get("C"));
console.log(get("d"));
console.log(get("f"));

Answer №2

drawn from the insights of Scott Marcus
(a slight "correction" was made)

check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

const scores = ['f','','d','c','b','a']

delete(scores[1])  // minor correction based on Scott Marcus' response

const get=char=>scores.indexOf(char.toLowerCase())

console.log('A ->',get('A'));  // 5
console.log('b ->',get('b'));  // 4
console.log('C ->',get('C'));  // 3
console.log('d ->',get('d'));  // 2
console.log('f ->',get('f'));  // 0

console.log('empty string ->',get(''));  // -1 (the original code by Scott Marcus gives 1)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {min-height:100% !important; top:0;}

Answer №3

To achieve the desired outcome, you can utilize the following code snippet to extract numbers by using parseFloat/parseInt:

function get (character) {
if (character == "A"||character=="a")
    return 5
else if (character == "B"||character=="b")
    return 4
else if (character == "C"||character=="c")
    return 3
else if (character == "D"||character=="d")
    return 2
else if (character == "F"||character=="f")
    return 0
else
    return -1
}

Answer №4

 function convertGradeToNumber (grade)  {
  if (grade == "A"|| grade == "a") {
    return grade = 5
  } else if (grade == "B"|| grade =="b") {
    return grade = 4
  } else if (grade == "C"|| grade =="c") {
     return grade = 3
  } else if (grade == "D"|| grade == "d") {
     return grade = 2
  } else if (grade == "F"|| grade == "f") {
     return grade = 0
  }

  return grade;
}

I encountered a similar issue while playing paperio 3

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

Merge multiple list groups into one with a single active selection using Bootstrap List group functionality

Currently, I am experimenting with merging Bootstrap's accordion and list group with JS behavior. My goal is to create a set of list groups where only one option can be active at a time within each accordion. <link rel="stylesheet" href="https:/ ...

What is the best way to modify values within arrays of objects in JavaScript?

I need to update the values in an array of objects. The keys 1 and 2 are dynamic and pulled from a JSON file. var rows = [ { "1": "14", "2": "55", "named": "name1", "row&quo ...

Manipulating graphics with CSS - dynamically linking Divs

I'm attempting to create a unique design by connecting a series of dynamically generated content divs with CSS. The goal is to have a curved line every three divs, complete with an arrow image at the end and an additional line to separate the contents ...

What is the process for accomplishing a Node.js redirection with an HTTP POST request?

I have set up app.js to route all requests to my controller.js. Here is an example of what my controller.js code looks like. router.all('/Controller/:id', controller); function controller(req, res){ // Check database using the ID in the URL ...

When the previous textbox is filled, the cursor will automatically move to the button

Utilizing an RFID reader where students tap their ID to display basic info, a hidden button on the form opens a modal with various purposes for selection. The challenge is shifting focus of cursor to the button and automatically clicking it when the last ...

Choose an HTML <select> element and its <option> based on the presence of a specific string within its value

<select id='mySelect'> <option value='FirstOption'> Option 1 </option> <option value='SecondOption'> Option 2 </option> </select> I am attempting to automatically select the second option b ...

React Native application crashes when the user presses the input field

How can I fix the issue where pressing input text for 3 seconds displays the message "Application name is stopped"?........................................................................................... https://i.sstatic.net/a0Ym8.jpg Here is my compo ...

Locate the initial ancestor element that contains a specific child element on the first level

Looking to retrieve the primary parent element of a selected item that contains a checkbox as a direct child. HTML $('input[type="checkbox"]').change(function(e) { $(this) .parent() .parents("li:has(input[type='checkbox'] ...

NextAuth - simulating the login process of OneLogin

I've been working on setting up a local OneLogin mocked service using WireMock. Everything has been going smoothly so far, as I was able to mock most of the OAuth OneLogin flow. However, I'm facing an issue with the last part that is preventing i ...

I need assistance in testing the component with the react query library as it requires a query client

I am encountering a specific issue while adding tests and need help to resolve it. I want to know how to set the query client inside the register page itself. Register.jsx --- Main page for user registration where I am attempting DOM testing. /* eslint ...

Field for Entering Time

I need help creating a form that will only accept time values formatted as HH:MM. Can someone guide me on how to filter user input and display the colon in the text field? I am thinking that I might need a specialized input box for this purpose. ...

Exploring Angular's ng-transclude directive within a repeat loop

Recently, I began delving into AngularJS and attempted to create a custom table directive with multiple slots for transclusion. However, I encountered an issue where the scope was not being passed to the transclude. Although there are various solutions ava ...

Navigate through intricate nested JSON array structures in JavaScript

nested json structure Json Tree Structure: { "id": "30080", "dataelements": { "Name": "abc" }, "children": [ { "id": "33024", "dataelements": { "Name": "a" }, "children": [ { "id": "33024", ...

Tips for resetting and configuring timer feature?

A feature in my quiz app requires setting up a timer in the controller that counts for 30 seconds and stops the quiz if there is no activity within that time frame. The timer should reset and start counting again if there is any activity. I have implemente ...

How can I reverse the names displayed in ng-repeat when I click?

When utilizing the orderby filter in angularjs, I want to be able to sort the data only when the button is clicked. If the button is not clicked, the sorting order should not be displayed. <tr ng-repeat="tools in toolsfilter | orderBy:orderByField:reve ...

Guide on transferring the content of a div to the beginning of a file

I am using a function xy to include PHP code in my document: go.php <?php $file_data = '?'; $file_data .= file_get_contents('xml.xml'); file_put_contents('xml.xml', $file_data); ?> ")} HTML <div id="content"con ...

Acquiring the assigned class attribute

I have an image that triggers ajax requests when clicked. To pass a variable from $_GET[] to my onclick function, I came up with the following solution: <img id="img1" class="<?=$_GET['value']"?> /> and using jQue ...

The function res.map() cannot be used in this context because res is an Array Object

I am dealing with data in the following format: [ { device_id: '12335', timestamp: '2018-05-14T08:31:23.000Z', temperature: 21, pressure: 31, humidity: 20, equipment_name: 'truck5' }, { device_id: &apo ...

I am looking to transmit a JWT token to my backend using next-auth

In my current project using Next.js, I have implemented authentication with next-auth. This project follows the MERN stack architecture. I am facing an issue where I need to retrieve the JWT token and send it to my backend server using next-auth along wit ...

JavaScript code to automatically pause/play HTML5 videos when scrolling

I'm working on creating a video gallery using HTML5 and JS. I've managed to set it up so that you can scroll horizontally between autoplaying muted HTML5 videos, and the videos play or pause when scrolled into or out of view. Everything is functi ...