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.