Strange situation. Consider an example. Suppose we calculate an even or odd number in front of us:

var time = new Date().getTime(); if ( time % 2 ) console.log('Нечётное') else console.log('Чётное') 

Works. Yes ... But brevity is the sister of talent:

 ( time % 2 ) ? console.log('Нечётное покороче') : console.log('Чётное покороче') 

In theory, both records are similar, but as a result of a short record we catch "Egorku":

Uncaught TypeError: undefined is not a function

WTF?

jsFiddle

  • Everything works. Try to put a semicolon after each expression. - lampa

3 answers 3

I think you need to dot the commas, and the situation will change, proof.

because in this case, the code is parsed as follows:

 if ( time % 2 ) console.log('Нечётное') else console.log('Чётное')( time % 2 ) ... 

because console.log returns undefined, then it is not possible to call the operator (), hence the error undefined is not a function

  • Damn. After watching the source code for bootstrap twitter I took this habit of not putting dots with commas. But they don’t have errors of such a plan ... So a semicolon is needed only when a situation arises ()() ? - Andrey Yakovlev
  • @Andrey Yakovlev make it a habit to put a semicolon after each expression. This will prevent many implicit errors and the code will be easier to read. - lampa
  • Nah ..) Now I realize when she really needs her - Yakovlev Andrei
  • @Yakovlev Andrey, if you want to save the code in this way, then I will upset you. Try to "run this water without a semicolon" through the compressor. All the same, the forces of good will win and the decimal points will be in place. - lampa
  • > Having seen the source code for Twitter bootstrap, I took this habit of not putting dots with commas when you do projects of the twitter bootstrap level, then you can take this habit, but for now no evala, with and everywhere dots with commas! - Specter

I have this option: http://jsfiddle.net/7Lyzv/

 var time = new Date().getTime() time % 2 ? console.log('Чётное покороче') : console.log('Нечётное покороче') 
  • You did not consider the previous code. > var time = new Date (). getTime ()> (time% 2)? console.log ('Even Shorter'): console.log ('Odd Shorter'); It won't work either. - lampa
  • It will not be so, but as I wrote it will be. After all, the question was how to make it short so as not to get an error. So, the error does not occur if you do not use parentheses in time% 2. - komka
  • @komka, you gave me more food for thought about JS syntax - Andrey Yakovlev

Guys, this is all described in great detail, as JS parses the code and puts semicolons for you. bonsaiden.github.com/JavaScript-Garden/ru/#core.semicolon

github.com/rwldrn/idiomatic.js/tree/master/translations/en_RU

Enlighten yourself and do not be lazy to put a semicolon.