A Absence of semicolons in CSS and Javascript can influence the operation of the code?

8

I always leave my css and javascript code minified but never noticed the generated output. Well, I noticed that the last rule of a selector (in css) and the last function (in javascript) always misses the semicolon. For example, a simple rule in css:

div {
  border: 2px solid red;
  color: #fff;
}

I would stay:

div{border:2px solid red;color:#fff} /*perdendo o último ponto e vírgula */

Another example, in javascript:

$(function(){
   var foo = true;

   if(foo) {
     foo = false;
     bar();  
   }
});

Will generate:

$(function(){var foo=true;if(foo){foo=false;bar()}}) /* sem os últimos ponto e vírgula */

In case there is only one function within a block, it also loses the score.

if(foo){
  bar();
}

Turns:

if(foo){bar()}

My question on the subject is: The absence of these multiple semicolons can influence in some way the code's functioning? I did tests on simple codes but I'm wondering if I can have problems with more complex work.

    
asked by anonymous 28.10.2014 / 14:45

2 answers

8

CSS

For CSS, I see no problem removing ; from the last property of a rule. Since the closing key comes after it, there is no way to be a problem. The minifier probably does this to reduce the file size by saving one character per rule.

JavaScript

In JS, the default rules of ; are more complex. Removing the semicolon just before the block closes does not seem to me problematic, but other cases can be. Your example of $(function...) , for example. Let's simplify and see where it can give trouble. Basically what you have is a function call:

funcao()

This can be problematic if another file is concatenated after that. The minifier does not know what the function does. What if it returns a function? For example:

function funcao() {
    return function(a) { console.log(a); }
}

Imagine something concatenated after that, like a typical code that uses module pattern :

(function() {
    return { foo: true };
}());

The mined and concatenated code would look like this (assuming funcao was already available and in scope):

funcao()(function() { return { foo: true };}())

The result is that the function returned by funcao will be invoked, receiving as parameter the { foo: true } object. The object will be logged into the console (this is what our example function does).

So, a withdrawal of ; in JavaScript, if not done with great care, can indeed cause side effects.

    
28.10.2014 / 16:01
0
  • When applying Minify techniques, without the;, your code will probably stop working;
  • In my opinion, something is cooler to understand;
  • 28.10.2014 / 15:36