Should JavaScript minifiers automatically combine var declarations? - javascript

I just discovered that YUICompressor (2.4.7) does not combine var declarations. For example,
var x = 1;
var y = 2;
compresses to
var a=1;var b=2;
I assume it would be reasonable to expect a minifier to be able to combine consecutive var declarations, like so:
var a=1,b=2;
But my real question is is it reasonable to expect/possible (for a minifier) to automatically and safely combine non-consecutive var declarations in a single function?

It depends. If you're talking about declarations with initialization then: No.
Consider this:
(function () {
var x = 1;
console.log(y); // undefined
var y = 2;
})();
(function () {
var x = 1, y = 2;
console.log(y); // 2
})();
However, the following is safe and should be done by minifiers:
(function () {
var x = 1, y;
console.log(y); // undefined
y = 2;
})();
It is certainly possible; the compressor scans the whole function for contained var statements prior to generating output. This is necessary to compress variable names.
Note that there is one possible tricky variant, which consists in extending the parameter list, and thus saving extra bytes by completely eliminating any var statements:
(function (x,y) {
x = 1;
console.log(y); // undefined
y = 2;
})();
However, this changes the function's (rarely used) length property and thus is not to be expected from minifiers.

I know of one example where this would not be desirable. See this question Have I reached the limits of the size of objects JavaScript in my browser can handle?
That question was about a bug when the initialization of a variable happened in a single var statement. The question was about assigning a really gigantic literal to a variable which failed. The solution in the end was to split the object into separate var declarations.
Therefore, if compressors always did that, that would cause your code to be more likely to run into that kind of problem

Related

Curly brackets usage without condition [duplicate]

In Javascript, you can have lonely code blocks, that is, code blocks without an if, function or something like that preceding them, placed arbitrarily in the code, like this:
var a = 3,
b = 4;
{
a = 50;
b = 50;
}
alert(a + b); //alerts 100
I know some other languages have this (I think C++ does), and they use it for scope control: variables declared inside the lonely code block cannot be accessed outside of it. But since Javascript has function scope rather than block scope, you have to use a self-executing function (function(){})() to acheive the same effect.
Is there a purpose for this construct? Have you ever seen anybody use it? Does the spec mention it? Is this just a side effect of the grammar having some sort of general rule about code blocks?
As I found out after googling my answer for How are labels used with statements that are not a loop?, the lonely code blocks can be related to labels:
myLabel:
{
for(x in y) {
break myLabel;
}
}
Will break out not only of the loop, but of the outer code block as well.
Update (as this question shows up high on Google for "javascript code block"):
With the introduciton of the let keyword in ECMAScript 6, code blocks can also be used to limit scope of variables.
{
let x = 20;
alert(x) // 20
}
alert(x) // undefined
Only code readability, nothing more.
They do not even give you the advantage of closures:
var c = 'fail';
{
var c = 123;
}
alert(c); //alerts 123
(see it live)
Only readability. Other than that, nothing. Do not do this as it's not future-proof. The following will happily break:
"use strict";
var a = 3,
b = 4;
{
a = 50;
b = 50;
}
alert(a + b); //alerts 100
I used to use it myself as it allowed logical separation of functionality, but no longer do due to the above.

Mutating variables inside a function - is it abuse?

I want to know what the best practices are before I go to my colleagues for a code review.
I know that the following code works. My question is whether relying on closure this way is generally accepted in JavaScript or if there's something problematic here that I'm missing? Thanks
EDIT: updated the snippet to more clearly show what I'm trying to achieve (cleaner, more readable code)
// All this is happening inside a function. Declared vars are not global.
var x, y, z; // lots of variables to declare (to use in closures)
setupVars(true); // lots of variables to setup
useVars(); // lots of variables to use
function setupVars(condition) {
if(condition){
x = 1;
y = 2;
z = 3;
} else {
x = 4;
y = 5;
z = 6;
}
};
function useVars(){
console.log(x);
console.log(y);
console.log(z);
}
Using variables with same names as the global ones, inside a function, is not a good coding practice. In the above code, you should consider renaming x inside the function.
Otherwise, if the function is as simple as the one shown above, you could just do something like this
function modify(value){
return modified_value;
}

If babel converts let and const to var, what's the difference?

I've tried the babel transpiler, and it converts All let, const and var to just var, so in all, what's the difference in our code usage?
I have read documents and I know what's the difference between let, const and var, but if all of them are eventually converted to var, what's the difference? it means that there shouldn't be any meaningful differences in performance or even scope!
Update(02.14.2019) : Based on the answers I understood that scope does matter and even though they are converted to var, babel keeps the meaning of scope. My question remains about the performance, is there any meaningful difference in performance?
I've attached the input and output of the transpiler, with a more complex scenario
input:
let a = 1;
for (let a = 0; a !== 0;) {
for (let a = 0; a !== 0;) {}
}
output
"use strict";
var a = 1;
for (var _a = 0; _a !== 0;) {
for (var _a2 = 0; _a2 !== 0;) {}
}
Babel converts the ES6 syntax to ES5 syntax (or whatever source and target versions of JS you are dealing with).
This will often lose some of the nuances in the code, but you are looking at a very trivial example.
Consider this instead:
let x = 1;
{
// Inside a block, this is a different x
let x = 2;
console.log(x);
}
console.log(x);
Babel will convert that to:
"use strict";
var x = 1;
{
// Inside a block, this is a different x
var _x = 2;
console.log(_x);
}
console.log(x);
See how it renames the inner x so that it doesn't overwrite the outer one?
It expresses the effect of the ES6 as much as it can in ES5, even if the result is ugly (because the elegant feature from ES6 is not available).
Babel runs checks against each variable, and throws errors if certain procedural rules are violated. For example, if a const is defined, and the value is changed later, this would violate the type's rules. Another would be if a variable is redefined in a scope where it already exists (this could be a function of the same name). In some cases Babel simply renames things to prevent conflicts.

javascript var statement and performance

Option1 : multiple var without assignment
function MyFunction() {
var a = null;
var b = null;
....
var z = null;
a = SomeValue;
b = SomeValue2;
....
}
Option 2: one var statement, no assignment
function MyFunction() {
var a, b ..., z;
a = SomeValue;
b = SomeValue2;
....
}
Option 3: multiple var statements with assignment
function MyFunction() {
var a = SomeValue;
var b = SomeValue2;
....
var z = SomeValue26;
}
Is there any performance benefit of using a particular option? Is it true for both primitive type assignments AND object reference assignments?
Thanks for your input.
"premature optimization is the root of
all evil"
I don't think there will be any significant performance change with any of this options.
(IMO) The third option is the most readable option and closest to dynamic memory allocation like C# etc'. But this is my humble opinion, Choose what you like the most.
If it really bothers you and you can't sleep without an answer, test it with jsPerf.
#Chad made a jsPerf so you can sleep well tonight...
To understand the performance you should first understand hoisting. Let's take the following code:
var x = 1;
function bar(val) {
var returnVal = val * 2;
return returnVal;
}
function foo(val) {
var returnVal = 10;
returnVal *= bar(val);
return returnVal;
}
var y = foo(x);
console.log(y); // 20
Hoisting basically means that the JavaScript interpreter will 'hoist' the variable declaration to the top of its scope. Making this example look more like this:
var x, y;
x = 1;
function bar(val) {
var returnVal;
returnVal = val * 2;
return returnVal;
}
function foo(val) {
var returnVal;
returnVal = 10;
returnVal *= bar(val);
return returnVal;
}
y = foo(x);
console.log(y); // 20
So, in your examples given, Option 2 and 3 will basically do the same thing. Since the interpreter will move those declarations to the top. At that point it's a decision of preference. A lot of people avoid doing something like var x, y, z; saying it's dangerous. I, personally, do it. In whatever scope I'm in I will declare all variables at the top, and then use them below. But either way works.
Now, your first example is the least efficient. After hoisting it will look like this:
function MyFunction() {
var a, b, ... z;
a = null;
b = null;
...
z = null;
a = someValue;
b = someValue2;
...
z = someValueN;
}
It basically results in setting the variables twice.
In Chrome, execution times are identical.
The only real consideration here is optimizing network transfer.
Consider var a=1;var b=2;...;var z=9; versus var a=1,b=2,...,z=9;
If you put a ;varĀ  in front of each identifier, that's 5 bytes (assuming a single-byte character encoding), versus 1 byte for a ,. Thus, declaring 26 variables, you can save 100 bytes by writing varĀ  once and listing identifiers with commas.
Granted it's not a huge savings, but every byte helps when it comes to pushing bits over the network. It's not something to worry a great deal about, but if you find yourself declaring several variables in the same area, using the variable declaration list is an easy way to shave a few bytes off your JS file.
That seems like premature optimization, the root of all evil.
How many times will it be executed? What fraction of of the whole program will this consume?
I will counter your question about performance with a few questions:
Have you noticed an issue with performance?
Have you determined that your var statement was the bottleneck?
Have you tested each version?
I'm going to assume the answer to all of these was no.
None of the options should make any significant difference, although the only way to know for certain is to run them and test. JavaScript being an asynchronous client-side language means that you'd have to run a seriously enormous amount of code to have the var statements be a bottleneck of any sort.
In the end, if you're deciding which version to use, I would recommend using a single var statement without assignment:
function () {
var a,
b,
c,
foo,
bar,
fizz,
buzz;
a = 1;
...
b = 3;
}
The reason for this is that this is essentially how the code will be executed due to variable hoisting. I can then move the initialize statement so where the variable is first used, such as in a for loop:
function foo(arr) {
var i,
l;
...
for (i = 0, l = arr.length; i < l; i++) {
doStuff(arr[i]);
}
...
}
They all basically do the same thing: declare a variable and eventually define it (assign something to it). The only thing you're changing throughout your examples is the order in which that occurs, and even that depends on the browser that is compiling your JavaScript -- some might perform optimizations that others do not.
There are some stylistic guidelines you should follow though, and this answer explains them well. Keep in mind that that answer is technology agnostic and may not apply to JavaScript at all.
Just stay away from option 1 if possible, there is no need to make two assignments.
Even variables declared inside a for loop or other compound statement/block will be available outside its containing block.
You can also do:
function MyFunction() {
var a = SomeValue, b = SomeVavlue2;
}

What's the purpose of lonely code blocks in Javascript?

In Javascript, you can have lonely code blocks, that is, code blocks without an if, function or something like that preceding them, placed arbitrarily in the code, like this:
var a = 3,
b = 4;
{
a = 50;
b = 50;
}
alert(a + b); //alerts 100
I know some other languages have this (I think C++ does), and they use it for scope control: variables declared inside the lonely code block cannot be accessed outside of it. But since Javascript has function scope rather than block scope, you have to use a self-executing function (function(){})() to acheive the same effect.
Is there a purpose for this construct? Have you ever seen anybody use it? Does the spec mention it? Is this just a side effect of the grammar having some sort of general rule about code blocks?
As I found out after googling my answer for How are labels used with statements that are not a loop?, the lonely code blocks can be related to labels:
myLabel:
{
for(x in y) {
break myLabel;
}
}
Will break out not only of the loop, but of the outer code block as well.
Update (as this question shows up high on Google for "javascript code block"):
With the introduciton of the let keyword in ECMAScript 6, code blocks can also be used to limit scope of variables.
{
let x = 20;
alert(x) // 20
}
alert(x) // undefined
Only code readability, nothing more.
They do not even give you the advantage of closures:
var c = 'fail';
{
var c = 123;
}
alert(c); //alerts 123
(see it live)
Only readability. Other than that, nothing. Do not do this as it's not future-proof. The following will happily break:
"use strict";
var a = 3,
b = 4;
{
a = 50;
b = 50;
}
alert(a + b); //alerts 100
I used to use it myself as it allowed logical separation of functionality, but no longer do due to the above.

Categories

Resources