When debugging JavaScript, you’ll often encounter ReferenceError
and TypeError
. While both indicate something went wrong, they mean very different things. Let’s break them down with examples.
See document.querySelector() vs. getElementById(): Which is Faster?
ReferenceError
– “Variable Doesn’t Exist”Occurs when: You try to use a variable or function that hasn’t been declared.
console.log(nonExistentVar); // ReferenceError: nonExistentVar is not defined
someUndefinedFunction(); // ReferenceError: someUndefinedFunction is not defined
✔ Declare the variable/function before using it.
✔ Check for typos (myVar
vs. myvar
).
TypeError
– “Wrong Type or Invalid Operation”Occurs when: You try to do something invalid with a value, like:
null
or undefined
.let foo = null;
foo.bar; // TypeError: Cannot read property 'bar' of null
let num = 42;
num(); // TypeError: num is not a function
✔ Check if a variable is null
/undefined
before using it.
✔ Ensure functions/methods exist before calling them.
Error | Meaning | Common Causes |
---|---|---|
ReferenceError | Variable/function doesn’t exist. | Misspelled names, missing imports. |
TypeError | Operation invalid for the type. | Calling non-functions, accessing null props. |
ReferenceError
:TypeError
:typeof
or optional chaining (?.
) to avoid null
/undefined
issues.ReferenceError
→ “Does this exist?”TypeError
→ “Can I do this with it?”Pro Tip: Use TypeScript or ESLint to catch these errors early! 🚀
Which error trips you up more often? Let us know in the comments! 💬
Latest tech news and coding tips.
Imagine moving to a new apartment. Instead of disassembling your furniture, rebuilding pipes, and rewiring…
Imagine you’re the principal of a large school. Every day, students (like buttons, links, or…
You know that thing you do? Where you copy a chunk of code, paste it…
We've all seen them. The developers who seem to effortlessly untangle complex problems, whose code…
If you're building a social, chat, or comment-based mobile app using React Native, protecting your…
The Cross-Platform ImperativeLet's face it: building separate iOS and Android apps wastes resources. React Native…