Currently trapped within the Javascript Fizzbuzz application on Codecademy

These are the instructions from Codecademy that need to be followed:

Display the numbers from 1 to 20.

If a number is divisible by 3, show "Fizz".

If a number is divisible by 5, display "Buzz".

If a number is divisible both by 3 and 5, then output "FizzBuzz" in the console.

Otherwise, simply display the number itself.

Here is the code I have prepared:

for (i = 1; i <= 20; i++) {
    if (i % 3 == 0) {
    console.log("Fizz");
    }
    else if (i % 5 == 0) {
    console.log("Buzz");    
    }
    else if (i % 3 == 0 && i % 5 == 0) {
    console.log("FizzBuzz");
    }
    else {
    console.log(i);    
    }
}

The issue encountered is with printing "FizzBuzz" for the number 15. It only prints "Fizz".

What could be the missing piece here?

Answer №1

The elseif statement is triggered only when all previous conditions have returned false. In this specific case, as i % 3 is true, the remaining else/if statements will not be executed. Below is an alternative approach:

for (i = 1; i <= 20; i++) {
    if (i % 3 == 0 && i % 5 == 0) {
        console.log("FizzBuzz");
    }
    else if (i % 5 == 0) {
        console.log("Buzz");    
    }
    else if (i % 3 == 0) {
        console.log("Fizz");
    }
    else {
        console.log(i);    
    }
}

Answer №2

If you're looking to implement a nested conditional, this example demonstrates how it can be done successfully.

for (let i = 1; i <= 20; i++){
    if(i % 3 === 0) {
        if(i % 5 === 0){
            console.log("FizzBuzz");
        }
        else {
            console.log("Fizz");
        }
    }
    else if (i % 5 === 0) {
        if (i % 3 === 0){
            console.log("FizzBuzz");
        }
        else{
            console.log("Buzz");
        }
    }
    else{
        console.log(i);
    }
}

Answer №3

Here's a concise implementation of FizzBuzz in JavaScript using ternary operators, which are shorthand for if-else statements. If you want to learn more about ternary operators click here.

let num = 1;
while (num <= 20){
    console.log((num % 3 === 0 && num % 5 === 0) ? "FizzBuzz" : (num % 3 === 0) ? "Fizz" : (num % 5 === 0 ? "Buzz" : num));
    num++;
}

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

Issue with three.js memory leak due to malfunctioning .dispose() method or incorrect usage

Greetings! I'm currently facing a memory handling issue. Despite researching various forums, I am still unable to identify the problem in my code. My project involves combining d3.js with three.js to create a visualization of nodes resembling planet ...

What steps need to be taken to implement a structured autocomplete feature?

Let me break down the workflow for you: The user inputs something in a text field. Upon keypress, the frontend communicates with our backend script to retrieve and select a specific value. Once the value is selected, on leaving the input field, we query ...

I'm curious about the outcomes of the JavaScript test. Could someone provide an explanation

Recently, I was in the process of writing a blog post discussing the importance of checking for the existence of jQuery elements before attaching event handlers. To illustrate this, I quickly created a jsfiddle example here. What puzzles me is that the re ...

Invoke the jquery plugin upon completion of the HTML load via Ajax

For my current project, I needed to style input radio buttons and decided to use the jquery uniform plugin. However, the radio buttons are displayed after some Ajax content is loaded onto the page. Since I do not have permission to edit the form or Ajax ...

Invoking a JavaScript function to retrieve an array of integers from a C# method for organizing columns in datatables.net

I have to admit that my JavaScript skills are not very strong. Currently, I am working on creating a table using datatables.net. The table is being populated by calling a generic handler, which in turn fetches data from the database using C#. This functio ...

Developing a JavaScript program for ATMs that can efficiently handle and dispense money in the fewest number of notes possible

When a certain amount is entered, the code should be capable of handling figures up to 20000. For instance, if the input amount is 2600 with a card balance of 3000, the output will be as follows: New Balance - 400 Notes: 2000 * 1 500 * 1 100 * 1 Only thre ...

Trouble with second function invocation in JavaScript

After creating two sets of arrays and passing them into different functions, I noticed some strange behavior. The first time I called the functions for scores1, everything worked perfectly. Likewise, the second time I called the first function (for Scores2 ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

Unlocking supplemental JSON data in a Dynatable AJAX query

I have implemented the dynatable.com plugin to generate a table of schools from our database. The table is dynamic and can be filtered, so it does not always display the total number of schools. While we do not include a 'number of pupils' column ...

The issue of jQuery not functioning properly within a Rails environment

Despite my efforts, I am still struggling to make jquery work in rails. I have installed the 'jquery-rails' gem and added the require statements in the application.js file. Below is a sample test page that I have been testing: <!DOCTYPE htm ...

Using jQuery to swap out sections of a HTML tag

Similar Question: Use of jQuery for Modifying an HTML Tag? After extensive research, I have not come across a solution that fits my specific requirements. My objective is to replace a part of an HTML tag without completely replacing the entire tag. To ...

Accessing an Accurate and Customized Menu Selection from an Old-School .ASP Loop Area

I am currently facing an issue with the note section in my form. Users with permissions can add information to a specific record, including deleting or editing their own notes. However, when I implemented a Jquery Modal Menu for confirming deletions, I enc ...

Accessing information via a PHP script with the help of AJAX and jQuery

In the process of developing a gallery feature that displays a full image in a tooltip when hovering over thumbnails, I encountered an issue where the full images extended beyond the viewfinder. To address this, I decided to adjust the tooltip position bas ...

Utilize an Express.js controller to retrieve information from an API service and display it on the view

I need assistance with connecting an ExpressJS web app to an API system that responds only with JSON objects. The API system example is: http://example.com/user/13 response: {name:'Aesome 1', age: '13'} The ExpressJS web app cre ...

Tips for accessing a value from a setInterval function

Is it possible to retrieve a value from the setinterval function in JavaScript? $.ajax({ type : "POST", url:"<?php echo TESTMINE_APP_URL; ?>/ajax/export-details", data:'paginationHash='+paginationHash+'&exp ...

What is the process for retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

AngularJS and Gulp: Enhancing Static Assets with Revisioning

I have implemented the gulp-rev module to re-vision static assets in my source files. It generates new file names for CSS, JS, and HTML files by appending a hash code to it. Before : app.js After : app-2cba45c.js The issue I am facing is that in my An ...

Utilize Google Charts Table Chart to extract data from an object-literal notation data source

Here's a look at the data source and Listener function: Data Source var data = new google.visualization.DataTable( { cols: [{ type: 'string', label: 'Col1' }, ...

What is the best way to determine the size of a returned element in React?

How can I determine if the description of {book.volumeInfo.description} is empty or not? If the length of {book.volumeInfo.description} is greater than zero, display it; otherwise, show "Book without description". I am unsure of the correct way to get the ...