React

Common JavaScript Fundamentals Mistakes and Fixes

Fix the JavaScript fundamentals mistakes beginners make most: loose equality, lost this, shared objects, wrong sort and missing await, with code you can run.

✗x == y✓x === yVSCompare value and type
  • JavaScript
  • Debugging
  • Beginners

Quick answer: The most common JavaScript fundamentals mistakes are using == instead of ===, adding strings to numbers, using || for defaults when 0 is valid, looping with var, forgetting return, copying objects by reference, sorting numbers without a compare function, losing this and forgetting await. Most of them throw no error, so print values and types while you test.

JavaScript fundamentals mistakes are hard to spot because the language rarely stops you. A wrong type gets converted. A missing property becomes undefined. The page loads, and the answer is wrong.

Below are twelve bugs that beginners meet early. Each one has the broken code, its real output, the reason and the fix. Copy the code into a file and run it with node file.js, or paste it into your browser console. The text you see can look slightly different there.

If you are new to the language, read our JavaScript fundamentals tutorial first.

Mistakes with values and types

1. Using == instead of ===

console.log(0 == "");          // true
console.log("5" == 5);         // true
console.log("5" === 5);        // false

Why it goes wrong: == converts values before it compares them. An empty string becomes 0, so two different things look equal.

Fix: Use === and !==. They compare the type as well as the value.

2. Adding a string to a number

Every value from a text input is a string, even when the user types digits.

const price = "250";           // came from an input box
console.log(price + 50);       // 25050
console.log(Number(price) + 50); // 300

Why it goes wrong: If one side of + is a string, JavaScript joins the two as text.

Fix: Convert as soon as you read the input, then check the result with Number.isNaN().

3. Using || for a default when 0 is valid

const settings = { volume: 0 };
console.log(settings.volume || 50); // 50
console.log(settings.volume ?? 50); // 0

Why it goes wrong: || replaces every falsy value: 0, "", false, NaN, null and undefined. Here the user chose silence and got half volume.

Fix: Use ??. It replaces only null and undefined.

4. Expecting exact decimals

console.log(0.1 + 0.2);             // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);     // false
console.log((10 + 20) / 100);       // 0.3

Why it goes wrong: Numbers are stored in binary, and 0.1 has no exact binary form.

Fix: For money, keep whole paise and divide by 100 only when you show the amount.

Interview note: "What does 0.1 + 0.2 === 0.3 print?" is a classic. Say false, then explain binary storage in one sentence.

JavaScript fundamentals mistakes with variables and functions

5. Using var in a loop with a delay

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log("var", i), 0);
}
for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log("let", j), 0);
}
var 4
var 4
var 4
let 1
let 2
let 3

Why it goes wrong: var makes one variable for the whole loop. The callbacks run after the loop ends, when that variable is already 4. let makes a new variable for each round.

Fix: Use const by default and let when the value must change. Our closures interview questions cover more of this pattern.

6. Forgetting return

const doubleA = (n) => { n * 2; };
const doubleB = (n) => n * 2;
console.log(doubleA(4)); // undefined
console.log(doubleB(4)); // 8

Why it goes wrong: An arrow function returns automatically only when it has no braces. With braces, you must write return.

Fix: Remove the braces or add return. To return an object without braces for a body, wrap it in brackets: () => ({ id: 1 }).

7. Losing this

const student = {
  name: "Ravi",
  show() { return this?.name; },
};
const show = student.show;
console.log(student.show());   // Ravi
console.log(show());           // undefined
console.log(show.bind(student)()); // Ravi

Why it goes wrong: In a normal function, this depends on how you call it. show() has no object before the dot, so the link to student is gone. This happens often when you pass a method as a click handler.

Fix: Pass an arrow function, () => student.show(), or use bind.

Mistakes with arrays and objects

8. Thinking = makes a copy

const original = { name: "Anu", marks: { maths: 80 } };
const shallow = { ...original };
const deep = structuredClone(original);

shallow.marks.maths = 10;
console.log(original.marks.maths); // 10
console.log(deep.marks.maths);     // 80

Why it goes wrong: A variable holds a reference to an object. Spread copies only the outer level, so marks is still shared. Plain = copies nothing at all.

Fix: Use spread for flat data and structuredClone() for nested data.

9. Sorting numbers without a compare function

const marks = [100, 9, 25];
console.log([...marks].sort());                // [ 100, 25, 9 ]
console.log([...marks].sort((a, b) => a - b)); // [ 9, 25, 100 ]

Why it goes wrong: Without a compare function, sort turns values into strings. "100" comes before "25" because "1" comes before "2".

Fix: Pass (a, b) => a - b. Also remember that sort changes the original array, which is why this example sorts a copy.

Common mistake: Comparing two arrays with ===. [1] === [1] is false, because each literal is a separate object.

Mistakes with async code and the DOM

10. Forgetting await

const getMarks = async () => 75;

async function main() {
  const wrong = getMarks();
  const right = await getMarks();
  console.log(wrong instanceof Promise); // true
  console.log(right);                    // 75
}
main();

Why it goes wrong: An async function always returns a promise. Without await, you hold the promise and not the value inside it.

Fix: Add await, and put it inside an async function.

11. Using await inside forEach

const wait = (ms) => new Promise((done) => setTimeout(done, ms));

async function main() {
  [1, 2].forEach(async (n) => {
    await wait(10);
    console.log("saved", n);
  });
  console.log("finished?");
}
main();
finished?
saved 1
saved 2

Why it goes wrong: forEach ignores the promises its callback returns, so it does not wait.

Fix: Use for...of with await to go one by one, or await Promise.all(items.map(...)) to run them together. A related trap is fetch: it does not reject on a 404 or 500 reply, so check response.ok yourself. See our promises and async/await questions.

12. Running the script before the page exists

// Browser code
const button = document.querySelector("#save");
button.addEventListener("click", () => alert("Saved"));

Why it goes wrong: If this script is in the <head>, the button does not exist yet. querySelector returns null, and you get "Cannot read properties of null".

Fix: Load the file with defer, so it runs after the HTML is ready:

<script src="app.js" defer></script>

JavaScript fundamentals debugging in five steps

JavaScript fundamentals debugging is a routine, not a talent. Follow the same order each time.

  1. Read the first error. Note the type, the message and the line number.
  2. Check the value and the type. Use console.log({ price }, typeof price). The braces print the name too.
  3. Pause the code. Add debugger; and open the browser's developer tools. Step through line by line.
  4. Make it smaller. Delete lines until the bug disappears. The last line you removed is your suspect.
  5. Fix one thing, then test again. Include an empty value, a zero and a very large value.
Error message Usual cause First check
x is not defined Spelling or scope Is it declared where you use it?
Cannot read properties of undefined Missing object or late data Print the part before the dot
x is not a function Wrong type or lost import Print typeof x
Assignment to constant variable Changing a const Does it need let?
Unexpected token Missing bracket or comma Look at the line above too

Pro tip: Install the ESLint extension in VS Code and turn on the eqeqeq and no-var rules. It flags mistakes 1 and 5 while you type.

How to stop repeating JavaScript fundamentals common errors

Most JavaScript fundamentals common errors come from five habits. Change the habit and the bug stops coming back.

  • Start every variable with const, and change it to let only when you must.
  • Use === everywhere.
  • Convert input once, at the edge of your program.
  • Copy before you change an array or object that another part of the code uses.
  • Put try...catch around every network call.

Then test yourself. Cover the "why" lines above and explain each bug aloud. After that, try the JavaScript fundamentals practice problems, since JavaScript fundamentals beginner mistakes show up fastest when you write code without help.

If you want regular feedback, our Full Stack Web Development programme starts from the basics. It runs in the Madhapur, Hyderabad classroom and live online, with the same trainers and syllabus for students across Andhra Pradesh and Telangana. The full stack developer course guide shows where JavaScript fits in the full syllabus.

Frequently asked questions

Why does my JavaScript code show undefined?

The usual reasons are a function with no return statement, a property name that does not exist, an array index that is out of range, or a variable you read before giving it a value. Print the value one step earlier to find which one it is.

Should I always use === in JavaScript?

Yes, as a default. It compares value and type without converting anything, so the result is easy to predict. The one common exception is value == null, which checks for null and undefined together.

How can I debug JavaScript as a beginner?

Read the error message and line number first. Then print the value and its type, or add a debugger statement and step through the code in the Sources tab of your browser. Change one thing at a time and test again.

Why does await give an error in my code?

The await keyword works inside an async function, or at the top level of a JavaScript module. If you use it inside a normal function, you get a syntax error. Add async before that function to fix it.

Are these JavaScript mistakes asked in interviews?

Yes. Many fresher interviews include a guess-the-output question, and those questions are built on these bugs: var in loops, loose equality, shared references, this and the order of asynchronous code.


Want a trainer to find the bugs you cannot see? Book a free demo class in our Madhapur, Hyderabad classroom or live online from any city in Andhra Pradesh or Telangana.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us