- One of these is that when you use a loop to create a new string, you use the join (), which is more efficient, often with push ();
- When you bind an action, you define the binding content that you want to execute as a function and then execute it. There are many advantages to doing so. The first is can be executed many times, the second is convenient debugging, the third is to facilitate reconstruction.
As a follow-up to "the HTML and CSS best practices", this week, we ' ll review javascript! Once you ' ve reviewed the list, being sure to let us know what little tips you ' ve come across!
1. Use = = = Instead of = =
JavaScript utilizes different kinds of equality operators: = = = | !== and = = | != It is considered best practice to always use the former set when comparing.
"If the operands is of the same type and value, then = = = produces true and!== produces false." –javascript:the Good Pa Rts
However, when working with = = and! =, you'll run into the issues when working with different types. In these cases, they ' ll-try to coerce the values, unsuccessfully.
2. Eval = Bad
For those unfamiliar, the "eval" function gives us access to JavaScript ' s compiler. Essentially, we can execute a string ' s result by passing it as a parameter of "eval".
Not only would this decrease your script ' s performance substantially, but it also poses a huge security risk because it GRA NTS far too much power to the passed in text. Avoid it!
3. Don ' t use Short-hand
Technically, you can get the away with omitting most curly braces and semi-colons. Most browsers would correctly interpret the following:
if (somevariableexists) x = False
However, consider this:
if (somevariableexists) x = False Anotherfunctioncall ();
One might think that the code above would is equivalent to:
if (somevariableexists) { x = false; Anotherfunctioncall ();}
Unfortunately, he ' d be wrong. In reality, it means:
if (somevariableexists) { x = false;} Anotherfunctioncall ();
As you ll notice, the indentation mimics the functionality of the curly brace. Needless to say, the is a terrible practice that should being avoided at all costs. The only time that curly braces should are omitted are with one-liners, and even this is a highly debated topic.
if (2 + 2 = = 4) return ' nicely done ';
Always consider the future
What if, at a later date, you need to add more commands to this if statement. Would need to rewrite this block of code. Bottom Line–tread with caution when omitting.
4. Utilize JS Lint
JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it ' ll quickly scan for any noticeable issues and errors in your code.
"JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem isn't necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove this your program is correct. It just provides another set of eyes to help spot problems. "
-JSLint Documentation
Before signing off on a script, run it through jslint just to being sure that you haven ' t made any mindless mistakes.
5. Place Scripts at the Bottom of Your Page
This tip has a already been recommended in the previous article in this series. As it ' s highly appropriate though, I'll paste in the information.
Remember-the primary goal is and make the page load as quickly as possible for the user. When loading A is script, the browser can ' t continue on until the entire file has been loaded. Thus, the user would have a to wait longer before noticing any progress.
If you had JS files whose only purpose are to add functionality-for example, after a button is clicked-go ahead and PL Ace those files at the bottom, just before the closing body tag. This was absolutely a best practice.
Better
<p>and now know my favorite kinds of corn. </p><script type= "Text/javascript" src= "path/to/file.js" ></script><script type= "text/ JavaScript "src=" Path/to/anotherfile.js "></script></body>
6. Declare Variables Outside of the for StatementWhen executing lengthy "for" statements, don ' t make the engine work any harder than it must. For example:
Badfor (var i = 0; i < somearray.length; i++) { var container = document.getElementById (' container '); container.innerhtml + = ' My number: ' + i; Console.log (i);}
Notice how we must determine the length of the array for each iteration, and how we traverse the DOM to find the "Containe R "element each time-highly inefficient!
Bettervar container = document.getElementById (' container '); for (var i = 0, len = somearray.length; i < Len; i++) { container.innerhtml + = ' My number: ' + i; Console.log (i);}
Bonus points to the person who leaves a comment showing us how we can further improve the code block above.
7. The fastest to Build a StringDon ' t always reach for your Handy-dandy "for" statement if you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...]; var list = ' <ul><li> ' + arr.join (' </li><li> ') + ' </li></ul> ';
I won ' t bore you with benchmarks; You ' ll just has to believe me (or test for yourself) –this are by far the fastest method!
Using native methods (like join ()), regardless of the "s" going on behind the abstraction layer, is usually much faster tha N any non-native alternative.
-James Padolsey, james.padolsey.com
8. Reduce Globals
"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other APS Plications, widgets, or libraries. "
-Douglas Crockford
var name = ' Jeffrey '; var lastName = ' the ' "; function dosomething () {...} Console.log (name); Jeffrey--or Window.name
Bettervar dudenamespace = { name: ' Jeffrey ', lastName: ' by ', ' dosomething:function ' () {...}} Console.log (Dudenamespace.name); Jeffrey
Notice how we have "reduced our footprint" to just the ridiculously named "Dudenamespace" object.
9. Comment Your CodeIt might seem unnecessary at first, but trust me, you want to comment your code as best as possible. What happens if you return to the project months later, and only to find so can ' t easily remember what your line of th Inking was. Or, what if one of the your colleagues needs to revise your code? Always, always comment important sections of your code.
Cycle through array and echo out each name. for (var i = 0, len = array.length; i < Len; i++) { console.log (array[i]);}
Embrace Progressive enhancementAlways compensate-when JavaScript is disabled. It might is tempting to think, "the majority of my viewers has JavaScript enabled, so I won ' t worry about it." However, this would is a huge mistake.
Taken a moment to view your beautiful sliders with JavaScript turned off? (Download the Web Developer Toolbar for a easy-to-do.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript would be disabled. Then, the once you ' ve do so, the begin toprogressively enhance your layout!
One. Don ' t Pass a String to "setinterval" or "SetTimeOut"Consider the following code:
SetInterval ("document.getElementById (' container '). InnerHTML + = ' My new number: ' + i ', 3000);
Not only was this code inefficient, but it also functions in the same as the "eval" function would. never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.
SetInterval (SomeFunction, 3000);
Don ' t use the "with" StatementAt first glance, ' with ' statements seem like a smart idea. The basic concept is this they can be used to provide a shorthand for accessing deeply nested objects. For example ...
With (being.person.man.bodyparts) { arms = true; Legs = true;}
–instead of–
Being.person.man.bodyparts.arms = true;being.person.man.bodyparts.legs= true;
Unfortunately, after some testing, it is found that they "behave very badly when setting new members." Instead, you should use Var.
var o = being.person.man.bodyparts;o.arms = True;o.legs = true;
Use {} Instead of New Object ()There is multiple ways to the Create objects in JavaScript. Perhaps the more traditional method was to use the ' new ' constructor, like so:
var o = new Object (); o.name = ' Jeffrey '; o.lastname = ' the ' "; o.somefunction = function () { console.log (this.name);}
However, this method receives the ' bad practice ' stamp without actually being so. Instead, I recommend that's the much more robust object literal method.
Bettervar o = { name: ' Jeffrey ', lastName = ' to ', somefunction:function () { console.log (this.name); }};
Note that if you simply want to create an empty object, {} 'll do the trick.
var o = {};
"Objects literals enable us to write code this supports lots of features yet still make it a relatively straightforward fo R the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc. "–dyn-web.co M
Use [] Instead of New Array ()The same applies for creating a new array.
Okayvar a = new Array (); a[0] = "Joe"; a[1] = ' Plumber ';
Bettervar a = [' Joe ', ' Plumber '];
"A common error in JavaScript programs are to use an object when an array is required or an array when an object is require D. The rule is simple:when the property names be small sequential integers, you should use an array. Otherwise, use an object. "–douglas Crockford
The. Long List of Variables? Omit the "Var" Keyword and use commas Insteadvar Someitem = ' some string '; var Anotheritem = ' another string '; var onemoreitem = ' One more string ';
Bettervar Someitem = ' Some string ', Anotheritem = ' Another string ', Onemoreitem = ' one more string ';
... should be rather self-explanatory. I doubt there ' s any real speed improvements here, but it cleans up your code a bit.
All, always use semicolonsTechnically, most browsers would allow you to get away with omitting semi-colons.
var Someitem = ' Some string ' function dosomething () { return ' something '}
Have said that, the is a very bad practice that can potentially leads to much bigger, and harder to find, issues.
Bettervar Someitem = ' some string '; function dosomething () { return ' something ';}
"For-in" statementsWhen the looping through items in a object, you might find this you'll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information
For (key in object) { if (Object.hasownproperty (key) { ... then do something ... }}
As referenced from Javascript:the good Parts, by Douglas Crockford.
Use Firebug's "Timer" Feature to Optimize Your CodeNeed a quick and easy-to-determine how long a operation takes? Use Firebug's "timer" feature to log the results.
function Timetracker () {console.time ("MyTimer"), for (x=5000; x > 0; x--) {} console.timeend ("MyTimer");}
Read, read, read ...While I ' a huge fan of the Web development blogs (like this one!), there really isn ' t a substitute in a book when grabbing s ome lunch, or just before you go to bed. Always keep a web development book on your bedside table. Here is some of my JavaScript favorites.
- Object-oriented JavaScript
- Javascript:the Good Parts
- Learning JQuery 1.3
- Learning JavaScript
Read them...multiple times. I still do!
self-executing Functions
Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent func tion is called. Simply Wrap your function in parenthesis, and then append an additional set, which essentially calls the function.
(function dosomething () { return { name: ' Jeff ', lastName: ' The ' " };}) ();
Raw JavaScript Can always be quicker Than Using a Library
JavaScript libraries, such as JQuery and Mootools, can save a enormous amount of time when coding-especially with A JAX operations. Have said that, always keep in mind that a library can never is as fast as raw JavaScript (assuming you code correctly).
JQuery's "Each" method was great for looping, but the using a native "for" statement would always be a ounce quicker.
Crockford ' s JSON. Parse
Although JavaScript 2 should has a built-in JSON parser, as of this writing, we still need to implement our own. Douglas Crockford, the creator of JSON, has already created a parser so can use. It can be downloaded here.
Simply by importing the script, you'll gain access to a new JSON global object, which can and be used to parse your. JSON File.
var response = Json.parse (Xhr.responsetext); var container = document.getElementById (' container '); for (var i = 0, len = response.length; i < Len; i++) { container.innerhtml + = '
- ' + response[i].name + ': ' + Response[i].email + '
‘; }
. Remove "Language"
Years ago, it wasn ' t uncommon to find the ' language ' attribute within script tags.
<script type= "Text/javascript" language= "JavaScript" >...</script>
However, this attribute have long since been deprecated; So leave it out.
That's all, folks
So there your IT; Twenty-four Essential tips for beginning javascripters. Let me know your quick tips! Thanks for reading. What subject should the third part in this series cover?
24 JavaScript Beginner Best Practices