--- title: You Don’t Know JS - Ch.8-III tags: Templates, Talk description: View the slide with "Slide Mode". --- # You Don’t Know JS - Ch.8-III ## Automatic Semicolons ASI (Automatic Semicolon Insertion) allows JS to be tolerant of certain places where ; isn’t commonly thought to be necessary. ```typescript var a = 42, b = "foo" c = a a b c //42 ``` --- Statement blocks do not require ; , so ASI isn’t necessary: ```typescript var a = 42; do { a--; console.log(a); } while (a>=0) // <-- no ; expected here! a; ``` --- ASI kicks in is with the break, continue, return, and (ES6) yield keywords For a example: The return statement doesn’t carry across the newline to the a *= 2 expression, as ASI assumes the ; terminating the return statement. ```typescript= function foo(a) { if (a) return a *= 2; } a // undefined ``` Compare with no API ```typescript= function foo(a) { if (a) return a *= 2; } a // a*2 ``` --- ## Error Correction ### Error --- One simple example is with syntax inside a regular expression literal,but the invalid regex will throw an early error: ```typescript= var a = /+foo/; // Error! ``` --- The target of an assignment must be an identifier so a value like 42 in that position is illegal and can be reported right away: ```typescript= var a; 42 = a; // Error! ``` --- ES5’s strict mode defines even more early errors. For example, in strict mode, function parameter names cannot be duplicated: ```typescript= function bar(a,b,a) { "use strict"; } // Error! ``` --- ### Using Variables Too Early --- #### TDZ (“Temporal Dead Zone”). The TDZ refers to places in code where a variable reference cannot yet be made, because it hasn’t reached its required initialization. ```typescript= { a = 2; // ReferenceError! let a; } ``` While typeof has an exception to be safe for undeclared variables, no such safety exception is made for TDZ references: ```typescript= { typeof a; // undefined typeof b; // ReferenceError! (TDZ) let b; } ``` ## Function Arguments --- When using ES6’s default parameter values,the default value is applied to the parameter if you either omit an argument, or you pass an undefined value in its place. ```typescript= function foo( a = 42, b = a + 1 ) { console.log( a, b ); } foo(); // 42 43 foo( undefined ); // 42 43 foo( 5 ); // 5 6 foo( void 0, 7 ); // 42 7 foo( null ); // null 1 ``` --- If you pass an argument, the arguments slot and the named parameter are linked to always have the same value. If you omit the argument, no such linkage occurs. ```typescript= function foo(a) { a = 42; console.log( arguments[0] ); } foo( 2 ); // 42 (linked) foo(); // undefined (not linked) ``` --- But in strict mode, the linkage doesn’t exist regardless: ```typescript= function foo(a) { "use strict"; a = 42; console.log( arguments[0] ); } foo( 2 ); // 2 (not linked) foo(); // undefined (not linked) ```