Why do most JavaScript frameworks use such short variable names? - javascript

I have been told to use a meaningful variable name for years. However, every time I've tried to debug some JavaScript code and dig in to the third party framework, I found that every JavaScript framework would have variable names like a, ac, b, c.
Why are such short variable names common practice? It seems like it would harm maintainability.

Its called minification. Its done in all languages but mostly JavaScript to remove all unnecessary characters from source code. Its mostly JavaScript because large JavaScript files can be made much smaller thereby loading quicker in the browser.
Most JavaScript libraries have a version available for developers that is not minified so that debugging can be done and then in production the minified version is used to reduce the transfer overhead.
When writing code you should always use sensible variables, but that's only so the developer can read it, the browser doesn't care.

You are most likely looking at minified javascript. This is the result of passing the original (and hopefully more readable) source code through a minification tool.

What you're probably looking at is minimized code. Minimizers rewrite the Javascript to take the minimum amount of space, so it will download as quickly as possible -- unnecessary whitespace is removed, variables and functions are replaced with short names, and some other tricks are used.

It might be the javascript you're debugging is minified. There's no way to convert a minified javascript to original code with meaningful names written by the author. You just use your instinct and analyzing skills to understand others code even if the keywords there are unreadable.

What you are seeing could be a minified version of the actual javascript. it is done so that the size of the file is reduced for performance reasons.
A good example is the jQuery library, you can look at the development version and minified version

As the others have said, it's the minified version. My contribution to this thread is simply to show an example.
take this example:
(function () {
"use strict";
var foo = function () {
return;
};
var bar = foo;
var baz = bar;
})();
And run it through jscompress.com. The result will be
(function(){"use strict";var e=function(){return};var t=e;var n=t})()

Related

Are JavaScript variable names changed to random letters when the file is minified?

I am learning JavaScript and one of my learning methods I use (same as html, CSS/SCSS) is to read source code to learn the language and try to understand what is happening.
But I am having trouble with JavaScript, as it's full of random letters and I can't work out what the code is doing. Is there a process of changing the JavaScript code (variable names etc...) when the file is minified and published on the web with the rest of the website files.
It depends on what minifier or optimizer you're using, but I'd assume that any quality optimizer should reduce variable names to shorter versions.
Using TerserWebpackPlugin:
// src/index.ts
const greeting = 'Hello World!'
console.log(greeting)
export default {
greeting: greeting,
}
Compiles to:
// /lib/build.js
...{return(()=>{"use strict";var e,r,n,t,o,i={607:(e,r,n)=>{n.r(r),n.d(r,{default:()=>o});const t="Hello World!";console.log(t);const o={greeting:t}}},d={};function c(e){var r=d[e];...
Variable greeting was changed to t.
Which would also make sense because if you have 10k variables in your project, each ~10 letters long, reducing it to 1 letter would be 10k * 9 = 90kb reduction in bundle size.
If you want to study javascript code then don't do it with minified versions of code, it's incredibly hard to read such code.
JavaScript, as a interpreted language, is not being compiled. One of the downsides of this is that the code is supposed to be human readable but also as small as possible in order to have fast web pages.
That's why web developer tools include "bundlers" (like Webpack or Rollup) which help reduce the number of files by grouping them, remove unused code (also known as tree-shaking) and minify the code by reducing the number of characters as much as possible while not changing the code behavior.
For example:
var variable becomes var a
true becomes !0
false becomes !1
...
Even global objects can be minified by using this pattern:
(function(window) {
// You can write code that uses window while window is eligible to minification
// Because it's a regular variable in this context
})(window)
Many other minification techniques exist...
When the code has been minified, it's impossible to revert, unless it has been built with source maps which make the code look like it's not minified in the debugger.
If source maps don't exist for the code you are reverse engineering, then you don't have any solution unless the source code is public. In that case you'll probably be able to find it on https://www.github.com

Can i publish my javascript file in minimal mode and hard to read by others? like jquery library

Sample my code
function doit(){
var num=num1+num2
}
After publish i want like in abstract format. Like -
function a(){var b=c+d}; //should not be easily readable
Yes all these minifiers do is rename functions and variables to obfuscated names so they have no meaning to anyone reading them. Then they remove all indentation, line returns, and unnecesary spaces. I personally use jsMIN and ocassionally this online tool. http://javascript-minifier.com/

How to display all JavaScript global variables with static code analysis?

I know that I can type into Chrome or FF the following command:
Object.keys(window);
but this displays DHTMLX stuff and also function names in which I'm not interested in. And it doesn't display variables in functions that have not been executed yet. We have more than 20,000 lines of JavaScript codebase, so I would prefer static code analyis. I found JavsScript Lint. It is a great tool but I don't know how to use it for displaying global vars.
So I'm searching for memory leaks, forgotten var keywords, and so on...
To do [only] what you're asking, I think you're looking for this:
for each (obj in window) {
if (window.hasOwnProperty(obj)) {
console.log(obj);
}
}
I haven't linted that code, which is unlike me, but you get the idea. Try setting something first (var spam = "spam";) and you'll see it reported on your console, and not the cruft you asked about avoiding.
That said, JLRishe is right; JSLint executes JavaScript in your browser without "phoning home", so feel free to run it. There are also many offline tools for JSLinting your code. I use a plugin for Sublime Text, for instance.
If you'd like some simplest-case html/JavaScript code to "wrap" JSLint, I've got an example here. Just download the latest jslint.js file from Crockford's repository into the same directory, and poof, you're linting with a local copy of JSLint.js. Edit: Added code in a new answer here.
Though understand that you're linting locally with that wrapper or when you visit JSLint.com. Honestly, I can say with some confidence, Crockford would rather not see our code. ;^) You download JSLint.js (actually webjslint, a minified compilation of a few files) from JSLint.com, but you execute in the browser.
(Admittedly, you're technically right -- you never know when that site could be compromised, and to be completely on the up and up, you sh/c/ould vet jslint.js each time you grab a fresh copy. It is safer to run locally, but as of this writing, you appear safe to use JSLint.com. Just eyeball your favorite browser's Net tab while running some test, non-proprietary code, and see if any phoning happens. Or unplug your box's network cable!)
Rick's answer to use "use strict"; is another great suggestion.
A great way to catch undeclared variables is to add 'use strict' to your code.
The errors will appear in the console, or you could display them in a try ... catch block:
'use strict';
try {
var i= 15;
u= 25;
} catch(ee) {
alert(ee.message);
}
I found a very good solution to list all the global variables with the jsl command line tool:
Here is the documentation
I just have to put /*jsl:option explicit*/ into each file that I want to check. Then it is enough to run ./jsl -process <someFile> | grep 'undeclared identifier'
It is also possible to use referenceFile that contains some intentional global variables /*jsl:import <referenceFile>*/ so these variables will not be listed.

Unminify / Decompress JavaScript

Original Question
This maybe a stupid question but is there a way in VS 2013 to unminify JavaScript?
Just making sure we are all on the same page here.
Minify:
var flashVer=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?"
That's just an example to make sure we all know what I'm on about. As far as I can tell there is no way to be able to do this. I have only been using VS 2013 for around 3 weeks so there is probably still stuff that is hidden to me.
If there is no way to do this within the program what is the next best thing for this?
I did see on another similar post that recommends the site http://jsbeautifier.org/ , so may have to give that ago but would make life easier if it was built into VS 2013
Thanks in advance as I know someone will be able to help me out here.
Update:
I have looked around VS 2013 and found nothing that can help me with this problem, like I said before they maybe some things I have missed (certain settings) so I guess if it cannot be done in VS what's the next best thing for the job? I seem to run into a fair amount of JS that is minifed and would like the quickest and best way to get the job done. I couple sites I have tried seem to have problems with it, is there a program I could install that would just allow me to short cut it with a hot-key or something. That would be pretty handy.
Update 2:
So I think its safe to say this cannot be done within VS2013, or for that matter at all due to missing var names and so on. So I have seen a few links and programs that allow you to format the code. Is there a way to do with within VS2013? And again if not what is the most reliable website/program that I can use to do this. Like I said I can see there have been answers and I appreciate all of them. I will be leaving this question open for a while to get more people to look at it and possibly give a better answer. Keep it up guys!
Update 3:
If anyone has any more information on this please do share. I am still looking around now and then waiting for someone to come up with something amazing for this. One day people.... One day!
The thing is that you cannot really "unminify" your code since some data was already lost - e.g. variable names. You can reformat it to more readable form though.
According to this question, since VisualStudio 2012 you can just use Ctrl+E, D keyboard shortcut
If the above is not right, there is this extension for VS 2010: http://visualstudiogallery.msdn.microsoft.com/41a0cc2f-eefd-4342-9fa9-3626855ca22a but I am not sure if it works with VS 2013
There is an extension to VisualStudio called ReSharper which can reformat javascript in a few different manners.
Also there are online formatters already mentioned in other answers (if your code is confidential, I would advise some paranoia manifested by downloading sources and using them locally).
Also you may always try to find unminified version of desired library on the interwebs
Also, there is the WebStorm IDE from JetBrains that is able to reformat JS - you may download a trial for the sole purpose of reformatting your minified scripts :)
If that's just to make debugging easier, you may want to use source maps
Also, here is a bunch of related questions:
How to automatically indent source code? <-- this is for VS2010, but it looks promising, maybe it will help you if it supports JavaScript (and it does since VS2012 according to MS support):
Ctrl+E, D - Format whole doc
Ctrl+K, Ctrl+F - Format selection
reindent(reformat) minimized jquery/javascript file in visual studio
Visual Studio 2010 can't format complex JavaScript documents
Visual Studio code formatter
how to make visual studio javascript formatting work?
I am not sure if they figured out a working way to reformat JS, but I've seen a few answers which might be helpful - I am just pasting this in here just FYI.
Added 03.06.2014:
http://www.jsnice.org/
This tool could be useful too, it even tries to infer minified names. As stated on their website:
We will rename variables and parameters to names that we learn from thousands of open source projects.
Personally I can't think of a reason to ever unminify code^:
If you're using a compiled js file (a-la google closure) and want more readable code to debug, use source maps available for well-supported libraries (speaking of jQuery, if it is served from a google CDN it already maps to the correct source)
If you're using a whitespace-only minified js file and want more readable code to debug, you could just toggle pretty print in-browser. This seems to best fit your question.
If you're using either of the above and want to modify the source code for a third-party js file, don't. Any future release will cancel out your change - instead consider one of the many patterns to extend a framework (or, perhaps, do some duck punching depending on the exact scenario.)
The other answers seem to cover the "unminification" process (maxification?) well, but it's worth making sure it's a necessary step first.
^ - Except when version control falls over, there are no backups and the only version of the file left is a minified copy in browser cache. Don't ask.
Its just a one way transformation .... sorry in normal cases you will not get something understandable back from minified JavaScript !
Make just a quick look at JQuery source for a second:
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.2",
------
And now at the minify source:
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,
l=e.jQuery,u=e.$,c={},p=[],f="1.10.2", ....
I think now you see it =>
window => e
undefined => t
readyList => n
rootjQuery => r
core_strundefined => i
location => o
document => a
So its mapped somehow to make it more shorter look here to minify something
People normally use this so there is no way back
you can just format it look here
If the code has only been minified then the best you can do automatically is reformat to make it more readable. One way of doing this is using an online formatter/beautifier. E.g. Copy and paste the line of code you posted into http://jsbeautifier.org/ or http://www.jspretty.com/ and it'll produce something like this:
var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"]
|| navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? ""
But of course what these don't do is put any comments that have been removed by the minifier back in. And if the code has also been obfuscated then it will be a lot less readable since the variable names will have changed (e.g. var a instead of var flashVer). See here for further details.
As you can see from the other answers, there is no way to reconstitute minified Javascript back into its original form, it is a lossy compression. The best you can do is make it readable by reformatting it.
If the code is open source, then it is likely that the code will exists in a raw state on some form of version control site or as a zip. Why not just download the raw version if available?
There is an online tool to unminify Javascripts
http://jsbeautifier.org/
And also for CSS
http://mrcoles.com/blog/css-unminify/

Renaming variables in JavaScript

I've been stuck with the unpleasant task of "unminifying" a minified JavaScript code file. Using JSBeautifier, the resulting file is about 6000 lines long.
Ordinarily, the variable and parameter names would be permanently lost, but in this case, I have an obsolete version of the original file that the minified JavaScript code file was generated from. This obsolete version of the original file contains most of the code comments and variable names, but absolutely cannot be used in place of the current version.
I would like to know if there is some way of renaming all instances of a particular parameter or variable in JavaScript. Since minification reduces the names to a single character, find-and-replace is impossible.
Is there some tool out there, which I can tell, in this file, the parameter a to function foo should be clientName and have it semantically rename all instances of that parameter to clientName?
Unfortunately, I work for a large organization with an approved list of software and I am stuck with Visual Studio 2010 for the forseeable future (no VS 2012).
Update: #Kos, we don't use Git, but we do use source control. The problem is that a developer who doesn't work for my organization anymore once made changes to the file, minified it, and only checked in the minified version to source control, so his changes to the original have been lost.
I'm a year late for this answer, but I had a similar problem to yours so I built this: https://github.com/zertosh/beautify-with-words. It unminifies code using UglifyJS2 but uses a phonetic word generator to rename variables. You get "long-ish" variable names so it's a breeze to do a find-and-replace. Hope this helps someone else!
You might have another way out.
Check out the last unminified version of the code. Compare to the minified version. Arguably most of it should be the same modulo consistent variable renaming. The differences you'll have to rename and remerge.
Diff won't do this kind of compare; you need tools that compare the programs as code, not text. Our SmartDifferencer tool will do this (by using language-specific full parsers to generate ASTs, and then comparing the ASTs); in effect, it compares the programs in spite of whitepspacing. SmartDifferencer also handles renaming; if two file are identical modulo a single renaming, that's what SmartDifferencer tell you.
I don't know how well this work work out; we haven't tried SmartDifferencer with 6000 lines of "consistently renamed" variables.
I found that a Visual Studio extension we've licensed here called "Telerik JustCode" has functionality to do what I want.

Categories