🔍 JavaScript Behavior You Might Have Seen (Array methods: mutate vs not) You write this: const arr = [1, 2, 3]; const newArr = arr.push(4); console.log(arr); // ? console.log(newArr); // ? You expect: 👉 newArr to be a new array But you get: 👉 arr → [1, 2, 3, 4] 👉 newArr → 4 This happens because of mutating array methods 📌 What does “mutate” mean? 👉 It means changing the original array In this case: 👉 push() modifies arr directly 👉 And returns the new length (not a new array) Now look at this 👇 const arr = [1, 2, 3]; const newArr = arr.map(x => x * 2); console.log(arr); // ? console.log(newArr); // ? 👉 arr → [1, 2, 3] 👉 newArr → [2, 4, 6] This is a non-mutating method 👉 It creates a new array 👉 Original array stays unchanged 📌 Common mutating methods: ✔ push ✔ pop ✔ shift ✔ unshift ✔ splice ✔ sort ✔ reverse 📌 Common non-mutating methods: ✔ map ✔ filter ✔ slice ✔ concat ✔ reduce 📌 Real problem: You think you’re creating a new array… 👉 But you accidentally modify the original one 💡 Takeaway: ✔ Mutating methods change original array ✔ Non-mutating methods return a new array ✔ Always be careful when updating state (especially in React) 👉 One wrong method can break your logic silently 🔁 Save this for later 💬 Comment “array” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
JavaScript Array Methods: Mutate vs Non-Mutate
More Relevant Posts
-
🔍 JavaScript Behavior You Might Have Seen (Hoisting) You write this: console.log(a); var a = 10; You expect: 👉 ReferenceError But you get: 👉 undefined 🤯 Now try this: console.log(b); let b = 20; 👉 This time you get: ReferenceError ❌ Same with: console.log(c); const c = 30; 👉 Error again ❌ Now look at functions 👇 sayHi(); function sayHi() { console.log("Hello"); } 👉 This works ✅ But this doesn’t: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Why different behavior? This happens because of Hoisting 📌 What is Hoisting? 👉 Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 📌 What’s actually happening? ✔ var: var a; console.log(a); // undefined a = 10; 👉 Hoisted + initialized ✔ let / const: 👉 Hoisted but NOT initialized 👉 Access before declaration → ReferenceError 👉 (Temporal Dead Zone) ✔ Function declarations: function sayHi() {} 👉 Fully hoisted (can be called before definition) ✔ Function expressions: const sayHello = function () {} 👉 Behave like variables 👉 Not usable before declaration 💡 Takeaway: ✔ var → hoisted + initialized ✔ let / const → hoisted but restricted (TDZ) ✔ Function declarations → fully hoisted ✔ Function expressions → NOT hoisted like functions 👉 Same concept… different rules 🔁 Save this before hoisting confuses you again 💬 Comment “hoisting” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Behavior You Might Have Seen (Function Declaration vs Expression) You write this: sayHi(); function sayHi() { console.log("Hello"); } 👉 Works perfectly ✅ Now try this: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Same idea… same function… Why different behavior? This happens because of Hoisting 📌 What’s happening here? 👉 Function Declarations are fully hoisted So internally: function sayHi() { console.log("Hello"); } sayHi(); 👉 That’s why it works even before definition But for Function Expressions: const sayHello = function () {} 👉 This is treated like a variable (const) So internally: const sayHello; // not initialized (TDZ) sayHello(); // ❌ error 📌 Key Difference: ✔ Function Declaration 👉 Hoisted completely (can call before definition) ✔ Function Expression 👉 Not hoisted like function 👉 Behaves like variable 📌 Bonus case 👇 var sayHello = function () { console.log("Hello"); }; sayHello(); 👉 Works (because var is hoisted) BUT: sayHello(); // before assignment 👉 TypeError ❌ (not a function yet) 💡 Takeaway: ✔ Function declarations → fully hoisted ✔ Function expressions → behave like variables ✔ let/const → TDZ error ✔ var → undefined (then TypeError if called) 👉 Same function… different behavior based on how you write it 🔁 Save this before it confuses you again 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Quirk: Hoisting (var vs let vs const) JavaScript be like: 👉 “I know your variables… before you even write them” 😅 Let’s see the magic 👇 console.log(a); var a = 10; 💥 Output: undefined Wait… no error? 🤯 Why? Because `var` is **hoisted** 📌 What is Hoisting? Hoisting is JavaScript’s behavior of **moving variable and function declarations to the top of their scope before execution**. 👉 JS internally does this: var a; console.log(a); // undefined a = 10; So the variable exists… but has no value yet. Now try with `let` 👇 console.log(b); let b = 20; 💥 Output: ReferenceError ❌ Same with `const` 👇 console.log(c); const c = 30; 💥 Error again ❌ Why? Because `let` & `const` are also hoisted… BUT they live in something called: 👉 “Temporal Dead Zone” (TDZ) Translation: 🧠 “You can’t touch it before it’s declared” --- 💡 Simple Breakdown: ✔ `var` → hoisted + initialized as `undefined` ✔ `let` → hoisted but NOT initialized ✔ `const` → same as let (but must assign value) 💀 Real dev pain: Using `var`: 👉 “Why is this undefined?” Using `let`: 👉 “Why is this error?” JavaScript: 👉 “Figure it out yourself” 😎 💡 Takeaway: ✔ Avoid `var` (legacy behavior) ✔ Prefer `let` & `const` ✔ Understand hoisting = fewer bugs 👉 JS is not weird… You just need to know its secrets 😉 🔁 Save this before hoisting confuses you again 💬 Comment “TDZ” if this finally made sense ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (setTimeout vs Promise) You write this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you expect? Start Timeout Promise End But actual output is: Start End Promise Timeout This happens because of the Event Loop 📌 What is the Event Loop? 👉 The event loop is the mechanism that decides which task runs next in JavaScript’s asynchronous execution. 📌 Priority order (very important): 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue 3️⃣ Macrotask Queue 📌 What’s inside each queue? 👉 Microtask Queue (HIGH priority): ✔ Promise.then / catch / finally ✔ queueMicrotask ✔ MutationObserver 👉 Macrotask Queue (LOWER priority): ✔ setTimeout ✔ setInterval ✔ setImmediate ✔ I/O tasks ✔ UI rendering events Execution flow: ✔ Step 1: Run all synchronous code 👉 Start → End ✔ Step 2: Execute ALL microtasks 👉 Promise ✔ Step 3: Execute macrotasks 👉 setTimeout So final order becomes: Start End Promise Timeout 💡 Takeaway: ✔ Microtasks run before macrotasks ✔ Promises > setTimeout ✔ setTimeout(fn, 0) is NOT immediate 👉 Understand queues = master async JS 🔁 Save this for later 💬 Comment “event loop” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Behavior You Might Have Seen (Prototype Chain) You write this: const arr = [1, 2, 3]; console.log(arr.toString()); // ? 👉 Did you define toString on this array? 👉 Did you even define it anywhere? No. Still it works. Now think step by step 👇 When you do: 👉 arr.toString JavaScript checks: Inside arr → ❌ not found Inside Array.prototype → ❌ not found Inside Object.prototype → ✔ found This step-by-step lookup is called the Prototype Chain 📌 What is Prototype Chain? 👉 It’s the process JavaScript uses to find a property by searching up through prototypes. 📌 How it works? Every object is linked to another object (its prototype) So lookup happens like this: 👉 arr → Array.prototype → Object.prototype → null Same with strings 👇 const str = "hello"; console.log(str.hasOwnProperty("length")); // ? 👉 hasOwnProperty is not in string JS finds it here: 👉 str → String.prototype → Object.prototype 📌 Important point: 👉 JavaScript keeps searching until it finds the property or reaches null 💡 Takeaway: ✔ Prototype Chain = lookup mechanism ✔ JS searches step by step ✔ That’s how all built-in methods work 👉 If you understand this, you’ll understand how JavaScript really works 💬 Comment “chain” if this clicked 🔁 Save this for later ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (null vs undefined) You write this: let a; console.log(a); // ? let b = null; console.log(b); // ? Both look similar… But they are NOT the same. 💥 Output: undefined null Now here’s where it gets confusing 👇 console.log(null == undefined); // ? console.log(null === undefined); // ? 💥 Output: true false Wait… WHAT? 🤯 This happens because of how JavaScript treats them. 📌 What is undefined? 👉 A variable that is declared but NOT assigned a value 📌 What is null? 👉 A value that represents “intentional absence of value” (You explicitly set it) 📌 Then why this? null == undefined // true Because == does loose comparison 👉 It treats them as equal BUT: null === undefined // false Because === checks: ✔ Value ✔ Type 💡 Takeaway: ✔ undefined → JS gives it ✔ null → YOU assign it ✔ == → treats them equal ✔ === → they are different 👉 Use undefined for default/unassigned 👉 Use null when you intentionally want “no value” 🔁 Save this before it confuses you again 💬 Comment “null” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Day 5: The Shortest JavaScript Program — What happens when you write NOTHING? 📄✨ Today I learned that even if you create a totally empty .js file and run it in a browser, JavaScript is already working hard behind the scenes. 🕵️♂️ The "Shortest Program" If your file has zero lines of code, the JavaScript Engine still does three major things: Creates a Global Execution Context. Creates a window object (in browsers). Creates the this keyword. 🪟 What is window? The window is a massive object created by the JS engine that contains all the built-in methods and properties (like setTimeout, localStorage, or console) provided by the browser environment. 🧭 The this Keyword At the global level, JavaScript sets this to point directly to the window object. 👉 Proof: If you type console.log(this === window) in an empty file, it returns true! 🌐 The Global Space I also explored the Global Space—which is any code you write outside of a function. If you declare var x = 10; in the global space, it automatically gets attached to the window object. You can access it using x, window.x, or this.x. They all point to the same memory location! 💡 Key Takeaway: Anything not inside a function sits in the Global Memory Space. Keeping this space clean is vital for performance and avoiding variable name collisions in large apps! It’s fascinating to see that even before we write our first line of code, JavaScript has already set up the entire "universe" for us to work in. #JavaScript #WebDevelopment #NamasteJavaScript #ExecutionContext #WindowObject #JSFundamentals #CodingJourney #FrontendEngineer
To view or add a comment, sign in
-
-
🧠 JavaScript Hoisting Explained Simply Hoisting is one of those JavaScript concepts that can feel confusing — especially when your code behaves unexpectedly. Here’s a simple way to understand it 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But there’s a catch 👇 🔹 Example with var console.log(a); var a = 10; Output: undefined Why? Because JavaScript internally treats it like: var a; console.log(a); a = 10; 🔹 What about let and const? console.log(b); let b = 20; This throws a ReferenceError. Because "let" and "const" are hoisted too — but they stay in a “temporal dead zone” until initialized. 🔹 Function hoisting Functions are fully hoisted: sayHello(); function sayHello() { console.log("Hello"); } This works because the function is available before execution. 🔹 Key takeaway • "var" → hoisted with "undefined" • "let/const" → hoisted but not initialized • functions → fully hoisted 💡 One thing I’ve learned: Many “weird” JavaScript bugs come from not understanding hoisting properly. Curious to hear from other developers 👇 Did hoisting ever confuse you when you started learning JavaScript? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Promise Chaining) You write this: Promise.resolve(1) .then((res) => { console.log(res); return res + 1; }) .then((res) => { console.log(res); return res + 1; }); 👉 Output: 1 2 Now try this 👇 Promise.resolve(1) .then((res) => { console.log(res); }) .then((res) => { console.log(res); }); 👉 Output: 1 undefined 🤯 Same chain… different result… why? This happens because of Promise Chaining 📌 What is Promise Chaining? 👉 It’s the process of passing the result from one .then() to the next 📌 What’s happening here? ✔ If you return a value: 👉 It goes to the next .then() ✔ If you don’t return anything: 👉 undefined is passed So this: .then((res) => { console.log(res); }) 👉 is actually: .then((res) => { console.log(res); return undefined; }) 📌 Important rule: 👉 Every .then() returns a new Promise 📌 Bonus case 👇 .then((res) => { return Promise.resolve(res + 1); }) 👉 Next .then() waits for it automatically 💡 Takeaway: ✔ Return value → passed to next .then() ✔ No return → undefined ✔ Returning Promise → waits automatically 👉 Promise chain is all about “what you return” 🔁 Save this for later 💬 Comment “promise” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Quirk: this behaves differently than you think This is one of the most confusing parts of JavaScript 👇 const user = { name: "Avinash", greet: function () { console.log(this.name); } }; user.greet(); // ? ✅ Output: "Avinash" Here, this refers to the object calling the function. Now look at this 👇 const greet = user.greet; greet(); // ? 💥 Output: undefined Why? Because this is no longer bound to user. In this case, this refers to the global object (or undefined in strict mode). Now the tricky part 👇 const user = { name: "Avinash", greet: () => { console.log(this.name); } }; user.greet(); // ? 💥 Output: undefined Why? Arrow functions don’t have their own this. They inherit it from their surrounding scope. 🚨 NEVER use this inside arrow functions for object methods. 💡 Takeaway: ✔ this depends on HOW a function is called ✔ Regular functions → dynamic this ✔ Arrow functions → lexical this ✔ Arrow + this in methods = bug waiting to happen 👉 Master this = fewer hidden bugs 🔁 Save this for later 💬 Comment "this" if it clicked ❤️ Like if this helped #javascript #frontend #webdevelopment #codingtips #js #developer
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