JavaScript const surprises: reassignment and object changes

You believe const means no changes but wait JavaScript has a little surprise !! When I started learning JavaScript, I thought const means the value can never change. Then I saw this magic… and got confused. 1. First: const with simple values const a = 10; a = 20; This makes sense. We are trying to change the value, and const does not allow that. 2. Now the surprise: const with objects const user = { name: "John" }; user.name = "Dev"; // allowed This works because: user is pointing to an object in memory & const locks the variable, It does NOT lock what’s inside the object. The variable still points to the same object. We are not changing the variable. We are only changing data inside it. So, const stops reassignment, but allows changes inside objects or arrays. Sharing this as part of my learning journey. Comment below if this is something you didn’t know before! #JavaScript #FrontendDevelopment #WebDevelopment #LearnJavaScript #CodingJourney #ProgrammingTips #CodingForBeginners #JSBasics #FrontendDev #LearnInPublic #CleanCode #CodeBetter #100DaysOfCode #DeveloperLife #TechLearning #JSFundamentals

  • No alternative text description for this image

Const pretty much means that the *reference* of the variable will not be changed, it does not guarantee if the value will be the same or not!

Like
Reply

To view or add a comment, sign in

Explore content categories