How ASI can change your JavaScript code's meaning

𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗰 𝗦𝗲𝗺𝗶𝗰𝗼𝗹𝗼𝗻 𝗜𝗻𝘀𝗲𝗿𝘁𝗶𝗼𝗻 (𝗔𝗦𝗜) 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 --> 𝘁𝗵𝗲 “𝗵𝗲𝗹𝗽𝗳𝘂𝗹” 𝗳𝗲𝗮𝘁𝘂𝗿𝗲 𝘁𝗵𝗮𝘁 𝘀𝗼𝗺𝗲𝘁𝗶𝗺𝗲𝘀 𝗵𝗲𝗹𝗽𝘀 𝗮 𝗹𝗶𝘁𝘁𝗹𝗲 𝘁𝗼𝗼 𝗺𝘂𝗰𝗵. JavaScript automatically inserts semicolons (;) when it thinks you forgot them. Sounds convenient. Well... sometimes it can change your code’s meaning entirely! 𝗛𝗲𝗿𝗲’𝘀 𝗮 𝗰𝗹𝗮𝘀𝘀𝗶𝗰 𝗲𝘅𝗮𝗺𝗽𝗹𝗲 👇 function getData() {  return  {   message: "Hello World"  } } console.log(getData()); You’d expect it to log { message: "Hello World" } 𝗕𝘂𝘁 𝘀𝘂𝗿𝗽𝗿𝗶𝘀𝗲 --> It logs undefined 𝗪𝗵𝘆? Because ASI inserts a semicolon right after return return; // inserted automatically {  message: "Hello World" } So the function actually returns nothing. 𝗧𝗼 𝗳𝗶𝘅 𝗶𝘁: function getData() { return { message: "Hello World" } } 𝗧𝗶𝗽: Always keep the return and the value on the same line. ASI is like that friend who “fixes” your code but never tells you what they changed. Always use semicolons intentionally, not accidentally. #JavaScript #WebDevelopment #Frontend #CleanCode #DevCommunity

This is meaningful i encountered one such in an interview seeing the results i was blank latter post interview i checked it out and came to know about it you can also validate it while coding if you enter the block in the next line you can observe the block will not be highlighted . It such a minute observation but says a lot about how JS works behind the scene .

Like
Reply

To view or add a comment, sign in

Explore content categories