It appears that there is a slight hiccup in the code when JavaScript is implementing the line skip functionality for the condition

Currently, I am working on a textbook exercise that involves the classic 99 Bottles of Beer on the wall JavaScript program. However, this assignment does not come with any examples or answers for reference. Despite searching online for assistance, the code I found differs greatly from what I have been taught in the book so far. One issue I encountered is that when the bottle count reaches one, the output displays "1 bottles" instead of "1 bottle". I'm unsure where I went wrong but I am excited to understand and improve! Thank you in advance for your help! Below is a link to the jsfiddle.

var word = "bottles";
var count = 99;
while (count > 0) {
    console.log(count + " " + word + " of beer on the wall ");
    console.log(count + " " + word + " of beer,");
    console.log("Take one down, pass it around,");
    count = count - 1;
    if (count > 0) {
        console.log(count + " " + word + " of beer on the wall."); 
    if (count === 1)
        word = "bottle";
    } else {
            console.log("No more bottles of beer on the wall.");
    }
}

https://jsfiddle.net/mmaffia92/3jp0fjya/

Answer №1

The reason behind the output "1 bottles of beer on the wall." in your code is due to the fact that you are modifying the value of word after logging that expression. To resolve this issue with minimal modifications to your existing code, all you need to do is switch the order of assigning values to word and using console.log:

if (count > 0) {
    if (count === 1) {
        word = "bottle";
    }
    // Keep in mind that the log comes after setting word = "bottle".
    console.log(count + " " + word + " of beer on the wall.");
} else {
    console.log("No more bottles of beer on the wall.");
}

In addition, I have enclosed the word = "bottle"; block within curly braces. While not mandatory, I believe it enhances code readability. On quick inspection, your else block may seem linked to if (count === 1), but it actually corresponds to if (count > 0).

Answer №2

To ensure the code runs smoothly, simply rearrange a few lines and make sure to keep the line that decrements the count within the loop. This is essential as it allows the loop to continue running until the condition (count > 0) is no longer met.

var count = 99;
var word;

while (count > 0) {
  var word = count === 1 ? "bottle" : 'bottles';
  console.log(count + " " + word + " of beer on the wall");
  console.log(count + " " + word + " of beer,");
  console.log("Take one down, pass it around,");
  count = count - 1;
  if (count > 0) {
    word = count === 1 ? "bottle" : 'bottles';
    console.log(count + " " + word + " of beer on the wall.");
    console.log('');
  }
}


console.log("No more bottles of beer on the wall.");

DEMO

To make the code more concise, you can replace the if statement with a ternary expression like so:

var word = count === 1 ? 'bottle' : 'bottles';

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

Retrieving information from a JSON file using AngularJS

Hello, I am a beginner in Angularjs and I am facing an issue while trying to retrieve data from a JSON file. The output I am getting is quite strange. Below are snippets from my controller.js and services.js files: angular .module('app') .contro ...

"Step-by-step guide on adding a new row to a table using a child controller in AngularJS

I have a table where I can insert new rows by opening a dialog window and entering the data. The dialog window contains a child controller called addNewTaskCtrl. Inside this dialog, there is a form that inserts data into the table when the "Add" button is ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Once appearing, the element quickly vanishes after the fadeIn() function is

In the source code, there is a section that looks like this: <div class="dash page" id="home"> <?php include ('pages/home.php'); ?> </div> <div class="dash page" id="screenshots"> <?php include ('pages/scr ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...

Steps to import an external script into a NextJS application and access it from the main bundle

I have encountered an issue while working with the mercadopago library. I need to load the mercadopago script file and create an instance of the MercadoPago object. However, nextJS loads the main bundle before including the mercadopago file, resulting in a ...

Ways to remove the highlighting from a selected list item using CSS/Javascript

I have a problem with a list of images and keywords that act as selections for users. When a user clicks on a selection, it highlights the corresponding image using CSS shadow. However, I am trying to figure out how to deactivate this highlight later on, e ...

Searching for JSON data in JavaScript

Is there a more efficient approach for searching data in JSON other than using loops? This is specifically for editing and deleting purposes. for(var k in objJsonResp) { if (objJsonResp[k].txtId == id) { if (action == 'delete') { obj ...

Develop and arrange badge components using Material UI

I'm new to material ui and I want to design colored rounded squares with a letter inside placed on a card component, similar to the image below. https://i.stack.imgur.com/fmdi4.png As shown in the example, the colored square with "A" acts as a badge ...

JavaScript: Controlling the ability to enter text based on the chosen option from a drop-down menu

After struggling to make my code work, I decided to create a piece of JavaScript to disable a text input when "Cash" payment is selected from the dropdown menu. On the contrary, I aimed to enable the text input if "Credit Card" payment was chosen. Unfortun ...

Building a 'Export to CSV' button using a PHP array within the Wordpress Admin interface

I have successfully populated a PHP multi-dimensional array using a custom function and now I want to enable my admin users to download the data. After researching, I came across a PHP function that can export an array to CSV file. I integrated this funct ...

Effective URL structure with nested ui-view in AngularJS

It is common knowledge that Angular functions as a SPA (Single Page Application). I am seeking the most effective approach to display a main left-side menu selector page, where clicking on any menu item will load the content in the right-side view div. Th ...

Issue with ISO-8859-1 character encoding in table formatting

I have set my website to use ISO-8859-1 encoding and special characters are displaying correctly. However, I'm facing an issue with the datatables plugin which does not seem to recognize special characters in the table data. Do I need to configure an ...

Having issues debugging in the browser as React seems to be undefined

I am trying to implement a Context system to store the login user's name and use it for protected routes. context.js import React from 'react'; const axios = require('axios'); export const AuthContext = React.createContext(null); ...

Showing validation for arrays with multiple inputs using Ajax in the Laravel framework

Could someone please provide guidance on how to use ajax to display the JSON response of form validation messages in Laravel? Below are some of my form inputs: {!! Form::text('stories[0][subject]', null, [ 'class' => 'form-con ...

Capture the $match outcome within a pipeline

My scenario for the output of the aggregation query: [{ items: <ALL_FILTERED_DOCUMENTS>, count: <ALL_DOCUMENTS_LENGTH> }] I attempted using `$facet`: db.collection(<COLLECTION>).aggregate([ { $facet: { items: [{ $match: <FILTER& ...

Transmit data or communications to a webpage while a script is performing operations (Django 4)

Currently, in my Python script with Django, when a user submits a file, I have a series of tasks that are processed which can take several minutes. While the user is waiting, a loading screen in JavaScript is displayed and updates are printed in the consol ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

What is the best way to modify a CSS property using logical operators in JQuery?

If an element with the class ".has_padding" does not have any text content, it should be set to "display:none;". However, those elements with text inside should remain visible. Below is some code where I have styled the elements to demonstrate the issue. ...

CSS Toggle failing to show updated styles

Initially, I successfully changed the font and color of text on Google using a simple code. However, when I attempted to incorporate it into a toggle on / off switch, the changes did not take effect. To address this issue, I sought assistance from ChatGPT ...