Establishing a repeated sequence for an alternative condition within a function

Struggling to create a loop that includes an else statement. The if statement works fine, but when adding the else statement, it either shows nothing or creates multiple loops. It seems I may be placing the else statement in the wrong spot. Can someone explain where to correctly place the else statement and the nesting criteria for ending curly braces within a function? Here is my code that works well until I add the else statement. Thanks!

var sports = ["golf", "cricket", "tennis", "badminton", "squash"];

function checkSport(sportToCheck) {
    for (var i = 0; i <= sports.length; i++) {
        if (sportToCheck == sports[i]) {
            alert("yes we offer that sport");
        }
    }
}

checkSport("tennis")

Answer №1

It seems like in this scenario, you don't necessarily need to include an else statement based on the variable names used, but rather you want to terminate the loop or function as soon as the sport is found:

function checkSportAvailability(sport) {
  for (var x = 0; x <= sportsList.length; x++) {
    if (sport == sportsList[x]) {
      alert("Yes, that sport is available.");
      return; // End the function execution
    } else {
      console.log("There's no action required here, so the else statement can be omitted.");
    }
  }
  alert("Sorry, we do not offer that particular sport."); // Display message if no match is found after looping through all options
}

Answer №2

To strictly adhere to the principle of Do One Thing, it is recommended that your function, named check(), should return either true or false.

While there are multiple approaches to resolving your problem, personally I advocate for using find().

var sports = ["golf", "cricket", "tennis", "badminton", "squash"];

function checkSport(sportToCheck) {
  return sportToCheck === sports.find((sport) => sport === sportToCheck);
}
   
console.log(checkSport("football")); // Expected outcome: false
console.log(checkSport("tennis"));   // Expected outcome: true

If you wish to enhance @Hangindev's solution, you can consider implementing the following:

for (sport of sports) {
  true === (sportToCheck === sport) && alert("yes we offer that sport");
}

Answer №3

A more efficient approach is to iterate through each value in the sports array without using unnecessary else statements. By utilizing the return statement, you can halt script execution within the function as soon as a match is found.

This function will return either true or false based on whether the given string is present in the sports array.

var sports = ["golf", "cricket", "tennis", "badminton", "squash"];

function checkSport(sportToCheck) {
    for (var i = 0; i <= sports.length; i++) {
        if (sportToCheck == sports[i]) {
            alert("yes we offer that sport");
            return true;
        }
        if (i == sports.length) {
            alert("sorry we do not offer this sport");
            return false;
        }
    }
}

checkSport("tennis")

This method can be used in scenarios like:

if (checkSport("tennis")) {
    // sport exists
} else {
    // sport does not exist
}

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

Is the maxJsonLength property in the web.config referenced by JQuery's Ajax?

Within my ASP.NET platform, I implement Jquery AJAX to retrieve JSON data (essentially a string) from a webservice upon clicking the search button: $.ajax({ type: "POST", url: url, data: JSON.stringify(parameterArray), contentType: "application/j ...

Establish the focus when the TinyMCE editor loads

After clicking the edit button, the tinymce text editor is displayed but there's an issue where the focus is not set on the first load of the editor. However, it works fine from the second load onwards. Here's what I have attempted: HTML <h ...

Unexpected behavior observed in while loop with dual conditions

To break the while loop, I need two conditions to be met - res must not be undefined, which only happens when the status code is 200, and obj.owner needs to match a specific value I have set. Since it takes a few seconds for the owner on that page to updat ...

Stop the continuous AJAX loop or look for an alternative method to retrieve and compare a list of HTML pages

I am in need of a solution to insert a small script onto all of my website pages. The script must include the correct token for each of the 21 different domains I have. However, not all the sites are directly under the 'domain name' but are consi ...

JS Issue with triggering .click() function

I'm currently incorporating dropzone.js to enable file uploads. In my setup, I have a button with the id #btn and an input field with the id #input. The following code snippet is functional: $('#input').on('input', function() { ...

Exploring the use of Firebase for personal endeavors: What are the potential financial risks involved and how can they be mitigated?

I am interested in taking a course and following a tutorial from YouTube. Specifically, I am eager to learn about a project with many features that go beyond my current basic understanding of back-end development. [Project][1] https://www.youtube.com/wat ...

I need to know the right way to send a file encoded in Windows-1255 using Express

I'm currently developing an API that is responsible for generating text files. The purpose of this API is to support legacy software that specifically requires the use of Windows 1255 encoding for these files. To create the content of the file, I am r ...

How can I modify my array from using images to using string values for radio buttons?

I am currently utilizing an array in my code: function displayStoneCut(box){ var stonecutPics = new Array(5) stonecutPics[0] = "images/designform7/design-form-07_type6-2.gif"; stonecutPics[1] = "images/designform7/design-form-07_type6-1.gif"; stonecutPic ...

Break down for me what Json is in a way that a five-year-old could understand

Let me clarify one thing, I may not be a Javascript expert but I'm far from being 5 years old. Json is one concept that's been confusing me lately as I dive into the world of programming. Can someone please explain json to me in a simplified mann ...

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

Verify if the specified date (in string form) has already occurred or is upcoming using JavaScript

I need to determine if the start date of a given date range string (e.g. 12/20/12-12/24/12) has already passed the current date. Is there a way to achieve this using JavaScript or jQuery? ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Issues encountered when updating values in MaterialUI's TextField using Formik

Within my React functional component, I utilize Formik for form management and MaterialUI V5.10 for styling. The form includes TextField elements and a Canvas element. I am encountering two issues... Despite setting initial values in Formik, the TextFiel ...

Tips for accessing the information received from an AJAX call

When making an AJAX post request for processed data from the database in the form of an array [value1, value2, value3,...,valueN], I aim to use it on a ChartJS object. Here is the AJAX Request: $(document).ready($.post('callMeForAJAX.jsp', func ...

Steps for implementing AJAX to display a success function and update database results in real-time

I'm struggling with allowing my AJAX call to send data to my PHP file and update the page without a reload. I need the success message to display after approving a user, but their name doesn't move on the page until I refresh. The goal is to app ...

Identifying the presence of a property value within a collection of objects

I am trying to verify the existence of a 'member' object with a specific 'ID' in the 'members' array of an 'EntityGroup' container object. I'm having trouble understanding why the EntityGroup.idExists(id) method ...

Combining nested arrays, objects, and properties into one comprehensive flat table through a left join

Overview I am utilizing the Microsoft OData Query Builder library to generate nested tables, but I require a flat table. To accomplish this, I have two potential solutions: Adjust the nested JSON data I receive to create a flat table. Allow the OData Qu ...

Unsuccessful attempts to animate with Jquery in Google Chrome are persisting

I've been facing a challenge with my jquery code that seems to be getting the "click" function but does not animate. Instead, it just abruptly jumps without any smooth animation. I've spent hours trying to troubleshoot this issue. Here is the Jq ...

a simple guide to setting a "lowest possible value" in javascript

As I was working on creating a shop/store in my index.html file, I had the idea of implementing a feature that would prevent users from buying items if they don't have enough gems. For example: You can buy 1 coin for 20 gems [Buy] Gems: 19 Coins: 0 Er ...

There are encountered issues with the `POST` value not functioning properly on certain pages

Form submission was done using script: window.document.form_id.submit(); After redirecting to the action link, unable to retrieve value using $_post['name'] This functionality works fine on local environment but not on the server. ...