Automatic semicolon insertion (ASI) in JavaScript

Publicado el: 03 mayo 2024
en el canal de: 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.


En esta página del sitio puede ver el video en línea Automatic semicolon insertion (ASI) in JavaScript de Duración hora minuto segunda en buena calidad , que subió el usuario Mayank Srivastava 03 mayo 2024, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 341 veces y le gustó 19 a los espectadores. Disfruta viendo!