Code Logo

Contains Value

Published at24 Jul 2026
TypeScript Data Structures Easy 0 views
Like0

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

Example 1
Input
0, [1,2]
Output
false
Example 2
Input
6, [1,2,3,4,5]
Output
false
Example 3
Input
5, [5]
Output
true
Example 4
Input
3, [1,2,3,4,5]
Output
true
Example 5
Input
5, []
Output
false

Algorithm Flow

Recommendation Algorithm Flow for Contains Value
Recommendation Algorithm Flow for Contains Value

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

typescript - Approach 1
function containsValue(target: number, nums: number[]): boolean {
    for (var i = 0; i < nums.length; i++) {
        if (nums[i] === target) return true;
    }
    return false;
}