Contains Value
Write a TypeScript function that checks if a given value exists in an array. Return true if found, false otherwise. Implement the check manually with a loop.
Use a for loop to iterate through the array. Compare each element with the target using strict equality (===). Return true as soon as a match is found. If the loop completes without finding a match, return false.
Edge cases include empty arrays (return false), the target at the first position (return true immediately), and type-sensitive matching.
Linear search is the simplest searching algorithm. It checks each element in sequence and returns as soon as a match is found. This early-exit optimization provides O(1) best-case performance when the target is at the beginning of the array.
The strict equality operator (===) in TypeScript checks both value and type, ensuring that 0 and '0' are not considered equal. This prevents type-coercion bugs that can occur with the loose equality operator (==).
TypeScript's boolean return type annotation `: boolean` ensures the function always returns a boolean value, making the function's contract clear to callers.
The function uses early return optimization: as soon as the target is found, the function exits immediately without checking remaining elements. This provides the best performance when the target appears early in the array.Example Input & Output
Algorithm Flow

Solution Approach
Loop through the array with a standard for loop. If nums[i] === target, return true immediately (early exit). If the loop finishes, return false.
The time complexity is O(n) worst case. Space complexity is O(1).
Best Answers
function containsValue(target: number, nums: number[]): boolean {
for (var i = 0; i < nums.length; i++) {
if (nums[i] === target) return true;
}
return false;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
