GoodBye 7 Bad javascript code habits
- Not Using Strict Mode:
function notStrict() {
var x = 10;
y = 15;
return x + y;
}
console.log(notStrict()); // 25
function useStrict() {
'use strict';
var x = 10;
y = 15;
return x + y;
}
console.log(useStrict()); // Uncaught ReferenceError: y is not defined
In the first example, the variable y
is not declared with var
, let
, or const
, which means it is created as a global variable. In contrast, the second example uses "use strict";
to enforce stricter coding practices and throws an error because y
is not declared
2.Declaring Variables Without var/let/const:
function declareVar() {
x = 10;
return x;
}
console.log(declareVar()); // 10
console.log(x); // 10
In this example, x
is declared without var
, let
, or const
, which makes it a global variable. This can lead to issues when multiple scripts or functions use the same variable name.
3. Using eval():
var x = 10;
var y = 20;
var code = 'console.log(x + y)';
eval(code); // 30
In this example, eval()
is used to execute code from a string. This can be dangerous because it can execute arbitrary code and potentially introduce security vulnerabilities.
4. Overusing Global Variables:
var x = 10;
function incrementX() {
x++;
console.log(x);
}
incrementX(); // 11
incrementX(); // 12
In this example, x
is a global variable that can be easily overwritten by other scripts or functions. This can lead to unexpected behavior and bugs.
5. Not Handling Errors:
function divide(a, b) {
return a / b;
}
console.log(divide(10, 0)); // Infinity
In this example, divide()
does not handle the case where b
is 0
, which results in Infinity
. It's important to handle errors to avoid unexpected crashes and to help with debugging.
6. Copying and Pasting Code:
function calculateArea(length, width) {
return length * width;
}
function calculatePerimeter(length, width) {
return 2 * (length + width);
}
In this example, the calculateArea()
and calculatePerimeter()
functions are very similar and could be refactored to reduce code duplication. Copying and pasting code can make it harder to maintain your code in the long run.
7. Not Testing Your Code:
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log(capitalizeFirstLetter('hello world')); // 'Hello world'
In this example, capitalizeFirstLetter()
is a simple function that doesn't have any tests. Testing your code thoroughly can catch potential bugs and ensure that it's working as expected.