Having trouble with your if statement in JavaScript?

I am currently working on a menu system using an array and if statements for each option. However, I have encountered an issue where selecting certain options in a specific order does not produce the desired result.

For instance, when adding credit followed by trying to view the current credit, it fails to display the correct information.

Any assistance or suggestions would be greatly appreciated!

Best Regards.

var readlineSync = require('readline-sync')
var currentCredit = 0;
var removeCredit = 0;

menu = [];
menu[0] = "Purchase a product";
menu[1] = "View your credit";
menu[2] = "Add credit";
menu[3] = "Retrieve a refund";

index = readlineSync.keyInSelect(menu, 'Please select an option');

if (index == [1]) {
console.log("Your current credit balance is: £", currentCredit);
index = readlineSync.keyInSelect(menu, 'Please select an option');
}

if (index == [2]) {
var addedCredit = readlineSync.questionInt('How much credit would you like to add? ');
currentCredit += addedCredit;
console.log("Your total credit balance now is: £" + currentCredit);
index = readlineSync.keyInSelect(menu, 'Please select an option');
}

if (index == [3]) {
var removedCredits = readlineSync.questionInt('How much credit do you want to remove? ');
currentCredit -= removedCredits;
console.log("The chosen credits have been removed. Your remaining available credit is: £" + currentCredit);
index = readlineSync.keyInSelect(menu, 'Please select an option');
}

Answer №1

If you're looking to continuously run your script in a loop, consider the following code:

var idx, points, deductions;
while(true) {
    idx = readlineSync.keyInSelect(menu, 'Select an option:');
    
    if (idx == 1) {
        console.log("Your current credit balance is: £", points);
    }

    if (idx == 2) {
        points = readlineSync.questionInt('Enter the amount of credit you want to add: ');
        console.log("Your updated credit balance is: £" + points);
    }

    if (idx == 3) {
        deductions = readlineSync.questionInt('Enter the amount of credit you want to deduct: ');
        console.log("Deductions made. Your remaining credit balance is: £" + (points - deductions));
    }
}

To exit the loop based on a chosen option, modify the code like this:

var idx, points, deductions;
while((idx = readlineSync.keyInSelect(menu, 'Select an option:')) != 4) {
    if (idx == 1) {
        console.log("Your current credit balance is: £", points);
    }

    if (idx == 2) {
        points = readlineSync.questionInt('Enter the amount of credit you want to add: ');
        console.log("Your updated credit balance is: £" + points);
    }

    if (idx == 3) {
        deductions = readlineSync.questionInt('Enter the amount of credit you want to deduct: ');
        console.log("Deductions made. Your remaining credit balance is: £" + (points - deductions));
    }
}

In this scenario, the number 4 serves as the exit option. Also note the use of "loose" equality for comparison since the return type of keyInSelect is not certain.

If you find the previous syntax confusing, here's an alternate version with improved readability:

var idx, points, deductions;
do {
    idx = readlineSync.keyInSelect(menu, 'Select an option:');
    
    switch(idx) {
        case 1:
            console.log("Your current credit balance is: £", points);
            break;

        case 2:
            points = readlineSync.questionInt('Enter the amount of credit you want to add: ');
            console.log("Your updated credit balance is: £" + points);
            break;

        case 3:
            deductions = readlineSync.questionInt('Enter the amount of credit you want to deduct: ');
            console.log("Deductions made. Your remaining credit balance is: £" + (points - deductions));
            break;
    }
} while(idx != 4);

Answer №2

Consider eliminating the brackets within your conditionals, for example:

if (count == 3)

Answer №3

Solving the issue is quite straightforward. The earlier if conditions will not be executed as the program flow cannot reverse. To address this, all the if conditions should be placed within a designated function. Upon receiving a new input, invoke this function so that each and every if condition is validated. The flow of control progresses from one line to the next without returning to a previous line unless inside a function (by calling it) or loop.

If you opt for a function, you have the option to call the function again ensuring that all if statements are reevaluated.

For instance:

if(i==1)
alert("one");
if(i==2)
alert("two");
 i=1;
if(i==3)
alert("three");

The program does not revisit the preceding if statement, hence no alert will be displayed.

function alerts()
{

if(i==1)
alert("one");
if(i==2)
alert("two");
 i=1;
alerts();
if(i==3)
}

In this scenario, only an alert box with "one" will pop up since the function has been invoked, causing prior conditions to be reassessed as well.

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

Can you merge the values between two arrays of objects by counting them and combining them into a single array?

I'm faced with an array conundrum categories: [ { name: 'category1', items: 0, }, { name: 'category2', items: 0, }, { name: 'category3', items: 0, }, ] And then there's this separate ar ...

The client side encountered an issue when attempting to transfer file data to a nodejs server

In my current project, I am working on a simple file upload module using AngularJS (v1.3.4) with a Node.js server. For this, I decided to utilize the https://github.com/danialfarid/angular-file-upload library. While the library seems straightforward, I hav ...

Setting up protected routes using react-router-dom version 6

When a visitor navigates to / (home), I want them to be redirected to /connexion" if they are not connected. To achieve this, I have implemented Private routes that work well. Now, I need to create the logic that will handle the redirection based on t ...

Moving a particle along the surface of a sphere using three.js geometry

Here is the code snippet I've been working on. Currently, my goal is to position a single particle on a sphere. How can I combine particles and sphere geometries together? Once this combination is achieved, I aim to dynamically render particles on top ...

Icon-enhanced Bootstrap dropdown selection

I have a unique select dropdown using Bootstrap where I want to display icons like the example below: https://i.sstatic.net/dZmTS.png <!DOCTYPE html> <html> <head> <script src="/scripts/snippet-javascript-console.min.js?v=1"& ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

How can I manually include a triangle in BufferGeometry using Three.js?

Recently, I've been exploring the quickest method to change a mesh's vertices using three.js. Through my experimentation, I discovered that modifying parts of mesh.geometry.attributes.position.array and then setting mesh.geometry.attributes.posit ...

What steps can be taken to ensure that only a single decimal separator is included?

I've created a calculator in HTML with two display screens, operators, and number buttons. The challenge I'm facing is implementing a decimal separator. Initially, I attempted to use a boolean variable as a switch, but the number() function remov ...

How to message someone privately in a public Discord channel using discord.js

Can someone help me figure out how to create a message in discord.js version 12.5.3 that only I can see? I know how to send messages to channels using message.channel.send, but I'm not sure how to make a message visible only to myself. Thank you! ...

Looking for a way to efficiently sort through props in Next.js? Struggling with filtering data within props from componentDidMount in Next.js?

I retrieve data into the props of my component using getStaticProps. However, I need to filter this data before utilizing it in the component. Typically, I would do this in componentDidMount, but it appears that the props are populated after componentDidMo ...

The terminal is unable to identify 'node' as a valid command, either internally or externally, in git bash. This could be due to it not being an operable

I encountered an issue where I received an error message stating 'node' is not recognized as an internal or external command, operable program or batch file when trying to run npm start from git bash CLI. $ npm start > [email protected] ...

Custom components receive specific values through Styled Components

Hey there! I'm currently working on customizing the color of a button based on its type within a modal. The button can be categorized as either "Success" or "Danger": import React from "react"; import styled from "styled-components" ...

What are the steps to execute a filter operation on a table by utilizing two select box values with jQuery?

I have a challenge with two dropdown menus. One contains names and the other subjects, along with a table displaying information in three columns: name, subject, and marks. I would like to implement a filter based on the selections in these two dropdowns. ...

Encountering a 'unknown column' error while using MySQL on a Windows operating system

A query is being executed on Node.Js with MySQL, resulting in the following: SELECT COUNT(DISTINCT t.uid) AS usersCount, COUNT(*) AS workingDaysCount FROM ( SELECT d.date, u.id AS uid, CASE TIMESTAMPDIFF(day, SUBDATE(d.date, WEEKDAY(d.date) ...

JavaScript Array Split Operation

I am facing a challenge with an array that contains multiple elements. A user has the ability to raise an HTML flag, which should result in the array being split at that specific point. It is important to note that the user can raise the flag multiple time ...

Encountering a 404 error when attempting to use the jQuery .load() function with parameters that include periods ('.')

I am attempting to invoke a controller function using the .load() method, but encountering an error which might be caused by the encoding of '.'. The call I am making is as follows: $("#main-content").load( url + "/" + encodeURIComponent(text ...

Displaying AJAX response with AngularJS

My Angular script structure is shown below: var myapp = angular.module("Demo",["ngRoute"]) .config(function($routeProvider){ $routeProvider .when ...

Creating a stylish CSS button with split colors that run horizontally

Could you please provide some guidance on creating a button design similar to this one? I've made progress with the code shown below, but still need to make adjustments like changing the font. <!DOCTYPE html> <html> <head> <sty ...

Accessing a file located in a specific directory using the node fs module

Currently, I am attempting to access a file from my local system using the 'fs' module in node.js. However, I have encountered an issue where the 'fs' module does not seem to function properly when an absolute path is provided. Here is ...

When sending large amounts of data using JQuery's ajax function with the POST method, it may not send the

While working on my Electron application, I encountered a problem with calling an API using the jQuery $.ajax function. When sending large data sets, part of the data was being truncated. However, when I tested the same request in POSTMAN, the server recei ...