JavaScript: Simply returning an array with no elements

As I work on refining a solution for fizzbuzz to generate an array of numbers and strings, I encountered an issue where the return statement only outputs an empty array. Interestingly, when I print the array to the console, it appears as intended with all the modifications I made. What could be the underlying concept that I am overlooking in this scenario?

Here is the code snippet:

function display(){
let fizzbuzz = [];

for (let i =1; i<=100; i++){

    let by3 = i%3==0; // checks if i is divisible by 3
    let by5 = i%5==0; // checks if i is divisible by 5
    let output="";


    if (by3){output+="Fizz";}
    if (by5){output+="Buzz";}
    if (output==="") {output = i;}
    fizzbuzz.push(output);
}

//console.log(fizzbuzz); 

return fizzbuzz; // the return statement is returning an empty array. Why is this happening? 
}
display();

Answer №1

The function display is not being shown on the screen. You have a couple of options to fix this:

window.onload = function() {
    console.log(display());
}

Alternatively, you could try:

window.onload = function() {
   let result = display();
   console.log(result);
}

Answer №2

This function is a simple implementation of the FizzBuzz problem:

function getFizzBuzzList() {
  let fizzBuzzList = [];

  for (let num = 1; num <= 100; num++) {
    let divisibleBy3 = num % 3 === 0;
    let divisibleBy5 = num % 5 === 0;
    let output = "";

    if (divisibleBy3) { output += "Fizz"; }
    if (divisibleBy5) { output += "Buzz"; }
    if (output === "") { output = num; }

    fizzBuzzList.push(output);
  }

  return fizzBuzzList;
}

const list = getFizzBuzzList();
console.log(list);

Answer №3

It seems like your function display() is functioning correctly. To confirm that it is returning the array with the necessary information, consider adding console.log(display()) at the conclusion of the script. Furthermore, if you require the array for other tasks, you can save it in a separate variable such as myArray = display()

Answer №4

Oops! Hey, thank you all. Once the responses began rolling in, I quickly realized my thinking was a bit off.

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

The Angular Factory service is accurately retrieving data, but unfortunately, it is not being displayed on the user interface

Here is a link to the complete source code angular .module('app') .factory('Friends', ['$http',function($http){ return { get: function(){ return $http.get('api/friends.json') .t ...

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

Exploring date formatting in NestJs with Javascript

Currently, I am working with a ScrapeResult mikroOrm entity. I have implemented the code newScrapeResult.date = new Date() to create a new Date object, resulting in the output 2022-07-17T17:07:24.494Z. However, I require the date in the format yyyy-mm-dd ...

What steps do I need to take to set up CORS properly in order to prevent errors with

I encountered the following error message: "Access to XMLHttpRequest at 'api-domain' from origin 'website-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HT ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

Do not activate hover on the children of parents using triggers

Check out my demonstration here: http://jsfiddle.net/x01heLm2/ I am trying to achieve two goals with this code. Goal number one is to have the mini thumbnail still appear when hovering over the .box element. However, I do not want the hover event to be tr ...

Endless cycle in Vue-Router when redirecting routes

I need advice on how to properly redirect non-authenticated users to the login page when using JWT tokens for authentication. My current approach involves using the router.beforeEach() method in my route configuration, but I'm encountering an issue wi ...

Step-by-step guide to performing an AJAX request in JavaScript while using Ubuntu

My current setup involves using a JavaScript file in conjunction with NodeJS to execute AJAX calls. To accomplish this, I have installed and imported jQuery as demonstrated below: var http = require("http"); $ = require("jquery"); test(); funct ...

The copyFileSync function is failing to copy the file without generating any error messages

I have developed a JavaScript function running in a nodejs/Electron client to copy a file from the user's flash drive to c:/Windows/System32. The file is copied to enable manual execution from Command Prompt without changing directories. The issue I ...

Sign up for an observable only when a specific variable has been modified

I am facing an issue where I need to restrict the usage of rxjs's subscribe method to only certain property changes. I attempted to achieve this using distinctUntilChanged, but it seems like there is something missing in my implementation. The specif ...

Highlighting text within ReactJS using Rasa NLU entities

Currently, I am working on a React application that retrieves data from the Rasa HTTP API and displays it. My goal is to tag the entities in a sentence. The code functions correctly for single-word entities but encounters issues with two-word entities (onl ...

Storing data in Angular service for future use

My ui-grid is functioning correctly, utilizing server side pagination with a view button to display row details on a separate page. However, upon returning to the grid after viewing details, it defaults back to displaying the first page. I would like it to ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

Steps to create an automatic submission feature using a combobox in HTML5 and then sending the retrieved data back to the HTML file

Here is the code snippet I've been working on: <strong>Station Name</strong> <!--This portion includes a combobox using HTML5 --> <input type=text list=Stations> <datalist id=Stations> <option>Station1</opt ...

How can JavaScript onClick function receive both the name and value?

My current challenge involves a function designed to disable a group of checkboxes if they are not checked. Originally, this function was set to work onClick(), with one argument being passed from the checkbox element. Now, I need this function to be trigg ...

A convenient Delete Modal Component in React utilizing Reactstrap

I am currently working on implementing a reusable Delete Component using reactstrap, which can be called from other components. Below is the code for my DeleteModal: class DeleteModal extends Component { constructor(props) { super(props); this. ...

Using jQuery AJAX to add to a JSON response with the value "d:null"

Hey everyone, I'm encountering a strange issue with my callback function when using the AJAX POST method to call my webservice. The JSON response from the webservice looks like this: Dim ser As New System.Web.Script.Serialization.JavaScriptSerialize ...

Can you explain the purpose of useEffect in React?

As a beginner in learning React, I have been able to grasp the concept of the useState hook quite well. However, I am facing some difficulties understanding the useEffect hook. I have tried looking through the documentation, searching online, and even wat ...

Retrieve information from an API and assign the corresponding data points to the graph using Material UI and React

I have 4 different APIs that I need to interact with in order to fetch specific details and visualize them on a bar graph. The data should be organized based on the name, where the x-axis represents the names and the y-axis represents the details (with 4 b ...

Reduce the number of days from a specified ISO date

How can I calculate the number of days between today and a date that's stored in my MongoDB database in ISO format? Your help is greatly appreciated. let ISOdate = ISODate("2020-12-25T20:40:08.295Z") let difference = newDate() - ISOdate; i ...