JavaScript Strings Are Immutable

✅ JavaScript Output — Why This String Didn’t Change This morning’s code was: let a = "Hello"; a[0] = "h"; console.log(a); console.log(a.length); 💡 Correct Output Hello 5 🧠 Simple Explanation : 🔹 Strings are immutable in JavaScript That means: Once a string is created, you cannot change its characters directly. So when you do: a[0] = "h"; JavaScript ignores this operation. No error. No warning. Just no change. That’s why: console.log(a); still prints: Hello 🔹 Why does a[0] look like it should work? Because strings allow read access: a[0] // "H" But write access is not allowed. Strings are not arrays. 🔹 What about a.length? Since the string never changed, its length remains: 5 ✔ Output: 5 🎯 Key Takeaways : Strings are immutable You can read characters but cannot modify them To change a string, you must create a new one ✔ Correct way: a = "h" + a.slice(1); 💬 Your Turn Did you expect the string to change? 😄 Comment “I thought it would 😮” or “Knew this 👍” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Strings #TechWithVeera #WebDevelopment #100DaysOfCode

  • graphical user interface, application, PowerPoint

To view or add a comment, sign in

Explore content categories