Top 11 Most Common JavaScript Errors

JavaScript is a relatively simple language to learn. However, there are more than enough errors in it. Are you sure you do not allow them? Today we look at the 11 most common mistakes.

Mistake 1 - Using Global Variables

If you are only familiar with JavaScript, you probably think this is great when all the variables are global. In fact, you may not know all the intricacies of this tool. Global variables are variables that are accessible from any part of the code, even if they are loaded into different .js files. Sounds tempting, doesn't it? Any variable is always available for change.

Not really.

This is a bad idea as you can overwrite values ​​unintentionally. Say you have an online store and use JavaScript to calculate the sum of the prices of items added to the basket. Here is a sample code:
var total = 0,    // конечные счет
    tax   = 0.05; // 5%

Now, let's say you use a code to display tweets on a page, or make a mini-gallery of your products. And it might contain code like this:
var total = 15; // кол-во твитов из twitter

var tax = function () { /* ... */ }; // Стартер для анимации

Now you have a problem. Two important variables have been overwritten and your code is not working properly. Paying for it is precious time spent rewriting.

So what is the solution? In a word, encapsulation ; but there are many other ways to avoid this. Firstly, you can write all the code in the form of a call itself, anonymous functions:
(function () {  
    var total = 0, tax = 0.05;  
    // какой-то код  

And no code from the outside gets to the code inside the function. This works great for "personal" code, but it does not provide the functionality that we need. For example, if we want a basket-counter that others could use as a template, it would be nice to do like this:
var cartTotaler = (function () {  
    var total = 0; tax = 0.05;  
    // еще код  
    return {  
      addItem : function (item) { },  
      removeItem : function (item) { },  
      calculateTitle : function () { }  

A little more about global variables: note that if you do not use the var keyword when creating a variable, the JavaScript engine defines it as global by default. For instance:
 (function () {  
  tax = 0.05;  
var totalPrice = 100 + (100 * tax); // 105 

The tax variable is available outside of our function because the word var was not used when declaring it. Watch for this.

Error 2 - Forgot about the semicolon

Any statement in JavaScript must end with a semicolon. It is very simple. If you forget, the compiler will do the job for you. So, you can not put them?

Well, in some places this is vital. For example, if you have several statements running in a loop body. Otherwise, the compiler will throw an error. What about the end of the line?

The JavaScript community is divided on this. There are strong arguments on both sides of the barricades. Here is my argument: if you rely on the compiler in this question (even in the simplest code), you play with fire.

For example, such a simple function:
function returnPerson (name) {  
        name : name  

It seems that it should return a nice little object ... but the compiler will decide that you wanted to put a semicolon after return, so nothing will return, and the object will be ignored. You should do the following:
return {  
    name : name  

So, my advice to you is to put semicolons; honestly, it gets in the habit pretty quickly. However, as a web developer, you probably use other languages ​​(for example, PHP), where you do not need to put semicolons. Then why?

Note: If you do not know about each situation where it is allowed to lower, it is better not to take risks.

Mistake 3 - Using ==

If you now ask the first JavaScript developer to come across: “What is the most common error in JavaScript?”, Most likely he / she will answer: “Using == instead of ===”. What does it mean?

Try it:
if (1 == 1) {  

You expected the code to work, right? Ok, now try the following:
if (1 == '1') {  

Yes, “Truth!” Popped up in your console ... and yes, that’s bad. The following happens here, == is the equalization operator. It makes the two variables as similar as possible. In our case, the string “1” is converted to the number 1, and our if-statement returns true .

The solution, as you understand it, is to use ===; All this is valid in the case of the operators! == and! =.

And now, for fun, a few of the best mistakes that came out of double equality:
''         == '0' // false  
'0'        == ''  // true  
false      == '0' // true  
' \t\r\n ' == 0   // true 

Mistake 4 - using objects wrapping types

JavaScript kindly (!) Gives us some type wrappers for easy (!) Type creation.
new Number(10);  
new String("Привет!");  
new Boolean(true);  
new Object();  
new Array("один", "два", "три");  

Firstly, it is super inconvenient. All this can be done with a significantly smaller number of keystrokes.
["один", "два", "три"];  

But wait, that’s not all: these two things are not exactly the same. Here's what Douglas Crockford * says on this matter:

For example, new Boolean (false) produces an object that has a valueOf method that returns a wrapped value.
- JavaScript: The Good Parts, page 114

This means that if you run typeof new Number (10) or typeof new String ("Hello!") , You will get an 'object' - not what you wanted. Plus, using a shell can cause an unexpected reaction.

So why does JavaScript give us these objects? For internal use. primitive values ​​have no methods (since they are not objects); So, when calling a method on a primitive object (for example, “Hello people!” replace (“people”, “habralyudi”)), JavaScript creates a wrapper for the string, does the job, and then discards the object.

Leave the wrapper for JavaScript and use primitive values.

Error 5 - No Attribute Verification When Using For-In

We are all familiar with enumeration of arrays; however, you may need to iterate over the properties of the object. (Digression. Actually, the elements of the array are the numbered properties of one object.) If you have not done this before, then you used the For-In loop:
  var prop, obj = { name: "Вася", job: "Тракторист", age: 55 };  
for (var prop in obj) {  
  console.log(prop + ": " + obj[prop]);  

If you run this code, you should see the following output:
name: Вася 
job: Тракторист
age: 55

However, the browser will include properties and methods further down the chain. Most likely, you do not want these properties to be listed. You must use hasOwnProperties to filter out properties that are not objects:
Function Dog (name) { = name;  
Dog.prototype.legs = 4;  
Dog.prototype.speak = function () {  
    return "Гав!";  
var d = new Dog("Тузик");  
for (var prop in d) {  
    console.log( prop + ": " + d[prop] );  
for (var prop in d) {  
  if (d.hasOwnProperty(prop)) {  
    console.log( prop + ": " + d[prop] );  
// Output  
// name: Тузик  
// legs: 4  
// speak: function () {  
        return "Гав!";  
// }  
// =====  
// name: Тузик  

Sometimes you need properties, but you want to filter out some methods. This can be done using typeof :
for (var prop in d) {  
  if (typeof d[prop] !== 'function') {  
    console.log( prop + ": " + d[prop] );  

In any case, always for-in expressions are clear to avoid unwanted results.

Error 6 - Using with or eval

Fortunately, most sources today do not learn with or eval . But if you use old or not very authoritative sources (sometimes good material is really hard to find on the Internet), you could find with or eval there and use them. A terrible start, developer.

So, let's start with . Two main reasons why you can not use it:

  1. It slows down your code.
  2. It’s not always clear what you are doing.

Point one stands its ground. So let's take a look for a second. Here's how with works: you send an object to an with-expression; then, inside the with block, you can access the properties of the object as variables:
var person = { name: "Петя", age : 10 };  
with (person) {  
  console.log(name); //Петя
  console.log(age);  // 10

But what if we have a variable with the same name as the property of the with object? Basically, if there is both, the variable will be used. But you cannot add properties to the object inside the with. If there is no property or the variable exists, then the variable can do this from outside the with statement:
var person = { name: "Петя", age : 10 },  
    name = "Жора";  
with (person) {  
  console.log(name); // Жора
  job = "Дизайнер";  
console.log(person.job); // неопределенно;  
console.log(job); // Дизайнер

Let's move on to eval . In a nutshell, you can pass a line of code to a function, and it will execute it.
eval( "Console.log('Привет!');" );

Sounds harmless, even powerful, right? In fact, this is the main problem - too much power. Obviously, there is no reason to write lines like this, because 1) why not write in a simple way? And 2) eval slows down as well as with. Thus, the main use of eval is to execute code that you don't need at the moment. You could receive it from the server or directly from the user. Are you sure you want to give site users full control of your code? I hope no. In addition, he opens his website for hackers: using EVAL is a sign that says: “I'm away, and the key is under the rug.” If you love yourself or your users: do not use it.

Error 7 - We forget about using number systems when using parseInt

JavaScript gives us a little function that helps convert a string containing a number to a number:
parseInt("200"); // 200  
parseInt("043"); // 35  

And what happened there? Shouldn't the second example be 43? In fact, parseInt does not only work with decimal systems. When he sees a line starting with 0, then he considers it an octal number. Therefore, we must not forget about number systems; they talk functions about the base number.
parseInt("020", 10); // 20
parseInt("100", 2);  // 4

Error 8 - Brackets are not used when using if and while statements

One of the merits of JavaScript is flexibility. But sometimes she can turn against you. This happens with curly braces in compound if and while statements . Brackets are optional if the statement has only one line of code:
if (true)  
  console.log("внутри оператора if");  

This is very convenient, because you can continue the statements on the same line:
 var arr = ["раз", "два", "три", "четыре", "пять", "шесть", "семь", "восемь", "девять", "десять"],  
    i   = arr.length - i;  
while (i) console.log( arr[i--] );  

But this is not reasonable for several reasons. Firstly, this technique leaves unclear:
if (true)  
  console.log("В операторе if");  
  console.log("Вне оператора if");  

See what I mean? The second line is not in the operator, but it looks very believable. Brackets bring clarity here. Also, if you want to add a line to if, don't forget the brackets. Better add them right away, it's much easier. Do it.

Error 9 - adding elements to the DOM one by one

Yes, yes, this is not JavaScript. But in 99 cases out of 100, JavaScript affects the DOM. Although there are many mistakes you can make in the DOM, here is the biggest.

Embedding a DOM element using JavaScript is fun and useful, but unfortunately it loads the page. So inserting many DOM elements one by one is a bad idea:
var list = document.getElementById("list"),  
    items = ["раз", "два", "три", "четыре"],  
for (var i = 0; items[i]; i++) {  
  el = document.createElement("li");  
  el.appendChild( document.createTextNode(items[i]) );  
  list.appendChild(el); // очень плохая идея 

Here is what you should do instead: use document fragments. Document fragments - containers for saving DOM elements; then, instead of separate insertion, you can do everything in one fell swoop. A document fragment is not a node in itself, and nothing will happen if you show it in the object model. It will be an invisible network for holding elements before laying out their DOM. Here is an example:
 var list = document.getElementById("list"),  
    frag = document.createDocumentFragment(),  
    items = ["раз", "два", "три", "четыре"],
for (var i = 0; items[i]; i++) {  
  el = document.createElement("li");  
  el.appendChild( document.createTextNode(items[i]) );  
  frag.appendChild(el); // Ништяк!  

Error 10 - You Don't Learn JavaScript

JavaScript is NOT jQuery. OK? If you make several of the above errors, you probably need to read JavaScript. JavaScript is a language that can be used with little or no learning, so many people don’t waste time on it. Do not be one of them. There are many good language textbooks, so you have no excuses. If all you know is jQuery (MooTools, etc.), you are putting yourself in a bad place.

Many people do not waste time learning JavaScript properly .

Error 11 - You follow all the rules

Last and final mistake - you follow all the rules. Yes, and some listed here. like everyone else, the rules for breaking them. The fact is that if you understand why one or another technique cannot be used, then it becomes a tool that you can correctly apply in the right situation. The same eval is the only way to parse JSON. Of course, there are many ways to check security in place (it is better to use a library). You should not be afraid to use “bad practice” if you know what you are doing and if it is necessary.

Of course, never make a mistake 10.

Douglas Crockford - an American programmer, developer of JavaScript, popularized JSON, a leading developer of Yahoo, as well as the creator of the YahooUI library.

Also popular now: