Finding myself at a standstill with the first step of the Codecademy FizzBuzz app

Let me share my code from the FizzBuzz lesson on Codecademy:

var i;
for ( i = 1; i > 20; i++ ) {
  "hello"
  if ( i % 3 === 0 ) {
    if ( i % 5 === 0 ) {
      "FizzBuzz";
    }
    else {
      "Fizz";
    }
  }
  else if ( i % 5 === 0 ) {
    "Buzz";
  }
 else {
    i;
  }
}

In my code, I aim to check if a number (i) is divisible by 3 before determining if it's also divisible by 5. If both conditions hold true, it should output "FizzBuzz". For cases where only the first condition applies, it's supposed to print "Fizz". If neither are divisible, but i is divisible by 5, it will display "Buzz". And as a last resort, it simply shows the number itself.

However, upon running the code, the results were not what I expected at all! Can you spot any glaring mistakes that I might have overlooked?

Answer №1

To begin, your loop is not starting as intended:

for ( i = 1; i > 20; i++ )

because the initial condition is already false. It seems like you meant to do this instead:

for ( i = 1; i <= 20; i++ )

"FizzBuzz";

is merely a string that JavaScript is disregarding. You must find a way to display this string:

console.log("FizzBuzz");

Furthermore, this portion

else {
    i;
  }

does not have any purpose. Were you trying to show numbers that are not divisible by 3 or 5?

else {
    console.log(i);
  }

Also, why is there a "hello" at the start of the loop?


On a brighter note, I appreciate that you are using strict equality:

if ( i % 5 === 0 )

This practice is commendable since the non-strict equality operator == can lead to unexpected implicit conversions. Always opt for strict equality unless you intentionally want those conversions to occur.

Answer №2

The main issues you are facing include misunderstanding of how the for loop works and the misconception that statements like "somestring" or i actually execute any actions. The correct approach is to output the information to the console (or another output stream) depending on the runtime environment of your Javascript.

It's worth noting that numbers divisible by both three and five are multiples of 15, which can simplify the code implementation.

To streamline your code, consider using a structure like this:

for each number in a specified range:
    if the number is divisible by 15:
        print "FizzBuzz"
        continue looping

    if the number is divisible by 3:
        print "Fizz"
        continue looping

    if the number is divisible by 5:
        print "Buzz"
        continue looping

    print the number itself

Some may argue against having multiple exit points in a loop, but as long as you maintain clear control flow within a concise structure, it eliminates the risk of creating spaghetti code.

Here's the corresponding Javascript code embedded in a webpage for testing purposes:

<html><head></head><body><script type="text/javascript">
    var i;
    for (i = 1; i <= 20; i++) {
        if (i % 15 === 0) {
            document.write ("FizzBuzz<br>");
            continue;
        };  

        if (i % 3 === 0) {
            document.write ("Fizz<br>");
            continue;
        };  

        if (i % 5 === 0) {
            document.write ("Buzz<br>");
            continue;
        };  

        document.write (i + "<br>");
    }   
</script></body></html>

When run, the script outputs the expected sequence:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

Answer №3

for (let x = 1; x <= 30; x++) {
    if (x % 21 === 0) {
        console.log("FizzBuzzPop");
    }
    else if (x % 3 === 0) {
        console.log("FizzPop");
    }
    else if (x % 7 === 0) {
        console.log("Pop");
    }
    else{
        console.log(x);
    };
} 

Answer №4

After reviewing all the insightful responses given here:

It appears that you may be experiencing difficulties with step 1 based on the code provided. I made a similar mistake when I followed your link and checked the instructions. Step 1 does not require solving the Fizzbuzz problem. Instead, it involves a much simpler task. I suggest revisiting the (not very clear) instructions once more ;)

Answer №5

When using the statement <code>for ( i = 1; i > 20; i++ )
, it actually means that the program will not execute any action as the condition is incorrect. To make the variable i start at 1 and end at 20, you should modify it to for( i = 1; i <= 20; i++). Additionally, if you intend to test a specific number, you can achieve this by creating a function like:

function TestFizzBuzz(num){
    ...
    ...
}
TestFizzBuzz(1);
TestFizzBuzz(990);
...

Answer №6

What if we increase the level of challenge? 1) Eliminate division and modulo operations; 2) Optimize the loop to avoid unnecessary iterations. Here's a unique solution:

int num3 = 3;
int num5 = 5;
int index = 3;

while (index <= 100)
{
    Console.Write(index.ToString() + " - ");

    if (index == num3)
    {
        Console.Write("fizz");

        num3 += 3;
    }

    if (index == num5)
    {
        Console.Write("buzz");

        num5 += 5;
    }

    Console.WriteLine();

    index = num3 < num5 ? num3 : num5;
}

Answer №7

This is my approach:

let numbers = new Array();

for (let j = 0; j < 20; j++){
    numbers[j] = j + 1;
}

for (let k = 0; k < 20; k++){
    if((numbers[k] % 5 == 0) && (numbers[k] % 3 == 0)){
        console.log("FizzBuzz");
    }else if(numbers[k] % 5 == 0){
        console.log("Buzz");
    }else if (numbers[k] % 3 == 0){
        console.log("Fizz");
    }else{
        console.log(numbers[k]);
    }
}

Answer №8

To keep it concise, let's achieve this in a single line of code:

for (i=1;i<21;i++){console.log(i+": "+(i%3?(i%5?i:'Buzz'):(i%5?'Fizz':'FizzBuzz')));};

Answer №9

  Let's write a simple FizzBuzz program using JavaScript! 

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

Answer №10

The objective is to output "Fizz" for numbers that are perfectly divisible by 3 (with no remainder), "Buzz" for numbers divisible by 5, and "FizzBuzz" for numbers divisible by both 3 and 5; otherwise, it should display the number itself.

  • The modulo (%) operator gives the remainder of a division operation, so when (x % y) equals 0, it means the division is perfect without any remainder
  • Since modulo can yield 0 as a result, it's important to understand truthy and falsy values - 0 is considered falsy, hence we need to negate the test if we want to check for an actual 0 value

    Example: !(3 % 3) => !(0) => !false => true

for (let i = 1; i <= 20; ++i) {
  if (!(i % 3) && !(i % 5)) { // Check if "i" is perfectly divisible by both 3 & 5
    console.log("FizzBuzz");
  } else if (!(i % 3)) {      // Check if "i" is only divisible by 3
    console.log("Fizz");
  } else if (!(i % 5)) {      // Check if "i" is only divisible by 5
    console.log("Buzz");
  } else {
    console.log(i);           // Output the number itself
  }
}
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

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

php utilizing javascript to generate encrypted data for a hidden file

Within my MVC application, I have implemented Raty for rating images. Below is the code snippet: <div class="container"> <form method="post" class='form' role='form' action="?section=photo&view=addVote"> <input t ...

Extract content from whole webpage including HTML, CSS, and JavaScript

Currently I am working on developing a webpage version control backup/log system. The goal is to automatically save a static copy of the webpage, including all its CSS and JavaScript files, whenever there are any changes made. I have already figured out h ...

Ways to eliminate text following a string substitution

When running the code below with keys assigned to summer, spring, fall, and winter, the output for ins would be: ['req.body.summer, req.body.spring, req.body.fall, req.body.winter'] I need to eliminate the surrounding string from the replace co ...

Is it possible to add to the existing class based on a certain condition?

I have a coding challenge that I need help with. I have a set of code where I want to replace the old value in a class named "content" based on certain conditions. If the value within the class matches one of the values in an Array, then I need to append s ...

Utilizing the Squared² Symbol in the Jscript File Path for Execution

I am encountering an issue with launching applications on a corporate portal that are tied to a specific business group. The problem arises when trying to access a file path that includes a ² character. This software is widely used on over 3000 computers ...

Node.js encountered an error: Address already in use. The specified port 8080 is currently being utilized by another application

My application was not functioning properly, and upon running the command "npm start", an error was thrown: Error: listen EADDRINUSE: address already in use :8080 Even after restarting my EC2 instance and attempting the command again, I encount ...

Guidelines for allowing TypeScript to automatically determine the precise structure of data objects in a generic HttpServiceMock through the utilization of TypeScript Generics and Interfaces

I'm currently diving into TypeScript and trying to accomplish something that I'm not entirely sure is possible (but I believe it is). Here's an example of the code I have: interface HttpServiceMockData<T> { status: number; data: T ...

The addition of a new row is permanent and cannot be altered

I am currently working with codeigniter and using bootstrap-editable.js plugin, among others. I have created an editable table with empty values, displaying only one row initially and providing an "addrow" button for users to add a new row if needed. The b ...

Sharing data between a Javascript applet and a webpage: strategies for sending results from the applet back to

When it comes to calling a method in an applet from JavaScript, I am facing a challenge. Both the applet and the JavaScript code are running on the same webpage. I am aware of how to call applet methods from JavaScript and vice versa using techniques like ...

Steps for removing an element from an array after unchecking a checkbox:

My issue involves handling multiple locations - when a particular location is checked, it gets added to an array. However, I am unable to remove it from the array when the checkbox is unchecked. handleChange(e){ if(e.target.checked){ let selec ...

After the animation has finished, the ".animated" class should be removed. If the element is reloaded, the class should be added back using plain

Within my CSS, there is a ".animated" class that is automatically applied to all elements with the "drawer-wrapper" class. The HTML structure looks like this: <div class="drawer-wrapper animated"> foo </div> I created a function that ...

Saving encoded data as base64 strings in GridFS (MongoDB's file storage system)

My current objective is to insert an image from the clipboard directly into an <img> tag. The image originates from the Prnt Scrn command rather than a file, resulting in a base64 format for the image. By utilizing JavaScript and a convenient plugin, ...

Show informational pop-up when hovering over selected option

My goal is to create an information box that appears when a user hovers over a select option. For example: <select id = "sel"> <option value="sick leave">Sick leave</option> <option value="urgent leave">Urgent lea ...

Certain users are experiencing a white screen when trying to view dynamic HTML5 videos on Firefox

Our header video displays an image first before lazy loading a video in either mp4 or webm format, depending on the user's browser. However, some Firefox users are experiencing issues where the HTML5 video source appears white instead of playing. Int ...

Modifying a JavaScript object causes changes to another object within the same array

Encountering an issue where player[0].pHand is being modified while updating player[1].pHand (where pHand is an array containing objects). for(var j = 0; j < 2; j++){ console.log(cardDeck[deckCounter]); player[0].pHand[j] = cardDeck[ ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

Creating a Kendo UI grid within a Kendo UI window and utilizing Knockout JS bindings

I'm encountering an unusual issue while working with Kendo UI and Knockout JS libraries. When attempting to display a kendo grid within a kendo window, the rows inside the grid are being duplicated. Below is a snippet of the code I'm using: JS: ...

What are the steps to implement IndexedDB in an Angular application?

I'm searching for a solution to utilize indexedDB within Angular. I need assistance with implementing data recovery or potentially using a browser-based database that doesn't have the 5 MB limit like localStorage. Can anyone point me in the right ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...