Automatic semicolon insertion (ASI) in JavaScript

Published: 03 May 2024
on channel: Mayank Srivastava
341
19

When we first take a glance at this piece of javascript code we might think that there is nothing wrong with it and when the function getObject is invoked it will return the object with the id property. However, when we run the snippet we can see that the returned value is undefined. This happens because there's a subtle issue here related to automatic semicolon insertion (ASI).In JavaScript, ASI automatically inserts semicolons at the end of certain lines if they're omitted. In this case, ASI inserts a semicolon after the return keyword, treating the subsequent lines as separate statements. So, the function getObject actually returns undefined, not an object with the property id set to 1, because the return statement is terminated prematurely by the automatically inserted semicolon. The object literal { id: 1 } is ignored because it's seen as an unrelated statement. This is also true for other javascript keywords like throw, break, and continue.
So, what's the takeaway? While JavaScript's ASI can be convenient, it's best to include semicolons explicitly to avoid unexpected behavior and improve code readability. Even enable all of the code linters to check for semicolons in your code.


On this page of the site you can watch the video online Automatic semicolon insertion (ASI) in JavaScript with a duration of hours minute second in good quality, which was uploaded by the user Mayank Srivastava 03 May 2024, share the link with friends and acquaintances, this video has already been watched 341 times on youtube and it was liked by 19 viewers. Enjoy your viewing!