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

When the React application loads, loadingbar.js will be mounted initially. However, as the props or states are updated, the object

I recently made the switch from using progressbar.js to loadingBar.js in my React application for widget progress. Everything was working smoothly with progressbar.js, but once I switched to loadingBar.js, I encountered a strange issue. After the page load ...

Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the ...

Can anyone suggest a solution to troubleshoot this issue with CSS Flexbox and absolute positioning?

I'm currently developing a React application featuring flex container cards (referred to as .FilmCard with movie poster backgrounds) within another flex container with flex-wrap. Each card has an item positioned absolutely (an FontAwesome arrow icon). ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

When using jQuery each method, it may return an [object Object]

Having an issue with the html variable displaying [object Object] instead of actual elements. Any suggestions on what I should change? var html = ''; $.each(data.response, function(index, value) { var tr = $('<tr>'); var ...

Enhance Your Charts: Learn how to dynamically adjust zoom levels between two timestamps with just a simple form submission

I have a Zingchart Area Graph that displays events on a timeline with time on the X-Axis. I want to be able to automatically zoom into a specific timeframe on the graph based on user input from a form. For example, if a user selects a start time of 8 AM an ...

Adding a div with a canvas element is malfunctioning

I've been experimenting with using canvg to convert an SVG within a div into a canvas. So far, the conversion is working fine but when I try to copy the innerHTML of the div to another div, it's not functioning properly. The canvas is being gener ...

Is it possible to dynamically load records in real time with the help of PHP and jQuery?

I developed a custom system using PHP that allows users to post status messages, similar to a microblog. The system utilizes a database table structured like this: posts_mst ------------------ post_id_pk post_title post_content date_added Initially, I su ...

Images that were just added to vite4 and vue3 are not appearing after the build on the production environment

I am facing issues displaying newly uploaded images in my Vue 3 project with Vite 4 on production after building. Despite trying various code snippets from the internet, I have not been successful so far. Specifically, I am attempting to display a user&apo ...

PhantomJS reveals underlying jQuery bug

Currently, I am developing automated test scripts that require a headless browser (PhantomJS) to perform all DOM navigation and actions except for downloads. So, PhantomJS seems like the right choice. However, I am encountering errors when trying to use P ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Error message: The context object is not iterable. Please note that it must be iterable in order to avoid

While going through a React course on Context API, I encountered an error that says "context is not iterable TypeError: context is not iterable". Has there been any new syntax introduced? If so, please let me know. Here is the content of app.js: I'v ...

Submitting an Ajax form to dual scripts

My goal is to pass variables from a single form to two separate php scripts for processing upon submission. The current setup that I have seems to be working fine, but I'm curious if there is a way to achieve this within one jQuery script instead of d ...

What is the reason behind obtaining a distinct outcome when logging the properties of an object compared to logging the object itself and checking its properties?

Currently, I am working on integrating socket-io with react redux and encountering a peculiar namespace problem. console.log(socket); console.log(socket.disconnected); console.log(socket.id); console.log(socket); The first log displays a comprehensive ob ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

Generating unique ObjectIDs for each object is crucial before saving documents in Mongoose

I need to generate a unique ObjectID for every object within my array. The challenge is that I am fetching products from another server using a .forEach statement and adding them to my array without a Schema that automatically creates an ObjectID.... Prod ...

Slower CSS rendering as Javascript finishes its tasks

I am currently dealing with a jQuery plugin that is quite large and complex, but I will not be sharing it here to keep things simple. The issue I am facing is relatively straightforward, so I will focus on the essential code snippets: There is a click eve ...

The MVC Controller is unable to retrieve decimal values from an Ajax POST request

I am facing an issue with the POST function in my code. While string and integer values are reaching the Controller without any problem, double values are not being received on the server side. Interestingly, when I test on my local machine, everything wor ...