Use some form of flag variable that exists outside of the loop. I would also print the index of the item, not the value, because the value is already known.
let flag = false;
let values = ["h", "i", "t"]
let target = "h"
function find(arr, t) {
let indexArr = []
for (let i = 0; i < values.length; i++) {
if (values[i] == target) {
console.log(`Item found at ${i}`)
flag = true;
}
}
return flag
}
let output = find(values, target)
This approach can be optimized. If I wanted to break the loop instantly and not care about telling someone the index of the value, I could use the following:
function find(arr, t) {
let indexArr = []
for (let i = 0; i < values.length; i++) {
if (values[i] == target) {
return true
}
}
return false
}
let output = find(values, target)
console.log(output ? "Item Found" : "Item Not Found")
Notice how I don’t return “Item Found”, I instead return true or false. This makes it a more universal function for others to use. Strings should always be a last resort. Always try to simplify logic into Booleans or lists of pure data.
Instead of writing the following and possibly dealing with typos (etc, “Item FOund”)
if (output == "Item Found") { ...
I could simply write the following that is universal
if (output) { ...
You could also use a method that saves the index of every location of your target in the array. This would be a more efficient approach if the target is repeated, which is usually the case. This is also more useful because in a real world application, you are trying to find something and need to save the location of that item.
function find(arr, t) {
let indexArr = []
for (let i = 0; i < values.length; i++) {
if (values[i] == target) {
indexArr.push(i)
}
}
return indexArr
}
let output = find(values, target)
console.log(output)
if (output.length == 0) {
console.log(`No Results Found`)
} else {
console.log(`Item Found`)
}
On a side not, you also could just use .indexOf()
which will return a index or -1 if the item is not found.