TheAlgorithms/JavaScript · error · TypeError
Argument should be string
Error message
Argument should be string
What it means
Guard in firstUniqChar. The function finds the index of the first non-repeating character and requires the input to be a string, throwing TypeError otherwise. (Note: the body misuses a Map with bracket access, but the guard itself is a clean type check.)
Source
Thrown at String/FirstUniqueCharacter.js:13
/**
* @function firstUniqChar
* @description Given a string str, find the first non-repeating character in it and return its index. If it does not exist, return -1.
* @param {String} str - The input string
* @return {Number} - The index of first unique character.
* @example firstUniqChar("javascript") => 0
* @example firstUniqChar("sesquipedalian") => 3
* @example firstUniqChar("aabb") => -1
*/
const firstUniqChar = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Argument should be string')
}
const count = new Map()
for (const char of str) {
if (!count[char]) {
count[char] = 1
} else {
count[char]++
}
}
for (let i = 0; i < str.length; i++) {
if (count[str[i]] === 1) return i
}
return -1
}
export { firstUniqChar }
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string; coerce numbers with String(n) or n.toString() first.
- Default missing values to '' (returns -1).
- Validate typeof at the boundary.
Example fix
// before firstUniqChar(maybeStr) // after firstUniqChar(typeof maybeStr === 'string' ? maybeStr : String(maybeStr ?? ''))
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof str !== 'string') {
throw new TypeError('str must be a string')
}
firstUniqChar(str) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
firstUniqChar(input)
} catch (e) {
if (e instanceof TypeError) { /* not a string */ } else throw e
} Prevention
- Coerce numbers with String() before passing.
- Default missing values to '' (returns -1).
- Validate typeof at the boundary.
When it happens
Trigger: Calling firstUniqChar(undefined), firstUniqChar(null), firstUniqChar(0), firstUniqChar([]). Any input where typeof !== 'string'.
Common situations: A LeetCode-style input that arrives as a number when a string was expected; a payload field that is null on miss; a destructured value that does not exist.
Related errors
- Argument is not a string.
- Argument is not a string.
- The first param should be a string
- The second param should be a boolean
- Input should be a string
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/a9b1fce3a2ddfc53.
Report an issue: GitHub.