Posts

Showing posts with the label automatic semicolon insertion

Javascript ASI and join vs concat(+)

Javascript Automatic Semicolon Insertion I came across a nice implication of Automatic Semicolon Insertion while developing an API in javascript. I'll let you guess at first as usual. Try the following function asi() { var a = 10, b = 20 c = 30; this.log = function () { console.log(a,b,c); }; this.set = function (A,B,C) { a=A; b=B; c=C; } } var a = new asi(); a.log(); var b = new asi(); b.log(); a.set(11,21,31); b.log(); b.set('This', 'is', 'wrong'); a.log(); //Expected output 10 20 30 10 20 30 10 20 30 11 21 31 //What happened?? 10 20 30 10 20 30 10 20 31 11 21 wrong How Come? First Thing to note: See Closely at line 3 there is a comma operator missing. So, now parser will decide what to do :P Remember: Whenever a statement misses a semicolon and if the statement following it makes sense along with the former. Then JS engine will not place a semicolon. Perhaps it parse them...

JS Automatic Semicolon Insertion

Semicolon; Why should I care? "Javascript is the only language which people dare to use before learning" - Crockford Actually I, myself belong to that category of people whom crockford mentions :) But trying to be out.. So, What's new today? Just a informative writeup about ASI ASI? Ya, Javascript Automatic Semicolon Insertion What is a legal statement in Javascript? Following are some var a=10; a; b++; b+=1; ;;; // 3 Empty Statements +a var a = function() { }; {   a   b   c     }; Lets start Try the following var a=10; function test() {     var b;     b = a;     b+=1 } console.log(a) Even though I didn't insert any semicolon [Statement Terminator] in line 5 and 7, the JS engine never throws an syntax error. Reason: ASI Construct Rules to remember:     ** ASI will insert one for you, if you specify a line terminator @ [no line terminator] mentioned        in the gra...