Is this example showcasing the use of JavaScript closures?

I have a JavaScript query that may be geared towards beginners:

var countries = [
    "Bangladesh", "Germany", "Pakistan"];


function checkExistence(arr, input) {

    for (var i = 0; i < arr.length; i++) {
        if (arr[i] != input) {
            alert("not exist");
            arr.push(input);
            break;
        } else {
            alert("already exist ");
        }
    }

}

checkExistence(countries, "UK");
checkExistence(countries, "Pakistan");
checkExistence(countries, "UK");

My expectation is that when I call the function again with 'UK', it should display "already exist"; however, this is not the case. I prefer to avoid using "prototype" or defining my own, and am seeking a one-line solution.

Within my code, there is an instance where I need to insert a new value into an array and then check that value in subsequent loops. Unfortunately, I keep adding existing values...

Why does the existing value get added, and why is the condition (arr[i] != input) failing?

Please provide an explanation as to why the above code is not functioning as intended.

Answer №1

It is essential to search through the entire array before concluding that an item doesn't exist within it.

function checkForItem(arr, target) {
    for (var index = 0; index < arr.length; index++) {
        if (arr[index] === target) {
            alert("The item already exists in the array");
            return; // stop the search by returning
        }
    }

    // If we reach this point, no matches were found during the loop.
    arr.push(target);
    alert("The item did not exist previously, but has now been added.");
}

Rather than using the name checkForItem, I would recommend naming your function something like addUniqueItem.

Answer №3

Firstly, it is important to note that this is far from being a form of closure.

In any case, here is the compact solution you requested, based on a modification of Ian's response

function checkExistence(array, item) {
  (!~array.indexOf(item)) && array.push(item);
}

We make use of several key concepts:

  • Array.indexOf searches for the first occurrence of a specific value in an array and returns its index (starting from zero) if found or -1 if not.
  • The usage of !~ in this context signifies checking for the value -1. The result of ~x is equivalent to -(x+1), transforming -1 into 0 (false) and all other numbers into non-zero values (true). Introducing ! flips this logic, turning -1 into true and everything else into false.
  • The && operator evaluates both sides. If the left side is truthy, then the right side is executed, otherwise it is skipped. This is commonly referred to as the "guard operator".

Answer №4

Give this code snippet a shot

var cities = ["new york", "tokyo", "paris"];


function checkCityExistence(arr, input) {
   var isPresent = false;

    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == input) {
            isPresent = true;
        }         
    }

    if(!isPresent)
    {
        alert("City does not exist in the list");
        arr.push(input);
    }
    else
    {
        alert("City already exists in the list");
    }
}

checkCityExistence(cities, "London");
checkCityExistence(cities, "new york");
checkCityExistence(cities, "London");

Answer №5

Here is an alternative solution to consider:

function checkIfExist(array, valueToCheck) {

    for (var j = 0; j < array.length; j++) {
        if (array[j] == valueToCheck) {
            alert("Value already exists in the array.");
            return;
        }
    }

    // If the if statement did not trigger, you will reach this point
    alert("Value does not exist in the array");
    array.push(valueToCheck);
}

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

Display or conceal DIVs with multiple attribute values according to the selected value in a dropdown menu using the jQuery Filter Method

I am attempting to display or hide multiple services, each with a custom attribute called data-serviceregion, which may have multiple values based on the selected option from the dropdown. <form class="book-now"> <select name="region" id="region" ...

Is it possible to iterate through a nested object with a dynamic number of fields?

{ "pagesections": [ { "title": "Leadership Team", "sections": [ { "title": "Co-Founders/Co-Presidents", ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

Issue - Basic Data Protection and Unscrambling - Node.js

I have been working on some basic code to encrypt and decrypt text, but I keep encountering an error when using the .final() function of createDecipherIV. I have tried experimenting with different encodings like Binary, Hex, and base64. Node Version: &apo ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...

Infinite scroll causing Firebase ".length" function malfunction

My NextJs website is encountering errors related to Firebase infinite scroll. The issue seems to be with the .length property being undefined for some unknown reason. I am struggling to debug the code and make it work properly in Next.js. Any help would be ...

Modifying an HTML list item to become 'active' in a navigation bar

One way I've been implementing my navbar on each page is by using the following code at the bottom of the page within script tags: $("#navbar-partial").load("navbar.html). The code for the navbar list looks like this: <ul id="main-nav" class="nav ...

Make sure to execute the fire directive only when ng-repeat has completed

Currently, I am utilizing owl carousel with data being fetched through an Ajax call. Once the data populates the HTML content using ng-repeat, I need to trigger the directive that initializes the owl carousel. How can I achieve this? One approach I consid ...

Ways to take an item out of your shopping cart

Do you have any ideas on how to handle cart redirection in JavaScript? My specific request involves a cart with a function that removes products. What approach should I take to redirect to the main page if the cart becomes empty? Here is the delete produc ...

How can I use jQuery to set the color of every other row in a

I'm facing an issue where I want to use jQuery to set the color of alternate rows in an HTML table. However, every time I add a new row, the color of the entire table switches. Below is the JavaScript code snippet that I am utilizing: var alternate = ...

Material UI Appbar is throwing an error with an invalid hook call

For my project, I needed to create a simple app bar, so I decided to use the code provided on the Material UI website. Here is the component's code that I used: import React from 'react'; import { fade, makeStyles } from '@material-ui/c ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

Is there a way to upload the image as byte data rather than a string?

As a beginner in python, I decided to experiment with changing my Instagram profile picture. However, I hit a roadblock when trying to input the image into the program. Here is the code I have so far: from instagram_private_api import Client, ClientCompatP ...

I am looking to have the first option in the dropdown menu appear as a placeholder text

In my form, I have two phone number fields - one for mobile phone and the other for home phone. I need to make only one of them mandatory. Can someone please advise me on how to accomplish this? ...

Having trouble sending a POST request to an Endpoint with Formidable and Request

I am encountering an issue while attempting a basic file upload to a REST endpoint using Node. The error that keeps appearing is: TypeError: Cannot read property 'hasOwnProperty' of null Below is my form setup: <form action="/upload4" me ...

PyScript <script type="py-editor"> Issue: SharedArrayBuffer cannot be used in an insecure environment

I am currently using PyScript to execute a basic Python script within my HTML file in order to show a pandas DataFrame. However, upon loading the page in the browser and attempting to run the code block by clicking the run button, I encounter an error rela ...

Creating an HTML table from JSON data using JavaScript

I recently wrote some code that reads the contents of an XML file and converts it into JSON. The JSON data is then displayed in an HTML table. Everything seems to be working fine, but there's one issue - the first row of the table always shows as "und ...

Ways to set a default value in AngularJS when there is no value to compare in an array

Hello, I'm a newcomer to AngularJS and I have the following code snippet in HTML: // Here, I have another ng-repeat loop where I compare home.home_info_id with avg.home_inof_id <div ng-repeat='home in homeDetailInfo'> <div ng-r ...

Tips for integrating v-virtual-scroll with v-table?

My Vuetify table is handling a large amount of data – 300 rows with 20 columns, some of which have calculated rowspans. To improve performance, I'm considering using the v-virtual-scroll component. I came across this sample code, which doesn't ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...