I'm currently working on an if statement that checks for multiples of a specific number

I'm currently working on a coding exercise, but I've encountered an issue with my if/else structure and I can't figure out what's causing the problem.

Below is the prompt for the exercise along with the code I have written:

Your task is to create a function called fizzBuzz that takes a number as input and returns a corresponding string:

'fizz' if the number is divisible by 3;
'buzz' if the number is divisible by 5;
'fizzbuzz' if the number is divisible by both 3 and 5.
'{number}' if none of the above conditions are met.
function fizzBuzz(number) {

  if (number % 3 === 0) {
    return "fizz"
  };
  if (number % 5 === 0) {
    return "buzz"
  };
  if (number % 3 === 0 && number % 5 === 0) {
    return "fizzbuz"
  };
  else return number
}

Answer №1

Take a moment to mentally troubleshoot your code. Run various values through it in your mind and observe the outcomes:

  • What results do you get when inputting the value 6?
  • How about when using the value 10?
  • And what happens with the value 15?

Challenge yourself with the question, "How can I resolve this?" (remember: the order of operations matters).

Consider tweaking the code as shown below to achieve the desired functionality:

function fizzBuzz(n) {
  const fizz = n % 3 ? '' : 'fizz' ;
  const buzz = n % 5 ? '' : 'buzz' ;

  return !fizz && !buzz ? '{number}' : `${fizz}${buzz}` ;

}

Alternatively, you could try this approach:

function fizzBuzz( n ) {
  let s;

  if ( n % 3 === 0 ) {
    s = 'fizz' ;
    if ( n % 5 === 0 ) {
      s = 'fizzbuzz' ;
    }
  } else if ( n % 5 == 0 ) {
    s = 'buzz' ;
  } else {
    s  = '{number}' ;
  }

  return s;
}

The latter involves [at most] 2 divisions and 2 comparisons.

The former requires 2 divisions and 3-4 comparisons, making it slightly less efficient in theory.

Nevertheless, consider which version is more visually appealing for future reference.

Answer №2

In the scenario where a number is divisible by both 5 and 3 (e.g., 15), only "fizz" will be returned since it's the first condition to match due to the use of return in each block, creating a short-circuit effect. It is essential to prioritize the 5 and 3 conditions and fix the undefined variable error named solution. Also, the unnecessary semi-colons at the end of each block are there for formatting reasons but do not impact functionality.

function fB(number) {
  if (number % 3 === 0 && number % 5 === 0) {
    return "fizzbizz";
  }
  if (number % 3 === 0) {
    return "fizz";
  }
  if (number % 5 === 0) {
    return "bizz";
  }
  return number;
}

console.log(fB(15));
console.log(fB(575));
console.log(fB(49));
console.log(fB(51));
console.log(fB(80));
console.log(fB(375));
console.log(fB(99));
console.log(fB(Infinity));

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

Issues with Javascript functionality on aspdotnetstorefront site

Lately, I've been facing some challenges with my Javascript and jQuery codes when trying to implement them in the storefront. Despite attempting different methods to create a slider, none seem to work within the store environment - even though they fu ...

Having trouble implementing highlighting functionality for a WebElement in Selenium with JavascriptExecutor on Firefox version 35

During the execution of a script designed to highlight and reset a WebElement in selenium 2.43: public void highlightElement(WebElement element) { String originalStyle = element.getAttribute("style"); JavascriptExecutor js = (JavascriptExecutor) sele ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Increase the worth of a particular element within an array based on its index position

Is there a way to update the value of a specific object in an array based on its index? I tried the following code, but it ends up adding a new object to the array. Instead, I want to update the "errors" property of an existing object at a specific index ...

Utilizing the Three JS raycaster to detect intersections as the mouse cursor moves around

I have a strong intuition that the current method I am using is completely off base because I am struggling to achieve optimal performance for my website. Take a look at the primary code snippet: onDocumentMouseMove( event ) { if ( this.isUserInterac ...

AngularJs setPristine() not resetting the invalid status of a form

Is there anyone who can assist with the provided Plunker code? All you need to do is submit the form with just one required field filled out. This action will result in validation errors being displayed. When you reset the form by calling both setPristine ...

Creating a list of font sizes for each <p> tag in my HTML document

I am looking to create an array containing the font sizes of all the p tags in my HTML document. How can I specifically target only the p elements and not their parent elements? ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Converting a string to a date type within a dynamically generated mat-table

I am working on a mat-table that shows columns for Date, Before Time Period, and After Time Period. Here is the HTML code for it: <ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay" > ...

What is the best way to manage a situation where no link is returned to the "to" attribute of a Link component in React

Hey, I'm just starting out in programming and I have a question about handling the default case where no link is returned in the switch statement below: class ParentComponent extends React.PureComponent { get_link = () => { const item ...

Embed one module within another module and utilize the controller from the embedded module

I am attempting to create a module and inject it into the main module. Then, I want to inject the controller into the injected module but am facing issues. In my index.html file: <html ng-app="MenuApp"> <head> </head> <body> <d ...

Angular 4: Implementing a Re-login Dialog/Modal Using Interceptors

Issue Description I recently started working with Angular 4 and I am facing a challenge in handling user re-logging when the token expires. Let's Dive Into the Code I have implemented a response intercepter that checks for a 401 error in the respon ...

If the condition in CodeIgniter is met, then insert data into table1; otherwise, insert the data into a different

Can it be done?? if(selectedValue == Trending_blog) { insert into trendingTable; } else { insert into anotherTable; } I am looking to implement this in codeigniter. When the select box's value is trending, I need to insert that blog into tre ...

What could be causing the failure of isElementPresent function?

Here is a simple code snippet that waits for a dropdown list to be displayed on the page: var By = this.webdriver.By; var driver = this.driver; var bySelector = By.xpath('//*[@id="searchForm"]//*[@class="autocomplete-suggestions autocomplete-suggesti ...

What is the advantage of utilizing the ng-idle library for monitoring user idle status when we have the ability to create custom JavaScript code to track inactivity based on keyboard and mouse events?

I have implemented a method to detect user idle time using mouse and key events as shown below. @HostListener('window:keydown', ['$event']) @HostListener('window:mousedown', ['$event']) @HostListener('window:mou ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

`Uniform background color across all pages`

My goal is to allow customers to select a color that will persist across different pages on the website. The code below shows how users can choose a color on the first page: <select id="color" style="width: 5%; height: 10%" size="5"> ...

what is the significance of the number THREE in the context of Three.js?

Can you explain the significance of "THREE" in three.js? When we are creating a scene or any object, we typically use names like new THREE.Scene() or new THREE.WebGLRenderer(). What is the meaning behind the term "THREE" in this context? ...

maintaining the alignment of one div's right boundary with another div's right boundary

---------------------- ----------------------------->edge X | | | | | logo | | dropdown menu ...