JavaScript for loop not executing as expected

Trying to create a JavaScript guessing game, but running into an issue with my for loop being skipped. This is the section of code causing trouble:

for (i = 0; i === tries; i += 1) {
    isSkipped = false;
    var guessedNumber = prompt("Guess your number now.");

    console.log("User guessed number " + guessedNumber);

    //check if number is correct
    if (guessedNumber === numberToGuess) {
        confirm("Hooray, you have guessed the number!");
        break;
    } else if (guessedNumber > numberToGuess) {
        confirm("A little too high...");
    } else {
        confirm("A little too low...");
    }
}

Here is the complete code:

//variables declaration
var numberToGuess;
var tries;
var i;
var isSkipped = true;

var confirmPlay = confirm("Ready to play the guessing game? The number will be between 1 and 25."); //prompt user

if (confirmPlay === true) {
    console.log("User ready to play");
} else {
    window.location = "http://lobuo.github.io/pages/experiments.html";
} 

numberToGuess = Math.floor((Math.random() * 25) + 1); //generate random number

tries = prompt("How many tries would you like?"); 
tries = Math.floor(tries); 

for (i = 0; i === tries; i += 1) {
    isSkipped = false;
    var guessedNumber = prompt("Guess your number now.");

    console.log("User guessed number " + guessedNumber);

    //check if number is correct
    if (guessedNumber === numberToGuess) {
        confirm("Hooray, you have guessed the number!");
        break;
    } else if (guessedNumber > numberToGuess) {
        confirm("A little too high...");
    } else {
        confirm("A little too low...");
    }
}

if (isSkipped === true) {
    console.log("Oh no! The for loop has been skipped!");
}

If more information is needed, feel free to ask.

Answer №1

Does the for loop need to be written in this way?:

for (i = 0; i < attempts; i += 1) {

Answer №2

When you are coding:

for (i = 0; i === attempts; i += 0) {

The loop will keep repeating as long as the condition i === attempts remains true. If, let's say, attempts is set to 3, this condition won't be met initially, causing the loop to end right away.

To fix this issue, you should program it like so:

for (i = 0; i < attempts; i++) {

Answer №3

It is important to utilize the parseInt() function when dealing with user input.

 var guessedNumber = parseInt(prompt("Please enter your guess."), 10);

rather than

var guessedNumber = prompt("Please enter your guess.");

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

Exception: Closing the database connection failed: db.close is not a callable

I have this Node.js application that utilizes MongoDb: const MongoClient = require('mongodb').MongoClient; const demoPerson = { name:'Jane', lastName:'Doe' }; const findKey = { name: 'Jane' }; MongoClient.connect( ...

Instructions on eliminating the chosen value from the initial dropdown to ensure it does not appear in the second dropdown, with the value retrieved directly from the database. [Laravel]

<div class="form-group mb-3"> <label for="">item 1 </label> <select name="item1" class="js-example-basic-single" style="width: 100%;"> ...

What is the best way to organize mocha tests to run sequentially?

I am currently working with a group of modules that are triggered by a global event emitter. These modules operate in a sequential chain based on specific events, such as: boot.ready server created (triggered by boot.ready event) server configured (trigg ...

Troubleshooting: The issue of importing Angular 2 service in @NgModule

In my Angular 2 application, I have created an ExchangeService class that is decorated with @Injectable. This service is included in the main module of my application: @NgModule({ imports: [ BrowserModule, HttpModule, FormsModu ...

Unlocking secrets: Displaying PIN/ Password using Bootstrap pincode-input.js

I am using Bootstrap's pincode-input.js to mask the PIN on my web app. However, I would like the PIN to be initially hidden, and only revealed when the user clicks the show button. Can anyone help me with this? Thank you in advance. <input type="t ...

Storing the value from the INPUT field in the state of React is not permitted

I'm attempting to retrieve the user input value from the INPUT field and update it in the corresponding state. However, no matter what I type in the field, it doesn't get set to the state. createForm(x){ var dx = 'd'+x let da ...

Tips on populating a text input field using ajax

This is the Jquery and ajax code I have written to load text box data sent from the server class. I am receiving a response, but for some reason, the data sent from the server is not loading into the textbox. You can see the error here. $(document).read ...

Is it possible to utilize an OAuth token generated from the backend on the frontend of my application?

After reviewing the details of Google's DrEdit sample app in Java, which showcases how to create a simple Drive application and manage authorization on the backend, I have come across an issue. Despite authenticating the app previously, users are stil ...

Establishing a universal function within Ionic AngularJS

I have the following code snippet, where I have added a reset function that I want to be able to use from ng-click in any part of any template. angular.module('starter', ['ionic', 'starter.controllers', 'starter.services ...

Using `ng-disabled` in AngularJS to check a function that utilizes `$http.get`

Seeking assistance on how to make my ng-disabled button trigger a controller function that makes an $http.get request. Below are the relevant code snippets: HTML Code: <a class="btn btn-warning" ng-click="upVote(item,me.email);" ng-disabled="votechec ...

Enhancing a jQuery progress bar with countdown timers and markers

Recently, I've been exploring the idea of creating a progress bar using jQuery. I came across examples like this one, as well as some simpler code snippets: var bar = document.getElementById('progress'), time = 0, max = 5, int = setInterval ...

Guide on incorporating reusable component inputs in Vue 3

Does anyone have any tips on creating reusable component input in Vue 3? Similar to how it's done in React: For example, Using <Input /> as a reusable component in the parent component import { ref } from 'vue'; import Input from &a ...

The form dropdowns are failing to reset after the select id is added in the html code

I'm attempting to reset the form fields. I have two selects with Select2 in JavaScript. If I eliminate the id of either select, it will reset, otherwise it will remain the same. $(document).ready(function() { $("#fieldName").select2(); $("#acti ...

When the checkbox is unchecked

Is it possible to remove the Checkbox element from the array once it is unchecked? { columns.columnNames && columns.columnNames.map(el => { return ( <div> <input type="c ...

Refreshing ng-repeat dynamically with $http without reloading the page

Just a quick heads-up, I'm new to AngularJS In my AngularJS application, I am using the $http service to fetch data. Each row has an update button that needs to trigger a server-side method (the API is already returning data) to sync with a third-par ...

Incorporating jquery.prettyPhoto results in the script being displayed on the webpage

When I relocate the following script: <script src="js/jquery.prettyPhoto.js"></script> To this location: <script type="text/javascript"> ... </script> The script starts displaying on the page starting from the bold section on ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

Establishing connection with SignalR JavaScript client

I'm unfamiliar with SignalR and I find myself feeling lost. My task is to establish a connection to a stream and retrieve certain data. The owner provided some guidance, but they are unsure how to accomplish this using JavaScript. They shared the fol ...

Error in JScript encountered during the downgrade to .NET Framework 2.0

Working on a Web Application project has brought about some challenges for me. Originally created in .NET 3.5, I recently found out that it has to be converted to .NET 2.0 (sigh). This transition not only caused issues with the LINQ functionalities but als ...

How is it possible for React to function within the views directory?

In the directory structure of my project, I have a React application housed within the views folder. The root folder contains the model, controller, and views directories. Within the views folder, there is a React app. I am unsure of how to start both si ...