Part 1: Why JavaScript Why? 🚨 JavaScript Question (surprisingly tricky) What will be the result of this code? 🤔 const initialGameBoard = [ [null, null, null], [null, null, null], [null, null, null], ]; const copiedArray = [...initialGameBoard]; copiedArray[0][0] = 'X'; console.log(initialGameBoard[0][0]); ⬇️ ⬇️ ⬇️ Most people expect null. But the actual output is: 👉 'X' Why does this happen? [...] creates a shallow copy, not a deep one. That means: The outer array is copied The inner arrays are NOT copied Both arrays still reference the same nested arrays in memory So changing copiedArray[0][0] also changes initialGameBoard[0][0]. The correct way (for a 2D array) const copiedArray = initialGameBoard.map(row => [...row]); Now: The outer array is new Each inner array is also new No shared references ✅ Why doesn’t JavaScript do a deep copy automatically? Because predictability > magic. If JavaScript auto-deep-copied: How deep should it go? What about circular references? What about functions, Dates, Maps, Sets, DOM nodes? There’s no single “correct” answer. So JavaScript makes this rule very explicit: Copying is shallow by default. Always one level. This keeps behavior: predictable performant explicit (you control when deep copies happen) Key takeaway 🔑 Spread (...) copies values — and for objects/arrays, the value is a reference. If you want a deep copy, you must say so explicitly. Curious how many people got this right on the first try 👇 What would you have answered?
JavaScript Shallow Copy Conundrum: Why '...' Creates References
More Relevant Posts
-
🕒 Temporal API in JavaScript — A Better Way to Work with Dates and Time If you’ve worked with JavaScript long enough, you probably know that the built-in Date object can be… frustrating. Handling time zones, parsing dates, or performing reliable date arithmetic often leads to confusing code and subtle bugs. Developers have relied on libraries like Moment.js, date-fns, or Luxon to fill these gaps. But JavaScript is finally getting a modern, built-in solution: Temporal. What is Temporal? Temporal is a new JavaScript API designed to replace the legacy Date object with a more reliable and predictable way to work with time. It introduces a set of clear, immutable objects for different time concepts: • Temporal.Instant — a specific point in time (UTC) • Temporal.ZonedDateTime — date and time with a timezone • Temporal.PlainDate — a calendar date without time • Temporal.PlainTime — a time without a date • Temporal.Duration — a time duration This separation solves one of the biggest problems with Date: mixing multiple concepts in one object. Why Temporal Is Better 1. Immutable values Temporal objects are immutable, which means operations return new values instead of mutating existing ones. 2. First-class timezone support Time zones are handled explicitly instead of being hidden inside system settings. 3. Clearer date arithmetic Temporal handles calendar rules correctly without the typical JavaScript pitfalls. Current Status Temporal is currently a Stage 3 proposal in the ECMAScript process and already available through a polyfill.
To view or add a comment, sign in
-
-
I’ve lost count of how many times I’ve seen the same explanation: “Primitives are passed by value, objects by reference.” It’s everywhere—in tutorials, interviews, Stack Overflow answers… and honestly, it’s been driving me nuts because it’s not quite accurate in JavaScript. So I finally sat down and wrote the post I wish I’d read years ago: “Primitives vs Objects: How JavaScript Values Actually Work” The real difference isn’t “value vs reference”—it’s mutability. Primitives are immutable (you can’t change them, only replace them). Objects are mutable (you can change their contents, and everyone with a reference sees it). Everything else flows from there: why a = b behaves differently, why {} === {} is false, why mutating an object affects the “original”, why reassignment doesn’t, and even why JavaScript technically uses “call by sharing” for everything. If you’ve ever been confused by why changing an array in a function changes the original, or why strings act “weird” compared to objects—this might clear things up. Check it out here: https://lnkd.in/dvRfbPFC What’s the biggest JavaScript primitive/object misconception you’ve had to unlearn? Drop it below—I’m curious. 👇 #JavaScript #WebDevelopment #Programming #Frontend
To view or add a comment, sign in
-
Understanding Optional Chaining in JavaScript The question sounded simple. “What is optional chaining?” I had used it many times. I had written user?.profile?.email in real projects. It worked. It saved me from errors. But in that moment, explaining it clearly felt harder than writing it. And that is more common than we admit. What is Optional Chaining? Optional chaining (?.) is a JavaScript feature that lets you safely access nested properties in an object. Normally, this can break your code: user.profile.email If profile is undefined, JavaScript throws an error. With optional chaining: user?.profile?.email If profile does not exist, it simply returns undefined instead of crashing your application. Why optional chaining matters - It prevents runtime errors - It keeps your code clean - It removes long condition checks - It improves readability - Instead of multiple if statements, you handle uncertainty in one simple line. The bigger lesson Many developers use powerful features daily but struggle to explain them professionally. Knowing the name and concept behind what you use builds confidence, especially in interviews and technical discussions. Small knowledge gaps can create big doubt. Have you ever used something confidently in code but struggled to explain it under pressure? Share your experience in the comments. If this helped you, like or repost so others can learn too.
To view or add a comment, sign in
-
👨💻Mastering JavaScript — One Concept at a Time (4/32) Operators are the verbs of your code. While revisiting JavaScript fundamentals, I noticed something interesting: 🔹 What Are Operators? Operators are symbols that tell JavaScript to perform an operation. They allow us to: Calculate values, compare data, make decisions, combine logic and modify variables. 1️⃣ Arithmetic Operators These are the most familiar ones used for mathematical operations. Addition, subtraction, multiplication, division, modulus, and exponentiation. But even here, JavaScript has quirks. For example, + is not just addition, but also performs string concatenation. That dual behaviour is something I now pay close attention to. 2️⃣ Comparison Operators These help us compare values; they return a boolean (true or false). Important distinction: Loose comparison (==) Strict comparison (===) Earlier in this series, I discussed why strict comparison is usually safer. Revisiting this again reinforces how small operator choices can prevent big bugs. 3️⃣ Logical Operators These are used for combining conditions: AND (&&), OR (||), NOT (!). What I appreciate now is that logical operators don’t just return true or false they return actual values based on truthy and falsy evaluation.That subtle behavior is powerful in real-world applications. 4️⃣ Unary Operators Unary operators work with a single operand. Examples include: Increment (++), Decrement (--), typeof, Logical NOT (!). They seem simple, but understanding how they affect state (especially in loops) matters a lot. ❓ Ternary Operator The ternary operator is JavaScript’s compact decision-maker. It’s a shorthand for if...else. Clean and readable when used properly. Confusing and messy when overused. I’ve learned that readability should always come before cleverness. 💡 Learning Mindset While revising this, I’m not just memorising operators. I’m asking: What exactly does this operator return? Does it mutate the value? Is it safe and readable? What operator confused you the most when you first learned JavaScript? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
Difference Between null and undefined in JavaScript A developer once told me, “My code is broken and I don’t know why.” We looked at it together, and the bug came down to one tiny detail: null vs undefined. Two words that look harmless. Two values that both seem to mean “nothing.” Yet that small misunderstanding caused hours of confusion. This happens more often than people admit. JavaScript is friendly, but it has weird behavior sometimes. And some of the biggest bugs come from the smallest concepts we rush past while learning. Understanding the difference between null and undefined is one of those quiet fundamentals that saves you from future headaches. undefined means a variable has been declared, but no value has been assigned yet. JavaScript assigns undefined by default. JavaScript let aniekan; console.log(aniekan); - undefined null on the other hand is an intentional value. It means the developer has explicitly set the variable to have no value. JavaScript let aniekan = null; Key differences undefined → value is missing or not yet assigned null → value is intentionally empty A common surprise: typeof null; - returns an"object" This is a well-known JavaScript weird behavior. Even though null is not an object, but typeof null returns "object". The difference between null and undefined is small, but it changes how you think about intention in your code. One is accidental. The other is deliberate. Knowing when to use each makes your programs easier to read and easier to trust. If this helped clarify things, give it a like so more developers can learn from it. Repost it for someone new to JavaScript. And drop your thoughts in the comments; when did null or undefined first confuse you? Let’s talk about it.
To view or add a comment, sign in
-
Difference Between Spread and Rest in JavaScript I remember the first time I saw ... in JavaScript. I thought it was a typo. Three dots sitting there like they forgot to finish typing. Then someone said, “That’s either spread or rest.” Either? Same symbol, different meaning? My brain paused. Many developers hit this moment early in their JavaScript journey. The syntax looks identical, but the behaviour feels opposite. It’s one of those small concepts that seems confusing at first, until it clicks. And once it clicks, your confidence grows, you become a better tech professional, and the codes of other developers becomes easier to reason about. Spread (...) is used to expand values. It takes an array, object, or string and spreads its items out into individual elements. Common uses of spread: Function calls Math.max(...[1, 2, 3]) becomes Math.max(1, 2, 3) Copying arrays or objects (shallow copy) const newArray = [...oldArray] Merging arrays or objects const merged = { ...obj1, ...obj2 } Spread is often used to maintain immutability, especially in frameworks like React(allowing developers to update data without directly altering the original (previous) state). Rest (...) is used to collect values. It takes multiple individual values and packs them into a single array or object. Common uses of rest: Function parameters function myFunc(...args) { // args is an array of all arguments } Destructuring const [first, ...rest] = array; In simple terms: - Spread spreads things out - Rest gathers things together Spread and rest are simple tools, but they unlock powerful patterns in modern JavaScript. Understanding them is not just about syntax, it’s about thinking clearly about how data moves in your code. If this explanation helped, give it a like so more developers can see it. Repost it for someone learning JavaScript. And drop your answer in the comments - which one confused you more when you first learned it? Let’s compare experiences.
To view or add a comment, sign in
-
⚔️ Normal JavaScript vs. War‑Style JavaScript What works locally often breaks in production. Here’s how to tell the difference—and why it matters. 🧪 Normal JavaScript You write it in a sandbox. The data is clean, the network is fast, and the user follows the happy path. ✅ No null or undefined to worry about ✅ Async/await with no .catch() ✅ const user = data.user.profile.email; – works every time This is lab‑grade code. Great for prototypes. Dangerous in production. 🛡️ War‑Style JavaScript This code has seen things. It’s been through code reviews, pentesting, and a 3am outage. 🔹 Defensive reading const email = data?.user?.profile?.email ?? 'fallback@example.com'; 🔹 Error handling that actually handles try { await riskyCall(); } catch (err) { logger.error(err); // Recover, don’t just crash } 🔹 Input validation – never trust the client 🔹 Performance under load – debouncing, throttling, memoization 🔹 Security – escape user input, validate JWTs, use Helmet.js 🔹 Observability – logs, metrics, structured errors War‑style code assumes the worst: 📉 Network fails 🧨 Third‑party API changes shape 🐞 Users type “eval()” into a text box 📈 The Real Difference Normal JS War‑Style JS Works on my machine Works for 10k concurrent Throws undefined Shows a friendly error One developer knows it Handover‑ready, documented “It’s fine for now” “How will this scale?” 🔥 Why This Matters War‑style isn’t over‑engineering—it’s respect. Respect for your users, your future self, and the people who will maintain your code. Start by auditing your last PR. Did you handle the unhappy paths? Did you log failures? Did you assume nothing? Normal JavaScript gets the job done. War‑style JavaScript keeps the job done. 💬 What’s one “war‑style” habit you always practice? I’ll go first: optional chaining and nullish coalescing are non‑negotiable. 👇
To view or add a comment, sign in
-
🚀 Currying, Closures & Functional Thinking in JavaScript Explored how functions in JavaScript can be composed, extended, and even behave like objects. Here’s what stood out 👇 🧠 Currying (Function Transformation) Transforming a function with multiple arguments into a chain of single-argument functions. function add(a) { return function (b) { return a + b; }; } add(2)(3); // 5 💡 Why it works: Closures allow the inner function to retain access to a. 🔁 Infinite Currying Built flexible patterns like: sum(1)(2)(3)(); // 6 console.log(sum(1)(2)(3)); // 6 Using: • Closures • Functions as objects • toString() override • Symbol.toPrimitive This shows how JavaScript allows deep control over function behavior. ⚙️ Functions Are Objects In JavaScript: • Functions can store properties • Functions can override default behavior • Functions can control type coercion 💡 Insight: Functions are not just callable — they’re fully dynamic objects. 🎯 Takeaway: JavaScript becomes predictable when you understand: • Closures • Execution context • Type coercion • Prototype behavior 🧩 Problem Solving — Sliding Window Optimization Solved: Longest Substring Without Repeating Characters Approach evolution: • Set-based → expand/shrink window (O(n)) • Map-based → store last seen index l = Math.max(l, lastSeen[s[r]] + 1); 💡 Key Insight: Instead of shrinking step-by-step, jump the left pointer directly. 🎯 Pattern Understanding: Sliding Window = • Expand when valid • Shrink when invalid • Never move pointers backward Building stronger functional thinking and optimized problem-solving patterns. 💪 #JavaScript #FunctionalProgramming #DSA #ProblemSolving #FrontendDeveloper #MERNStack “Closures allow functions to remember variables even after execution — that’s the power behind currying.”
To view or add a comment, sign in
-
-
🚀 Top 20 JavaScript Concepts Every Developer Must Master. 1️⃣ Hoisting JavaScript moves variable and function declarations to the top of their scope before execution. 2️⃣ Closures A function that remembers variables from its outer scope even after the outer function has finished. 3️⃣ Scope (Global, Function, Block) Determines where variables are accessible. 4️⃣ Lexical Scope Scope is decided by where functions are written, not where they are called. 5️⃣ Prototypes & Inheritance JavaScript uses prototypal inheritance to share properties and methods between objects. 6️⃣ Event Loop Handles asynchronous operations in JavaScript’s single-threaded environment. 7️⃣ Call Stack Tracks function execution order. 8️⃣ Async/Await Cleaner way to handle asynchronous code using promises. 9️⃣ Promises Represents a value that may be available now, later, or never. 🔟 Callback Functions Functions passed as arguments to other functions. 1️⃣1️⃣ Debounce & Throttle Improve performance by controlling how often functions run. 1️⃣2️⃣ Event Delegation Attach event listeners to parent elements instead of multiple children. 1️⃣3️⃣ Truthy & Falsy Values Understanding how JavaScript evaluates values in conditions. 1️⃣4️⃣ Type Coercion JavaScript automatically converts types (== vs === difference). 1️⃣5️⃣ Destructuring Extract values from arrays or objects easily. 1️⃣6️⃣ Spread & Rest Operators Expand arrays/objects or collect function arguments. 1️⃣7️⃣ ES6 Modules Organize and reuse code using import and export. 1️⃣8️⃣ Memory Management & Garbage Collection JavaScript automatically allocates and frees memory. 1️⃣9️⃣ IIFE (Immediately Invoked Function Expression) Function that runs immediately after it’s defined. 2️⃣0️⃣ The " this" Keyword 'this'refers to the object that is calling the function. Its value depends on how the function is invoked (not where it’s defined). In arrow functions, this is inherited from the surrounding scope. #JavaScript #FrontendDeveloper #BackendDeveloper #WebDevelopment #FullstackDeveloper #Developers
To view or add a comment, sign in
-
-
Recently I wrote an article explaining the idea of Javascript prototypes from the ground up ⬆️ , starting from something familiar: plain objects, and gradually building toward how Javascript actually constructs prototype chain. If you have ever tried explaining prototypes to someone or struggled with the mental model yourself, you might find this interesting. Read here: https://lnkd.in/gCYnRNmv 🙋🏻♂️ While working with Javascript developers, I've noticed that prototypes remain confusing for a long time 🕰️ Most people eventually learn that objects “inherit” from other objects, but the underlying intuition often stays fuzzy Terms like prototype, [[Prototype]], and the prototype chain get used interchangeably, which makes the mental model 🧠 even harder to build Over time, I realized the problem usually isn’t the concept itself — it’s how it’s introduced. 👨🏻💻 Its a good 4-5 min read !! #javascript #frontend #softwareengineering #webdevelopment #blog #prototype
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development