(Not so Awesome) Programming Languages Bad Features AKA What Not To Do and How To Fix It
Table of Contents
var worstPossibleExample = eval("[].map.call('Eval is evil', function(x){ return x;}).reverse().join('')");
console.log(worstPossibleExample);
The eval() function evaluates javascript code dynamically. This leads to a few problems.
- Using it improperly on the client-side could lead to code injection attacks.
- As you can see in my example, the code inside the eval can become very hard to read.
- It could make your code slow.
Don't use eval :)
",,," == new Array(4)); // true
null == undefined; //true
[] == false; // true
0 == "\t\r" // true
The ==
operator has a few problems:
- It compares just the values on both sides of the equality.
- It allows type coercing(implicit type casting).
Now, in the first example we can see both of these problems. On the left side we have a string with 3 commas, on the right side an initialized Array with 4 positions, which will evaluate to [, , ,] and get cast to a String, so the interpreter can compare the evalues. That's why it returns true.
Using the ===
comparison operator.
Because it not only compares values but types.
var foo = function () {
return
{
1: 'a'
}
} // throws a syntax error
var foo = function () {
var localVariable = 'local';
globalVariable = 'global';
}
foo();
This has to do with the way JavaScript deals with the scope chain. When you don't use the `var` keyword, the interpreter will assume you are referencing a variable. So, if the interpreter can't find the variable in the inner scope, it will look for it in the outer scope, and will keep doing it until it reaches the global scope. If it cannot find the variable at all, the interpreter will then declare it globally.
- Always use the
var
keyword before declaring variables. - Enable the ECMAScript 5 strict mode with:
'use strict';
at the beginning of a file or function, so globals will throw a ReferenceError - If you are writing a module, put yout code in an IIFE or better yet, learn to work with the Module Pattern.