Automatic semicolon insertion (ASI) in JavaScript

Опубликовано: 03 Май 2024
на канале: 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.


На этой странице сайта вы можете посмотреть видео онлайн Automatic semicolon insertion (ASI) in JavaScript длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь Mayank Srivastava 03 Май 2024, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 341 раз и оно понравилось 19 зрителям. Приятного просмотра!