Start all javascript scripts with ;? [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it good practice to start all JS files with a semi colon to account for any bad scripts included before it? Or don't bother?
Thanks
;(function(){ /* my script here */ })();

Do bother, more and more people leverage the power of ASI and write semicolonless JavaScript. In semicolonless JS world that's the "rule", you put a semicolon before raw expressions, like ;(), or ;[] or ;//, as well as after 'use strict'; and omit them everywhere else. Raw expressions are not very common, except the typical IIFE.
Even if you write JS with semicolons, that particular one is safe and will do more good than bad.

not a good idea:
hide errors
stuff wont work on your site with no clear indication as to why
see no reason to use faulty scripts.

Instead, start all your scripts with "use strict"; which on some browsers will check your scripts for some error-prone practices, and interestingly I believe it will have a similar effect as the ; for closing any outstanding statements from faulty scripts included prior.

The leading semicolon is actually pretty useful if you split and decouple a lot of code into several javascript files, which you at some point, concatenate to create a production file.
It will simply help to avoid errors in constructs like
(function() {
}())
if all your files are wrapped in constructs like this, it fill fail without any semicolon, separating them. Other than that, there isn't much value in that pattern.

I usually don't bother, but, if you want to be really safe, then do it. If you are using somebody else's library, I would probably do it, but, then again, it is your choice.

Related

Naming convention to use for singletons in javascript [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

Reasoning behind the default jQuery alias ($) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been thinking a lot about the way that jQuery is implemented in Javascript code. Libraries such as jQuery and Prototype bind to an alias by default; for these examples, they use the dollar sign $. (Underscore, appropriately, uses an underscore character _.)
I understand how this works. I also understand that many libraries provide a noConflict mode.
My question is, why do these libraries use an alias by default?
From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial. (Honestly - I'm a little biased, because I don't have issues typing long variable names.) I thought that maybe it was for filesize purposes, but with the proliferation of minifiers, it seems like it'd be a moot point (and a form of premature optimization).
On the flip side, the aliases seem to cause a lot of confusion for people using these libraries.
Now, I'm not really arguing against the use of aliases - I'm just wondering why it's the default option for these libraries. Currently, to avoid an alias, we explicitly have to declare that we don't want to use it. Are there specific benefits that I'm missing about the use of aliases for library calls? The only advantage that I could readily think of is if you somehow wrote cross-library code - to swap libraries, you simply swap the alias. I don't think I've ever seen this done, though.
Anyone know the reasoning behind this? I, for one, would really love to know.
"From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial."
That's what the people who designed VB thought too. "What's this
for (int i=0; i<10;i+=2){
}
Stuff! What's wrong with:
For i as Integer = 0 To 10 Step 2
Next i
So I save 13 keystrokes! That's trivial."
It's not trivial when this is what we do all. day. long.
Take the jQuery Cycle plugin: http://malsup.github.com/jquery.cycle.all.js. It has 400 instances of $. If you were to use jQuery instead of $, that would be an extra 2000 keystrokes. It's the reason why IDEs now perform autocomplete of parens, etc. etc. etc.
Using jQuery and Prototype together is not good idea. Ideally there must be only 1 javascript framework for the site, and a lot of calls to it. So the best (default) choice is to use shorthand alias for it's main function.
Anyway, if you need to use several libraries/frameworks together on the same page, and you want to avoid conflicts, you can use noConflict mode.

JavaScript Performance Evaluation [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
background:
I've searched around for a reference, or possibly a tool, that helps you theoretically evaluate the efficiency (resource cost) of your JavaScript. This search has turned up a lot of excellent debugging software, but I can't really find something that helps me optimize the code, by utilizing less resource-intensive methods.
question:
Is there any resource (online guide, list, database, book, anything) or perhaps some software (web-based, browser plugin, IDE extension) that will help you optimize your JavaScript?
example:
innerText in IE / textContent in Firefox requires far fewer resources than innerHTML in either browser.
That one is kinda common sense, because it's less powerful, but there are other comparisons I hear about on a daily basis, and can't really verify if they are in fact better for optimized code or more efficient, and even if I could I have no way to test it!
Any ideas?
In the same line as strife25, firebug has a very handy method of measuring time without handling any dates. Just use this:
console.time("Your timer name");
//Execute some javascript
console.timeEnd("Your timer name");
Then, check the console.
alt text http://aquate.us/u/62232567893647972047.jpg
Edit -- off by 30 odd seconds. :(
the usual way to evaluate Javascript is by evaluating the amount of time it takes for a set of code to execute:
var begin = new Date().getTime();
//do stuff
console.debug( new Date().getTime() - begin );
However, there are some issues with this in IE. if a script takes <15ms to run, IE returns 0ms as the result.
Various javascript libraries have testing frameworks to help evaluate your code's speed. Dojo's testing framework is called DOH.
John Resig also made a firebug plugin called FireUnit which allows you to easily evaluate the time it takes for a function to execute, and with a little configuring, also outputs the Big O of a function, which is a great piece of data.
Check out Resig's video from JSConf on JS performance testing:
Measuring Javascript Performance - John Resig
FireUnit rundown
I always liked the simple approach with Firebug:
console.time("timer-name");
and
console.timeEnd("timer-name");
Good for granular level measurements.
Firebug's 'profile' tool is great for measuring javascript performance. It shows you all the bottlenecks in your code in a function by function breakdown, showing which one's had the highest average time, most calls, etc.
Profiler in IE8 is amazing. It gives you a tree view along with the Inclusive time (in ms)

JavaScript naming conventions [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

What good is JSLint if jQuery fails the validation [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have been exploring different methods to clean up and test my JavaScript. I figured just like any other language one way to get better is to read good code. jQuery is very popular so it must have a certain degree of good coding.
So why when I run jQuery through JSLint's validation it gives me this message:
Error:
Problem at line 18 character 5:
Expected an identifier and instead saw
'undefined' (a reserved word).
undefined,
Problem at line 24 character 27:
Missing semicolon.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Expected an identifier and instead saw
'='.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Stopping, unable to continue. (0%
scanned).
This was done using JSLint and jquery-1.3.1.js
JSLint tests one particular person's (Douglas Crockford) opinions regarding what makes good JavaScript code. Crockford is very good, but some of his opinions are anal retentive at best, like the underscore rule, or the use of the increment/decrement operators.
Many of the issues being tagged by JSLint in the above output are issues that Crockford feels leads to difficult to maintain code, or they are things that he feels has led him to doing 'clever' things in the past that can be hard to maintain.
There are some things Crockford identifies as errors that I agree with though, like the missing semicolons thing. Dropping semicolons forces the browser to guess where to insert the end-of-statement token, and that can sometimes be dangerous (it's always slower). And several of those errors are related to JSLint not expecting or supporting multiple assignments like jQuery does on line 24.
If you've got a question about a JSLint error, e-mail Crockford, he's really good about replying, and with his reply, you'll at least know why JSLint was implemented that way.
Oh, and just because a library is popular doesn't mean it's code is any good. JQuery is popular because it's a relatively fast, easy to use library. That it's well implemented is rather inconsequential to it's popularity among many. However, you should certainly be reading more code, we all should.
JSLint can be very helpful in identifying problems with the code, even if JQuery doesn't pass the standards it desires.
JSLint helps you catch problems, it isn't a test of validity or a replacement for thinking. jQuery is pretty advanced as js goes, which makes such a result understandable. I mean the first couple of lines are speed hacks, no wonder the most rigid js parser is going have a couple of errors.
In any case, the assumption that popular code is perfectly correct code or even 'good' is flawed. JQuery code is good, and you can learn a lot of from reading it. You should still run your stuff through JSLint, if only because it's good to hear another opinion on what you've written.
From JSLint's description:
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 is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language.
"jQuery is very popular so it must have a certain degree of good coding."
One would like to hope this is the case with jQuery, but unfortunately it's not really true. jQuery is useful and popular, but it is not a well written JavaScript library. David Mark recently posted a scathing critique of jQuery in comp.lang.javascript that examines a large number of examples of the poor code found in jQuery:
http://groups.google.com/group/comp.lang.javascript/msg/37cb11852d7ca75c?hl=en&
If you're not actively developing jQuery itself, why even run JSLint over it at all? If it works, it works, and you don't have to worry about it.
The jQuery developers' goals are not the same as your goals. jQuery is built for speed and compactness and achieving those goals trumps readability and maintainability.
Crockford's tests in JSLint have more to do with achieving something that he would feel comfortable taking home to meet his mother, which is a valid concern if you will be married to your code for some time.
The purpose of JsLint is clearly stated in the FAQ [1]:
"JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language."
Now if you are confused: ECMA3 is already a subset of the JS capabilities provided by any of todays JS interpreters (see [2] for an overview of the relation between JavasScript and ECMAScript versions)
To answer the quesition "what good is JSlint":
* use JsLint to verify you are using a "safe" subset of Javascript that is unlikly to break accross JS implementations.
* use Jslint to verify you followed the crockford code conventions [4]
[1] http://www.jslint.com/lint.html
[2] https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/JavaScript_Overview#Relationship_between_JavaScript_Versions_and_ECMAScript_Editions
[3] https://developer.mozilla.org/en/New_in_JavaScript_1.7#Avoiding_temporary_variables
[4] http://javascript.crockford.com/code.html
I've found one case where JSLint is very, very useful: when you grab one of those big-arse libraries that float around the 'Net, then another, then again one other, you soon find yourself loading 50k of Javascript on every new page load (caching may help, but it's not a cure-all solution).
What would you do then? Compress those libraries. But your host doesn't do compression for non-html file! So what? You use a Javascript compressor.
The best I've found is Dean Edward's; I used it to compress John Fraser's Showdown (a Markdown for Javascript library), but unfortunately, the compression broke the code. Since Showdown isn't supported anymore, I had to correct it myself - and JSlint was invaluable for that.
In short, JSlint is useful to prepare your JS code for heavy duty compression.
If you like to daisy-chain methods like jQuery allows you, you might appreciate YUI3.
JQuery is of course not the best thing in the world. That's already clear when you look at the notation. The dollar parentheses combination is really bad for your eyes. Programming should be clear and simple. JQuery is far from that. That reason is enough for me not to use it. That it's not properly written doesn't surprise me and only underscores my thoughts on this JavaScript library.

Categories

Resources