What is the best way to incorporate the final paragraph into the foundational code?

I'm attempting to create my own version of the lyrics for 99 Bottles of Beer

Here is how I've modified the last line:

1 bottle of beer on the wall, 1 bottle of beer.
Take it down and pass it around,
no more bottle of beer on the wall.

How can I include an additional line starting with a capital letter?

No more bottles of beer on the wall, no more bottles of beer.
Head to the store and buy some more, 99 bottles of beer on the wall.

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

Answer №1

You may also insert the console.log within the if loop

var beer = 99;
while (beer >= 0) {
  var words = beer === 1 ? "bottle" : "bottles";
  console.log(beer + " " + words + " of beer on the wall, " + beer + " " + words + " of beer. Take one down and pass it around, ");

  beer--;

  words = beer === 1 ? "bottle" : "bottles";

  if (beer === 0) {
    beer = "no more";
    console.log(beer + " " + words + " of beer on the wall.");
    console.log("No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.");
  } else {
    console.log(beer + " " + words + " of beer on the wall.");
  }
}

Answer №2

Take a look at the other responses for ways to enhance your current code

Below is my attempt at making it as DRY as possible.

const plur = (word, count) => count === 0 ? `no more ${word}s` : `${count} ${word}${count === 1 ? "" : "s"}`;
const capitalize = str => `${str.slice(0,1).toUpperCase()}${str.slice(1)}`;
const onTheWall = 'of beer on the wall';
for (let beer = 99; beer >= 0; beer--) {
    let beerText = plur("bottle",beer);
    let nextBeerText = plur("bottle",beer-1);
    const lines = [
        `${beerText} ${onTheWall}, ${beerText} of beer.`,
        beer > 0 ? `Take one down and pass it around,` : `Go to the store and buy some more,`,
        `${beer > 0 ? nextBeerText : plur("bottle", 99)} ${onTheWall}.`
    ];
    if(beer === 0) lines[0] =  capitalize(lines[0]);
    console.log(lines.join("\n"));
}

Here's another version for entertainment and learning purposes

const maxBeers = 99;
const plur = (word, count) => count === 0 ? `no more ${word}s` : `${count} ${word}${count === 1 ? "" : "s"}`;
const capitalize = str => `${str.slice(0, 1).toUpperCase()}${str.slice(1)}`;
const onTheWall = 'of beer on the wall';

const song = Array.from({ length: maxBeers + 1 }, (_, beer) => {
    beer = maxBeers - beer;
    let beerText = plur("bottle", beer);
    let nextBeerText = plur("bottle", beer - 1);

    let lines = [
        `${beerText} ${onTheWall}, ${beerText} of beer.`,
        beer > 0 ? `Take one down and pass it around,` : `Go to the store and buy some more,`,
        `${beer > 0 ? nextBeerText : plur("bottle", maxBeers)} ${onTheWall}.`
    ];

    if (beer === 0) lines[0] = capitalize(lines[0]);
    return lines.join("\n");
});

console.log(song.join("\n---\n"));

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

What is the best way to create dynamic .env files that can easily adapt to different environments instead of

Having multiple .env files (one for Vue and one for Laravel) with 'localhost' hard coded in them is causing accessibility issues from other computers on my network. It would be beneficial to have this set up dynamically, except for production. F ...

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

Navigating by Typing in the URL Bar in React

Whenever I paste a valid URL and press enter, the useEffect function in the parent component does not get triggered. However, if I reload the page, it works fine. Here is the code snippet: Routing path <Route path="/search" element={<Searc ...

Create a toggle effect similar to jQuery using JavaScript

Looking for pure JavaScript code to implement show/hide functionality similar to jQuery. Currently, I am using the following code: y=document.getElementById('regform').style.display; if (y == 'block'){ document.getElementById(&apo ...

Having trouble viewing objects' content in the JavaScript console in Visual Studio 2015?

In the past, I was able to see all the content of my JavaScript objects like this: However, for some reason now, the content is not being displayed at all: I am using Visual Studio 2015 Community with Cordova and Ripple emulator. I have tried creating a ...

Is there a clash with another code causing issues in troubleshooting a straightforward jQuery function?

jQuery(document).ready(function() { jQuery("#bfCaptchaEntry").on("click", function(){ jQuery("#bfCaptchaEntry").css("background-color", "#FFFFFF"); }); jQuery("#bfCaptchaEntry").on("blur", function(){ jQuery("#b ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...

PersistJS callback function is malfunctioning

I stumbled upon a great library for managing client storage. You can find the latest version here: https://github.com/jeremydurham/persist-js However, I encountered an issue with the callback function. var result = store.get('saved_data', func ...

What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows: var Parent = (function(){ var self; var parent = function(){ self = this; self.type = 'Parent'; }; parent.protot ...

Executing Sequential Jquery Functions in ASP.Net

I have successfully implemented two JQuery functions for Gridview in ASP.Net 1. Enhancing Gridview Header and Enabling Auto Scrollbars <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script& ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Is there a way to pull information from a string and organize it into a two-dimensional array?

Utilizing the axios library, I am pulling data from a website. Unfortunately, the data being fetched is in HTML format. The extracted data looks like this: 1 Agartala VEAT 120830Z 23004KT 5000 HZ SCT018 SCT025 34/27 Q1004 NOSIG= 2 Ahmedabad VAAH 120830Z 23 ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

Bind a collection of Firestore documents dynamically using Vuexfire

I currently have a collection of firebase documents stored in a vuex state that is dynamically updated. My goal is to bind these documents with vuexfire dynamically as they are added or removed from the list. state: { docsToBind: [], // This array is dy ...

"Enhancing User Experience with Multiple Conditional Checkboxes in jQuery

Having difficulty making a checkbox change some HTML content using JQuery. There is a standard html checkbox with the following attributes <input type="checkbox" name="AQN1" class="checkbox Q1" value="AQN10" id="3mcq"> <input type="checkbox" nam ...

Replace the indexOf() method to be called on a null value

I have discovered a way to override functions in JavaScript, such as indexOf(), like this: var indexOf = String.prototype.indexOf; String.prototype.indexOf = function(){ //MY CUSTOM CODE HERE return indexOf.call(this, arguments); }; By doing this ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...

The jQuery statements are not properly executing the if and else conditions

i'm currently assessing the condition using this particular code. jQuery(document).ready(function($){ $('#uitkering_funds').hide(); $('#uitkering_funds_hoofd').hide(); $('#partner_uitkering').hide(); $('#par ...

Ensuring JS consistently monitors changes in value

Is there an equivalent of (void update) in Unity that is called every frame in Web Development (using JavaScript)? "I want it to continuously check if certain values have changed and then update them accordingly." let governmentprice = parseFloat(select ...

Facing issues connecting to my MongoDB database as I keep encountering the error message "Server Selection Timed Out After 3000ms" on MongoDB Compass

I am encountering an error on my terminal that says: { message: 'connect ECONNREFUSED 127.0.0.1:27017', name: 'MongooseServerSelectionError', reason: TopologyDescription { type: 'Single', setName: null, maxS ...