Check javascript for missing ";" before compression - javascript

I'm doing some optimizations and decided to compress my javascript files using YUI Compressor. The problem is, that some code lines are missing ";" at the end, since javascript allows that and developers do not look too much at this.
Is it going to be a problem when code is compressed? If it is, is there a way to check javascript for lines that are missing ";"?

jsLint can check your code for that. And yes it will most likely cause issues unless the compressor actually contains a JavaScript parser and actively fixes missing semicolons.

According to this SO answer, YUI Compressor can handle it.

I've done a simple test on three JavaScript compressors: Yuicompressor, Yuglify and Google Closure Compiler. On my PC with Ubuntu 12.10, I've downloaded the binaries of every compressor, and then tested this file on every one of them:
function dbz(){
var goku = 1
var vegeta = 2
var freeza = 3
console.log(goku + vegeta + freeza)
}
dbz()
And here is the results:
Yuicompressor (2.4.7):
function dbz(){var b=1;var c=2;var a=3;console.log(b+c+a)}dbz();
Yuglify (0.1.2):
function dbz(){var e=1,t=2,n=3;console.log(e+t+n)}dbz();
Closure-Compiler (version 20121212 revision 2388):
function dbz(){console.log(6)}dbz();
Althought this is a very simple example, all of then worked fine on lines with missing semicolons. All of them detected lines without semicolons at the end, added it and removed the line break afterwards.

You could always use regexp to match for newlines that dont have a ; before them, and naturally make exceptions for stuff like empty lines, )} etc.
But to be honest, if it really doesn't already do this sort of thing automatically, seems like it really is broken \ plain bad.

Related

Is there a way to echo every line of JavaScript as it is executed?

I have two programs that should be running the same . They are not. I'd like to see where their execution diverges. Is there an option in Chrome or Firefox or Safari to log/echo every line of JavaScript as it is executed ? Or some other way to do this short of manually adding console.log every few lines? Note: the divergence is 10k or 20k maybe 100k lines deep and ideally I'd want it to print variables similar to the Chrome dev tools.
Then I can just dump the logs and find the divergence
Stepping through the code in the debugger is not a solution as it would take hours if not days to step that far.
One idea is to use a babel or uglify plugin to use the last to emit code for each line to print what it is about to do or just did.
Another idea is if there is a way to dump all of memory from js so I can compare all objects and all references. They should be the same so when I see two dumps that differ I'll have found my bug. note: JSON.stringify is not an option as I need to see all variables/objects/classes etc.
Note: I'm not looking for basic answers like "use console.log" or "step in the debugger". I appreciate the help and maybe I've overlooked something simple but I do have quite a bit of JavaScript experience.
Maybe an example would help. Imagine you got the source to an app as large as google docs. You run some processor over it that's not supposed to break anything or change anything. Except it does. You look at the changes and can't see anything wrong. All you know is when you run it it runs but a few things are subtly broken. So you put a breakpoint there and see the data is bad. But when did it go bad? You don't know the code (you just got it). It could have been 100s of thousands of lines before. You have no idea where to put breakpoints or console.logs. It could take weeks. But, given you know the code should run exactly the same if you could print all lines of execution you'd find the bug in minutes instead of days.
You can add debugger; at the begin of the function() or where you want and open the console.
When the debugger is reached it stop the execution. After that you can execute code step by step and add some watches.
It works fine with all recent browser.
Example :
function test()
{
var rand = Math.random();
debugger;
return rand;
}
test();
It is node js but it may be helpful for you. set the NODE_V8_COVERAGE environment variable to a directory, coverage data will be output to that directory when the program exits.
https://blog.npmjs.org/post/178487845610/rethinking-javascript-test-coverage

Are commas necessary in Node.js?

Are there risks incurred when omitting commas in variable declarations for node.js? For example, declaring some global variables like the following works just fine:
express = require('express')
jade = require('jade')
And I don't want to write commas if it's safe not to write them (I don't care about "beauty/clarity of code" arguments).
Important: I mean commas, not semicolons (got 3 answers about semicolons). It's perfectly OK and even recommended to remove semicolons from node.js. The creator of npm also does it: http://blog.izs.me/post/3393190720/how-this-works
If in doubt, check the latest javascript specs: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Note that you also don't need to write
var
for global variables.
But this question is about "commas" so please don't replace commas by semicolons by mistake when editing my question (done before).
In JavaScript, if you don't write semicolons ; they will be inserted for you, invisibly. And you may not always like where they go.
You are not technically required to end every statement with a semicolon. However, most consider it a good idea.
For more info, peruse through the results of this google search. We've been arguing about this topic for a long time.
Here's an example of why this is more complex than it appears at first glance. While you are not technically required to end every statement with a semicolon, there are a few cases where you MUST, or things break. You cannot completely omit them in most codebases.
foo.def = bar
(function() {
// some self executing closure
})()
Looks simple enough right? Well the interpreter looks at that and does this:
foo.def = bar(function() {
// some self executing closure
})()
Which is probably not what you were expecting. The way to fix it, is with a semicolon.
foo.def = bar;
(function() {
// some self executing closure
})()
There a lot of cases like this. You can either learn them all, and only use them in those cases, and when you inevitably forget you try to debug your code that's doing something so strange and bizarre that you tear your hair out hours... "what do you mean wtfvar is not a function?!? It's not supposed to be a function!"
Or you can just use semicolons with consistency.
In short, no. The problems you are likely to run into will arise when you go to do things like code minifying and the compiler thinks that your two statements are one. Anyhow, if you choose not to use commas/semicolons, which is absolutely not recommended, you should be fine.
Node.js uses the V8 engine to read your code so it will pretty much behave like in Google Chrome. That said, not using semicolons is generaly a bad practice. The interpreter will try to understand your code and may be sometime mistaken (by your fault).
Check this out for a full explanation: Do you recommend using semicolons after every statement in JavaScript?
This very late answer just goes to clear confustion for others that might read this.
Since you're actually talking about commas, not semi-colons, I can only assume that you have a misunderstanding of what is implicitly being added by the engine.
Commas are not optional. And this code:
express = require('express')
jade = require('jade')
is being implicitly converted into this:
var express = require('express');
var jade = require('jade');
not this, which you might be expecting:
var express = require('express'),
jade = require('jade');

Javascript obfuscator / minifier for projects using JQuery

what is the best JS minifier / obfuscator to use for projects that use JQuery? I'm currently using the closure compiler and I've also tried YUI but they never seem to minify and optimise my function names or variable names, effectively all they do is remove whitespace and comments whereas I'm trying to make my code as small as possible and hide as much as possible.
Any ideas?
Thanks
Take a look at the closure compiler again.
It has 3 execution levels
Whitespace only You used this setting. Just redundant whitespaces are removed.
Simple In addition to removing whitespaces this renames your variables and function names to shorten the overall scripts, but leave your code intact.
Advanced This further improves the simple setting by possible restructuring your code. So, e.g., some functions may get inlined etc.
Closure is a good minifier. Also there are other minifiers worth to check,
Packer: http://dean.edwards.name/packer/
JSMin: http://crockford.com/javascript/jsmin

Automatically Fix "missing semicolon before statement"

I have a large javascript file that is missing a lot of semicolons. It works fine as it is, but when I try to use a minifier = kaboom! Is there a way to automatically fix this? I tried to go manually through it but it's not humanly possible.
check out the JavaScript Lint application that checks your script for common errors (semicolon, curly brackets, trailing decimals, nested comments, etc.)

JavaScript code completition done right?

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?
I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>
The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Categories

Resources