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
, orconst
x = 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 NaN
console.log(typeof NaN); // "number"Even though
NaN
(Not a Number) means it's not a number,typeof NaN
returns "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
break
in aswitch
Statementswitch(day) {
case 1:
console.log("Monday");
case 2:
console.log("Tuesday");
}Forgetting to include
break
after acase
will cause the program to run through all remaining cases, which may result in incorrect outcomes. -
Functions Without a
return
Statement Returnundefined
function doSomething() {
// no return statement
}
console.log(doSomething()); // undefinedIf you forget to include a
return
statement in a function, it will returnundefined
, which can confuse developers. -
Forgetting That
this
Changes Contextconst obj = {
name: "John",
sayHello: function() {
setTimeout(function() {
console.log(this.name);
}, 1000);
}
};
obj.sayHello(); // undefinedIn this example, the
this
within the function passed tosetTimeout
no longer refers toobj
, which may prevent you from accessing the properties ofobj
as expected. -
Accessing an
array
Element That Doesn't Exist Returnsundefined
const arr = [1, 2, 3];
console.log(arr[5]); // undefinedWhen trying to access an array element that doesn’t exist, it returns
undefined
instead of an error, which might lead to confusion when debugging. -
Forgetting to Use
await
with Asynchronous Functionsasync function fetchData() {
const result = someAsyncFunction();
console.log(result); // Promise {<pending>}
}Forgetting to include
await
will return aPromise
instead 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.