JavaScript is a relatively simple language to learn. However, there are more than enough errors in it. Are you sure you don't allow them? Today we look at the 11 most common mistakes.
Error 1 - Using Global Variables
If you are only familiar with JavaScript, you probably think that this is great when all variables are global. In fact, you may not know all the subtleties 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 good, isn't it? Any variable is always available to change.
Not really.
')
This is a bad idea, as you may overwrite the values ​​unintentionally. Suppose you have an online store, and you use JavaScript to calculate the sum of prices of goods added to the cart. Here is a sample code:
var total = 0,
Now, let's say you use code to display tweets on a page, or have made a mini-gallery of your products. And there may contain code like this:
var total = 15;
Or,
var tax = function () { };
Now you have a problem. Two important variables were overwritten, and your code works with errors. The fee for this is the valuable time spent on rewriting.
So what's the solution? In short,
encapsulation ; but there are many other ways to avoid this. First, you can write all the code as a call itself, anonymous functions:
(function () { var total = 0, tax = 0.05;
And no code from the outside will get 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 this:
var cartTotaler = (function () { var total = 0; tax = 0.05;
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 example:
(function () { tax = 0.05; }()); var totalPrice = 100 + (100 * tax);
The
tax variable is available outside our function because the word
var was not used when it was declared. Watch this.
Error 2 - Lost Semicolon
Any operator in JavaScript must end with a semicolon. It is very simple. If you forget, the compiler will do the work for you. So you can not put them?
Well, in some places it is vital. For example, if you run several operators in a row in the loop body. Otherwise, the compiler will generate an error. What about the end of the line?
The JavaScript community was divided on this. There are weighty 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) { return { name : name }; }
It seems that it should return a small, pretty object ... but the compiler will decide what you want to put a semicolon after the return, so nothing will be returned, and the object will be ignored. You must do the following:
return { name : name };
So, my advice to you is to put dots with commas; honestly, it gets into habit pretty quickly. However, as a web developer, you probably use other languages ​​(for example, PHP), where dots with commas are not needed. Then why?
Note: If you do not know about every situation where it is allowed to lower, it is better not to risk it.Error 3 - Using ==
If you now ask the first JavaScript developer to find out: “What is the most common error in JavaScript?”, He / she will most likely respond: “Using == instead of ===”. What does it mean?
Try it:
if (1 == 1) { console.log("!"); }
You expected the code to work, right? Ok, now try this:
if (1 == '1') { console.log("!"); }
Yes, “Truth!” Jumped out in your console ... and yes, this is bad. The following occurs here, == - the equating 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-operator returns
true .
The solution, as you understand, is to use ===; All this works in the case of operators! == and! =.
And now, for fun, a few of the best mistakes that resulted from double equality:
'' == '0'
Error 4 - use of objects wrapping types
JavaScript kindly (!) Gives us a few type wrappers for easy (!) Type creation.
new Number(10); new String("!"); new Boolean(true); new Object(); new Array("", "", "");
First, it is super uncomfortable. All this can be done with a significantly smaller number of keystrokes.
10; ""; true; {}; ["", "", ""];
But wait, that's not all: the two things are not exactly the same. Here is what Douglas Crockford says on this issue:
For example, new Boolean (false) produces an object that has a valueOf method that returns a wrapped value.
- JavaScript: The Good Parts, page 114This means that if you run
typeof new Number (10) or
typeof new String (“Hello!”) , You get a 'object' - not the kind 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 (as they are not objects); so, when calling a method on a primitive object (for example, “Hello people!”. replace), JavaScript creates a wrapper for the string, does the work, and then discards the object.
Leave the javascript wrapper and use primitive values.
Error 5 - No attribute validation when using For-In
We are all familiar with brute force arrays; however, you may need to sort through the properties of the object. (Retreat. Actually, the elements of an array are the numbered properties of a single 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 don’t want these properties to be listed. You must use
hasOwnProperties to filter properties that are not objects:
Function Dog (name) { this.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] ); } console.log("====="); for (var prop in d) { if (d.hasOwnProperty(prop)) { console.log( prop + ": " + d[prop] ); } }
Sometimes you need properties, but you want to filter 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 teach
with or
eval . But if you use old or not very reputable sources (sometimes good material is really difficult to find on the Internet), you could find there
with or
eval and use them.
Awful start, developer.
So let's start with
with . Two main reasons why you can not use it:
- It slows down your code.
- It's not always clear what you are doing.
Point one is worth it. So let's take a look at a second. Here is how with works: you send an object to a 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);
But what if we have a variable with the same name as the property of the with object? In principle, if there is both, the variable will be used. But you cannot add properties to the object inside with. If there is no property or a variable exists, then the variable can be made from outside the with expression:
var person = { name: "", age : 10 }, name = ""; with (person) { console.log(name);
Let's
go to
eval . In a nutshell, you can pass a line of code to a function, and it will execute it.
eval( "Console.log('!');" );
It 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 work as well as with. Thus, the main use of eval is to execute code that you do not need at the moment. You could get it from the server or directly from the user. Do you really want to give site users complete control of your code? I hope no. In addition, he opens up 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 - Forget about using number systems when using parseInt
JavaScript gives us a small function that helps convert a string containing a number into a number:
parseInt("200");
And what happened there? Shouldn't the second example be 43? In fact,
parseInt does not work only with decimal systems. When he sees a line starting with 0, he considers it an octal number. Therefore, we should not forget about the number systems; they say functions about the base number.
parseInt("020", 10);
Error 8 - Do not use brackets when using if and while statements
One of the merits of JavaScript is flexibility. But sometimes she can turn against you. This happens in the case of curly braces in compound
if and
while statements . The brackets are optional if there is only one line of code in the statement:
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. First, this technique leaves no ambiguity:
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. The brackets will clarify here. Also, if you want to add a string to an if, do not forget the parentheses. Better add them right away, it's much easier. Do it.
Error 9 - adding items to DOM one by one
Yes, yes, this is not javascript. But in 99 cases out of 100, DOM is affected in JavaScript. Although there are many mistakes you can make in the DOM, the biggest one here.
Inserting a DOM element with JavaScript is fun and useful, but unfortunately loads the page. Therefore, inserting many DOM elements one by one is a bad idea:
var list = document.getElementById("list"), items = ["", "", "", ""], el; 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 storing DOM elements; then, instead of separate insertion, you can do everything in one fell swoop. The document fragment itself is not a node, and nothing will happen if you show it in the object model. It will be an invisible network for holding items before laying their DOM. Here is an example:
var list = document.getElementById("list"), frag = document.createDocumentFragment(), items = ["", "", "", ""], el; for (var i = 0; items[i]; i++) { el = document.createElement("li"); el.appendChild( document.createTextNode(items[i]) ); frag.appendChild(el);
Error 10 - You do not learn JavaScript
JavaScript is
NOT jQuery. OK? If you make a few of the errors listed above, you probably need to read JavaScript. JavaScript is a language that can be used with little or no learning, so many people do not spend time on it. Don't be one of them. There are many good language textbooks, so you have no excuses. If all you know is jQuery (MooTools, etc.), you put yourself in a bad place.
Many people do not waste time learning JavaScript properly .Error 11 - You follow all the rules
The 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 you cannot use one or another technique, 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’s better to use the 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 is an American programmer, developer of the JavaScript language, popularized JSON, the lead developer of Yahoo, and the creator of the YahooUI library.