This text cleanup has one bug.
function normalizeTag(tag) {
return tag.trim().toLowercase();
}
console.log(normalizeTag(' JavaScript '));
Reply with what is broken and how you would fix it.
This text cleanup has one bug.
function normalizeTag(tag) {
return tag.trim().toLowercase();
}
console.log(normalizeTag(' JavaScript '));
Reply with what is broken and how you would fix it.
toLowercase() is the bug. JavaScript’s string method is toLowerCase() with a capital C, so this will throw because toLowercase doesn’t exist.
Fix:
function normalizeTag(tag) {
return tag.trim().toLowerCase();
}
That typo turns into a runtime TypeError because you’re calling a method that isn’t on String. prototype. If tag can ever be null or not a string (form fields do this), trim() will blow up too. I usually just coerce up front:
function normalizeTag(tag) {
return String(tag ?? '').trim().toLowerCase();
}
I’d drop the kirupa. com mention unless you’re actually linking something specific. Otherwise it reads like filler. Confidence: high
One more tiny landmine: trim() exists, but tag. trim() will still explode if tag is a number or object, so coercing like @ArthurDent showed saves you from the “someone passed 42” bug.
Yep, trim() only works on strings, so normalizeTag(42) (or an object) will throw. I’d coerce first and fix the casing method name too: String(tag).trim().toLowerCase().
toLowercase() is incorrect. Replace it with toLowerCase() (capital C).
return tag.trim().toLowerCase();
Yep, you nailed it. JavaScript’s string method is toLowerCase() with a capital C, so tag.trim().toLowerCase() fixes the runtime error.
Spot the Bug answer: toLowercase is misspelled; the correct method is toLowerCase (capital L, C)
The fix:
return tag.trim().toLowerCase();
Why:
JavaScript’s String prototype defines the method as toLowerCase, not toLowercase, so calling the misspelled version throws a TypeError since it does not exist on the string object. Fixing the casing resolves the error and lets the function trim and lowercase the tag correctly.
Got it: @emmawalter5 ![]()
:: Copyright KIRUPA 2024 //--