𝗧𝗵𝗶𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝘀𝗻𝗶𝗽𝗽𝗲𝘁 𝗹𝗼𝗼𝗸𝘀 𝗶𝗻𝗻𝗼𝗰𝗲𝗻𝘁... but it reveals one of the MOST misunderstood concepts in JS ❓ 𝗪𝗵𝗮𝘁 𝗱𝗼 𝘆𝗼𝘂 𝘁𝗵𝗶𝗻𝗸 𝘁𝗵𝗶𝘀 𝗹𝗼𝗴𝘀? Most people say: 1 ✅ That part is correct… but 𝘁𝗵𝗲 𝗿𝗲𝗮𝘀𝗼𝗻 𝗺𝗮𝘁𝘁𝗲𝗿𝘀 𝗺𝗼𝗿𝗲 𝘁𝗵𝗮𝗻 𝘁𝗵𝗲 𝗮𝗻𝘀𝘄𝗲𝗿. 🧠 What’s really happening? • Default parameters in JavaScript are 𝗲𝘃𝗮𝗹𝘂𝗮𝘁𝗲𝗱 𝗮𝘁 𝗰𝗮𝗹𝗹 𝘁𝗶𝗺𝗲 • NOT at function definition time • total + 1 runs 𝗼𝗻𝗹𝘆 𝘄𝗵𝗲𝗻 𝘂𝗽𝗱𝗮𝘁𝗲𝗧𝗼𝘁𝗮𝗹() 𝗶𝘀 𝗶𝗻𝘃𝗼𝗸𝗲𝗱 • total itself is never updated So this logs 1, but total stays 0. 💡 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 👉 Default parameters are 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀, 𝗻𝗼𝘁 𝗮𝘀𝘀𝗶𝗴𝗻𝗺𝗲𝗻𝘁𝘀 👉 They don’t mutate external state 👉 They’re 𝗲𝘃𝗮𝗹𝘂𝗮𝘁𝗲𝗱 𝗳𝗿𝗲𝘀𝗵 on every call #JavaScript #WebDevelopment #Programming #Frontend #CodingTips #DevLife #LearnJavaScript #HappyCoding
There is no assignment to total variable, so obviously total value didn’t change. Instead of total + 1 , use total++ and it will update total too.
Absolutely spot on. The real gotcha isn’t the output, but when the expression runs. Default params are evaluated at call time, not definition time, and they don’t mutate state. That’s why it logs 1 while total stays 0. A great example of how JS rewards solid mental models.
since total being a number (primitive data type) always get passed by value not reference.
answer : 1
😊
Nobody. EVER. ;-)
Why would anyone do it this way in the first place? Value is a completely redundant variable. You could simply use total, a waste of a variable and more importantly, memory. Passing a default value is unnecessary as total has already been defined. ++total or total++ would suffice as long as it was placed before console.log(total). Maybe I missed something but this just seems like bad code, what is the point that was intended?