9 Commonly Amusing Mistakes in Javascript Programming Every Developer Faces
There are several problems that Javascript developers often encounter, which sometimes seem amusing because they happen so frequently or are caused by unexpected little mistakes. Here are some examples
-
Forgetting to Declare Variables with
var,let, orconstx = 10;When you forget to declare a variable using
var,let, orconst, the variable automatically becomes a global variable, which can lead to unexpected issues. -
The Result of
typeof NaNconsole.log(typeof NaN); // "number"Even though
NaN(Not a Number) means it's not a number,typeof NaNreturns "number," which confuses many developers. -
Using
==Instead of===console.log(0 == false); // true
console.log(0 === false); // falseUsing
==can lead to unexpected comparisons due to automatic type conversion. Using===avoids this issue by not converting data types before comparing. -
Forgetting the
breakin aswitchStatementswitch(day) {
case 1:
console.log("Monday");
case 2:
console.log("Tuesday");
}Forgetting to include
breakafter acasewill cause the program to run through all remaining cases, which may result in incorrect outcomes. -
Functions Without a
returnStatement Returnundefinedfunction doSomething() {
// no return statement
}
console.log(doSomething()); // undefinedIf you forget to include a
returnstatement in a function, it will returnundefined, which can confuse developers. -
Forgetting That
thisChanges Contextconst obj = {
name: "John",
sayHello: function() {
setTimeout(function() {
console.log(this.name);
}, 1000);
}
};
obj.sayHello(); // undefinedIn this example, the
thiswithin the function passed tosetTimeoutno longer refers toobj, which may prevent you from accessing the properties ofobjas expected. -
Accessing an
arrayElement That Doesn't Exist Returnsundefinedconst arr = [1, 2, 3];
console.log(arr[5]); // undefinedWhen trying to access an array element that doesn’t exist, it returns
undefinedinstead of an error, which might lead to confusion when debugging. -
Forgetting to Use
awaitwith Asynchronous Functionsasync function fetchData() {
const result = someAsyncFunction();
console.log(result); // Promise {<pending>}
}Forgetting to include
awaitwill return aPromiseinstead of the desired result from the asynchronous function. -
Forgetting to Add ; at the End of Statements
let a = 5
let b = 10
let c = a + b
console.log(c) // 15While JavaScript automatically adds semicolons in most cases (automatic semicolon insertion or ASI), forgetting to manually add
;can sometimes lead to unexpected behavior, especially when chaining multiple statements on the same line or using certain patterns that ASI doesn't handle well.
These issues occur frequently, and while they can be amusing when looking back, they often stem from negligence or small misunderstandings on the developer's part.