The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →When JavaScript behaves unexpectedly, start with the exact error and the smallest piece of code that reproduces it. These five common pitfalls explain why callbacks can show the wrong value, comparisons can surprise you, and results can appear before they are ready—and how to correct each one.
Why does my loop callback show the wrong value?
If callbacks inside a loop all report the same final value, the loop variable may be declared with var. The loop itself runs as expected, but callbacks run later and share that function-scoped variable.
As an Amazon Associate I earn from qualifying purchases.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Logs: 3, 3, 3
Use let to create a separate block-scoped binding for each loop iteration:
Recommended Free Tools
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Logs: 0, 1, 2
MDN Web Docs explains that with let, the value associated with the function is unique to each iteration in “JavaScript debugging and error handling.” In modern code, prefer const for bindings you will not reassign and let when you will. A const binding prevents reassignment; it does not make an object’s contents immutable.
#1 Best Overall
Why does == work differently from ===?
The loose equality operator == can convert one or both operands before comparing them. Strict equality === compares without that type coercion, so values with different types remain distinct.
console.log(123 == "123"); // true
console.log(123 === "123"); // false
For beginner code, use === by default, and explicitly convert a value when conversion is intended:
Rank #2
const input = "123";
const number = Number(input);
console.log(number === 123); // true
This makes the type change visible instead of relying on implicit coercion. MDN’s equality comparisons guide describes how JavaScript compares values and where the operators differ.
Why is my JavaScript code not working when I define a function?
A function declaration creates a function; it does not run the function. Call it explicitly:
function greet() {
console.log("Hello");
}
greet(); // Calls the function
If the function is called but a name or value is still undefined, check spelling and capitalization: JavaScript identifiers are case-sensitive. Also verify that a variable is in scope where you use it. When building an object, separate each property name and value with a colon:
const person = {
name: "Kai",
age: 20
};
MDN’s “What went wrong?” troubleshooting guide recommends checking names and casing, as well as validating code for syntax problems.
Rank #4
Why is my async value undefined?
A Promise-based result is not available immediately. Code that runs next may execute before the asynchronous operation finishes; a Promise does not block the whole program. Put work that depends on the result after an await or inside a .then() handler.
async function showUser() {
const response = await fetch("/api/user");
const user = await response.json();
console.log(user);
}
showUser();
Here, await pauses showUser until each Promise settles, while other code can continue. Use await inside an async function, or in a JavaScript module context that supports top-level await. An alternative is to continue with .then():
Best Value
fetch("/api/user")
.then(response => response.json())
.then(user => console.log(user));
If you need to handle a failed request, add error handling, such as .catch() or try...catch. MDN covers asynchronous behavior and error handling in its Promise guide.
How do I find the actual JavaScript error?
Read the error before changing code. A misspelled name, for example, can cause a ReferenceError when execution reaches that line.
const total = 5;
console.log(totla); // ReferenceError: totla is not defined
Use this sequence to narrow down the cause:
- Validate the code. A validator or editor linter can flag syntax and other issues before you run the program. Fix reported problems one at a time.
- Open the browser developer tools. Check the Console for the exact error message and line, then inspect the stack trace to see how execution reached it.
- Check names and scope. Compare spelling and capitalization, and confirm the variable or function exists in the scope where it is used.
- Inspect runtime values. Add a targeted
console.log()near the failing line. Useconsole.error()when you want diagnostic output to stand out. - Handle or surface failures deliberately. Use
try...catcharound code that may throw, and usethrowwhen your code needs to report an invalid condition.
Validation or linting provides feedback before execution and can catch syntax or style issues; browser tools require no separate editor extension and show runtime state, errors, and stack traces after code runs. MDN’s troubleshooting guide and debugging and error-handling guide describe these techniques.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




