Avoid these Javascript
Mistakes
@_codevalley
Zuhaib Asif
@_codevalley Zuhaib Asif
Not using strict mode:
Strict mode helps catch common coding
errors by enforcing stricter rules.
function doSomething() {
x = 10; // Assigning without declaring
}
function doSomething() {
'use strict';
let x = 10; // Declare before assigning
}
@_codevalley Zuhaib Asif
Not checking for null or undefined:
Checking for null or undefined values helps
prevent runtime errors.
function processData(data) {
if (data.length > 0) { // Might throw an error if data is
null or undefined
// Process data
}
}
function processData(data) {
if (data && data.length > 0) { // Check if data is not null
or undefined
// Process data
}
}
@_codevalley Zuhaib Asif
Relying too much on ==:
Using loose equality (==) can lead to
unexpected type coercion. It's safer to use
strict equality (===) for more predictable
comparisons.
if (num == '5') { // Type coercion may result in unexpected
behavior
// Do something
}
if (num === '5') { // Strict comparison avoids type coercion
// Do something
}
@_codevalley Zuhaib Asif
Inefficient looping over arrays:
Inefficient looping techniques can impact
performance, especially for large arrays.
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));
@_codevalley Zuhaib Asif
Using conditional statements over
ternary operator:
Ternary operators offer a concise way to write
conditional expressions and can enhance
readability.
let result;
if (x > 10) {
result = 'Greater than 10';
} else {
result = 'Less than or equal to 10';
}
let result = x > 10 ? 'Greater than 10' : 'Less than or equal
to 10';
@_codevalley Zuhaib Asif
Not using default function parameters:
Default function parameters provide fallback
values when arguments are not provided,
improving code clarity.
function greet(name) {
name = name || 'Guest'; // Not using default parameter
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!