What is the point of using an empty statement in JavaScript?

I tried to find good resources in an empty instruction, but nothing seemed to appear. Even at MDN , they have nothing to say about it.

ie:

for(var i = 0; i < a.length; a[i++] = 0); if((a==0) || (b == 0)); 

I would like to know what are real examples of the need to use empty statements in my project. What is the reason for this?

+5
source share
7 answers

The examples you provided do not make much sense. They are better to write

 for (var i = 0; i < a.length;) a[i++] = 0; for (var i = 0; i < a.length; i++) a[i] = 0; ; // the comparisons really don't do anything (assuming a and b are no objects) (a==0) || (b = 0); // Oh wait, that the one given by @Shomz if (a != 0) b = 0; 

However, for an empty operator, there are real-world applications. I just list 3 that come to my mind:

+2
source

no / laziness. there is no difference in

 for(var i = 0; i < a.length;) a[i++] = 0; 

and only minimal difference with

 for(var i = 0; i < a.length; i++) a[i] = 0; 

the first one is several ms faster after several billion iteration steps; aka. premature optimization

EDIT:

 if((a==0) || (b == 0)); 

it makes no sense as it does nothing.

but expressions like

 a==0 || (b=0); //or maybe sth like this: //var noop = ()=>void 0; //FYI typeof a === "function" || (a = noop); 

they are very useful to me because they are short and readable, and the additional if-statement does not add any meaning to readability or understanding (at least as soon as you know this template).

+2
source

The first explicitly passes through the array and assigns all values ​​to zero, without having the code specified in the instruction.

The other looks like a typo because it is useless.

However, something like

 if((a==0) || (b = 0)); 

would make sense because it would assign b zero if a not equal to zero.

 var a = 1, b = 1; if((a == 0) || (b = 0)); alert("a: " + a + ", b: " + b); 
+1
source

I do not think they are really useful, but I could be wrong. You can try to use the side effects of evaluating conditions in if, but I do not see sufficient reason for this.

+1
source

My favorite use is to wait for the condition to become true.

 while ( !condition ); // do what happens once your condition is met 

It's nice to read, in my opinion, but the same thing can be done with { } instead of an empty statement.

+1
source

First example for(var i = 0; i < a.length; a[i++] = 0); IMO is useful and the reasons would be as follows:

  • Writing less without sacrificing readability.
  • beauty!
  • Telling people: Hey, I'm talking about the JS encoder. :)

The second if((a==0) || (b == 0)); it seems to mean nothing.

0
source

Suppose you have two functions X and Y , and suppose that Y should only be executed when X returns true , in this situation you will write:

 if( X() && Y() ); 
0
source

Source: https://habr.com/ru/post/1240806/


All Articles