JavaScript Variables: Primitives vs Objects

JavaScript's got a thing or two to teach us about variables. It's pretty straightforward, actually - everything's passed by value. But, what's that even mean? It means when you pass a primitive, like a number or a string, JavaScript just makes a copy of it. Simple as that. The original and the copy, they're like two separate entities, living their best lives independently. So, yeah: Primitives are stored right in the variable, no fuss. But objects, on the other hand, are a different story - they're passed by value too, but the value is actually a reference to where the object lives in memory. Think of it like sending someone a map to your house, instead of the actual house. You can make copies of objects, though, using the spread operator or structuredClone() - it's like taking a snapshot of the object, so you can play around with the copy without messing up the original. Here's the lowdown: Primitives are safe, they won't get changed on you. Objects and arrays, though, they share references, so be careful not to mess things up. Just use spread or structuredClone() to make copies, and you're golden. And, honestly, embracing immutability is the way to go - it makes your code predictable, and performant, like a well-oiled machine. Check it out: https://lnkd.in/g-Nj9Rh6 #JavaScript #Variables #Immutability

To view or add a comment, sign in

Explore content categories