🌙 Evening Post — slice vs splice (Same Look, Different Behavior) This morning’s code was: let arr = [1, 2, 3, 4]; let a = arr.slice(1, 3); let b = arr.splice(1, 2); console.log(a); console.log(b); console.log(arr); 💡 Correct Output [2, 3] [2, 3] [1, 4] Yes — the first two lines look the same, but the array changes 👀 Let’s understand why. 🧠 Simple Explanation : 🔹 slice(start, end) Does NOT change the original array Returns a new array end index is not included arr.slice(1, 3) From [1, 2, 3, 4]: Takes index 1 and 2 Returns: [2, 3] Original arr is still: [1, 2, 3, 4] 🔹 splice(start, deleteCount) Changes the original array Removes elements Returns the removed elements arr.splice(1, 2) From [1, 2, 3, 4]: Removes 2 elements starting at index 1 Returns: [2, 3] Now the original array becomes: [1, 4] 🎯 Final Values a → [2, 3] b → [2, 3] arr → [1, 4] 🎯 Key Takeaways : slice() → non-mutating splice() → mutating slice uses end index splice uses delete count 📌 Many bugs happen because developers assume slice and splice are similar. 💬 Your Turn Which one surprised you more? 😄 Comment “slice 😮” or “splice 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
JavaScript Array Methods: Slice vs Splice
More Relevant Posts
-
🌙 Evening Post — Explanation & Answer ✅ Why This Map Has Two Entries This morning’s code was: const map = new Map(); map.set({}, "first"); map.set({}, "second"); console.log(map.size); 💡 Correct Output 2 Yes — two entries, not one 😄 Here’s why 👇 🧠 Simple Explanation : 🔹 Objects are compared by reference, not by value Even though both keys look like {}: {} !== {} Each {} creates a new object in memory. So JavaScript sees this as: Key 1 → one object reference Key 2 → another object reference They are completely different keys. 🔹 How Map works Map allows any type as a key Keys are matched by reference Different object references → different entries So: map.size // 2 🎯 Key Takeaways : Map keys are compared by reference {} and {} are never the same key Objects are not value-equal by default This behavior is different from plain objects 📌 To use the same key, you must reuse the same reference: const key = {}; map.set(key, "first"); map.set(key, "second"); 💬 Your Turn Did you expect the size to be 1 or 2? 😄 Comment “Got it wrong 😅” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Maps #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
🌙 Evening Post — Function Reference vs Function Call (Very Important!) This morning’s code was: function show() { return "Hello"; } console.log(show); console.log(show()); 💡 Correct Output : [ Function : show ] Hello (Exact formatting may vary by browser, but the meaning is the same.) 🧠 Simple Explanation : 🔹 Line 1: console.log(show); Here, we are NOT calling the function. show refers to the function itself JavaScript prints the function definition This is called a function reference So the output shows something like: [ Function : show ] 👉 You’re telling JS: “Show me the function, not run it.” 🔹 Line 2: console.log(show()); Now the function IS called. show(); // returns "Hello" So this becomes: console.log("Hello"); ✔ Output: Hello 🎯 Key Takeaways : show → function reference (no execution) show() → function execution Functions in JS are values, just like numbers or strings You can pass functions around without calling them 📌 This difference is very important in: callbacks event handlers React props higher-order functions 💬 Your Turn Did you already know this difference? 😄 Comment “Clear now ✅” or “Didn’t notice this before 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Functions #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
Quick JS Brain Teaser: What will be the output of this code? async function test() { console.log('1'); setTimeout(() => { console.log('2'); }, 0); await Promise.resolve(); console.log('3'); setTimeout(() => { console.log('4'); }, 0); console.log('5'); } test(); console.log('6'); A) 1, 6, 3, 5, 2, 4 B) 1, 3, 5, 6, 2, 4 C) 1, 6, 2, 3, 5, 4 D) 1, 2, 3, 4, 5, 6 Drop your answer in the comments and explain why! Does this match your expectations for execution context questions? #JavaScript #JavaScriptInterviewQuestion #JavaScriptFundamentals
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟵 Have you ever updated one variable… and another one changed automatically? 𝙋𝙖𝙪𝙨𝙚 𝙛𝙤𝙧 𝙖 𝙨𝙚𝙘𝙤𝙣𝙙 — 𝙬𝙤𝙪𝙡𝙙 𝙮𝙤𝙪 𝙚𝙭𝙥𝙚𝙘𝙩 𝙩𝙝𝙞𝙨 𝙘𝙤𝙙𝙚 𝙩𝙤 𝙢𝙪𝙩𝙖𝙩𝙚 𝙗𝙤𝙩𝙝 𝙫𝙖𝙡𝙪𝙚𝙨? { 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟷 = { 𝚗𝚊𝚖𝚎: "𝙰𝚕𝚎𝚡" }; 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟸 = 𝚞𝚜𝚎𝚛𝟷; 𝚞𝚜𝚎𝚛𝟸.𝚗𝚊𝚖𝚎 = "𝙹𝚘𝚑𝚗"; 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚞𝚜𝚎𝚛𝟷.𝚗𝚊𝚖𝚎); // "𝙹𝚘𝚑𝚗" } Why did user1 change? Because: • Both variables point to the same memory address • No copy was created • Only the reference was shared 𝘛𝘩𝘪𝘴 𝘪𝘴 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵’𝘴 𝘝𝘢𝘭𝘶𝘦 𝘷𝘴 𝘙𝘦𝘧𝘦𝘳𝘦𝘯𝘤𝘦 𝘣𝘦𝘩𝘢𝘷𝘪𝘰𝘳 — 𝘢𝘯𝘥 𝘪𝘵’𝘴 𝘥𝘦𝘦𝘱𝘭𝘺 𝘵𝘪𝘦𝘥 𝘵𝘰 𝘮𝘦𝘮𝘰𝘳𝘺. 𝙏𝙝𝙚 𝙈𝙚𝙣𝙩𝙖𝙡 𝙈𝙤𝙙𝙚𝙡 (𝙈𝙚𝙢𝙤𝙧𝙮 𝙁𝙞𝙧𝙨𝙩) JavaScript mainly uses two memory areas: -> Stack Memory • Stores primitive values • Fixed size • Fast access -> Heap Memory • Stores objects, arrays, functions • Dynamic size • Accessed via references 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙫𝙖𝙡𝙪𝙚: A copy of the actual value is passed. Primitives (number, string, boolean, null, undefined, symbol) are always passed by value. 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙧𝙚𝙛𝙚𝙧𝙚𝙣𝙘𝙚: A memory address (reference) is passed, not the object itself. Objects & arrays live in heap memory. #JavaScript #JSFundamentals #MemoryManagement #FrontendDevelopment #ReactJS #BugFixing #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
Evening Post — Why includes() Works but indexOf() Fails Here This morning’s code was: const arr = [1, 2, NaN, 4]; console.log(arr.includes(NaN)); console.log(arr.indexOf(NaN)); 💡 Correct Output true -1 Yes — same value, same array, different results 😄 Let’s understand why. 🧠 Simple Explanation : 🔹 includes() uses SameValueZero comparison That means: It can correctly compare NaN It treats NaN as equal to NaN So: arr.includes(NaN) ✔ Finds NaN ✔ Returns: true 🔹 indexOf() uses strict equality (===) Important rule 👇 👉 In JavaScript: NaN === NaN // false So when indexOf() checks each element: It compares NaN === NaN That comparison always fails Because of this: arr.indexOf(NaN) ❌ Cannot find NaN ✔ Returns: -1 🎯 Key Takeaways : includes() can find NaN indexOf() cannot find NaN NaN is the only value that is not equal to itself Prefer includes() for value checks 📌 This difference has caused real production bugs. 💬 Your Turn Did you expect both lines to behave the same? 😄 Comment “Surprising 😮” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
Evening Post — Why includes() Works but indexOf() Fails Here This morning’s code was: const arr = [1, 2, NaN, 4]; console.log(arr.includes(NaN)); console.log(arr.indexOf(NaN)); 💡 Correct Output true -1 Yes — same value, same array, different results 😄 Let’s understand why. 🧠 Simple Explanation : 🔹 includes() uses SameValueZero comparison That means: It can correctly compare NaN It treats NaN as equal to NaN So: arr.includes(NaN) ✔ Finds NaN ✔ Returns: true 🔹 indexOf() uses strict equality (===) Important rule 👇 👉 In JavaScript: NaN === NaN // false So when indexOf() checks each element: It compares NaN === NaN That comparison always fails Because of this: arr.indexOf(NaN) ❌ Cannot find NaN ✔ Returns: -1 🎯 Key Takeaways : includes() can find NaN indexOf() cannot find NaN NaN is the only value that is not equal to itself Prefer includes() for value checks 📌 This difference has caused real production bugs. 💬 Your Turn Did you expect both lines to behave the same? 😄 Comment “Surprising 😮” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
Reversing a string in JavaScript can be done in more than one way. I revisited this problem today and tried three approaches, each with a different mindset: // 1. Using built-in methods const reverse1 = (str) => str.split("").reverse().join(""); // 2. Using a loop (more control) function reverse2(str) { let result = ""; for (let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result; } // 3. Using reduce (functional style) const reverse3 = (str) => str.split("").reduce((acc, char) => char + acc, ""); console.log(reverse1("hello")); //"olleh" console.log(reverse2("hello")); //"olleh" console.log(reverse3("hello")); //"olleh" Methods I used: • Built-in methods → concise and readable • Loop → full control and clarity • reduce → functional and expressive This reminded me that in real projects, how you think about a problem matters as much as the answer itself. Still learning, still building, still showing up. #JavaScript #FrontendDevelopment #LearningInPublic #JuniorDeveloper
To view or add a comment, sign in
-
𝐘𝐨𝐮𝐫 𝐮𝐬𝐞𝐌𝐞𝐦𝐨 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐝𝐨𝐢𝐧𝐠 𝐚𝐛𝐬𝐨𝐥𝐮𝐭𝐞𝐥𝐲 𝐧𝐨𝐭𝐡𝐢𝐧𝐠 𝐟𝐨𝐫 𝐲𝐨𝐮𝐫 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐜𝐞. I've seen so many teams use `useMemo` to cache expensive computations, only to find their component still re-renders and re-calculates everything. The culprit? Often, it's the dependencies array. If you're doing something like this: ```jsx const expensiveResult = useMemo(() => { // complex calculation }, [someArray.map(item => item.id)]); // ❌ Bad: new array every render ``` Even if the `ids` are the same, someArray.map(...) creates a new array reference on every render. `useMemo` sees a new reference and re-runs the computation. The fix? Ensure your dependencies are stable. If `someArray` itself is stable, then use that. If you need a derived list, memoize that derived list first if it's based on volatile data. Or, if possible, derive a primitive value (like a hash or a count) that represents the change. ```jsx const stableIds = useMemo(() => someArray.map(item => item.id), [someArray]); // ✅ Better: stable IDs const expensiveResult = useMemo(() => { // complex calculation using stableIds }, [stableIds]); ``` This small change can make a huge difference in CPU-bound components, preventing unnecessary re-executions and keeping your React app snappy. It's about memoizing the right thing at the right level. What are your go-to strategies for making sure `useMemo` actually pulls its weight? #React #Frontend #Performance #JavaScript #WebDevelopment
To view or add a comment, sign in
-
forwardRef isn’t about refs. It’s about ownership. A real UI case where it actually makes sense. Parent component: import { useRef } from "react"; import TextInput from "./TextInput"; export default function Form() { const inputRef = useRef<HTMLInputElement>(null); return ( <> <TextInput ref={inputRef} placeholder="Email" /> <button onClick={() => inputRef.current?.focus()}> Focus input </button> </> ); } The parent needs imperative control. Child component: import { forwardRef } from "react"; type TextInputProps = { placeholder: string; }; const TextInput = forwardRef<HTMLInputElement, TextInputProps>( ({ placeholder }, ref) => { return <input ref={ref} placeholder={placeholder} />; } ); export default TextInput; This works, but notice the tradeoff. By adding forwardRef: - the child exposes its DOM - the parent depends on internal details - a component boundary is crossed That’s the real cost of forwardRef. Takeaway forwardRef is not a helper. It’s an architectural decision. #ReactJS #FrontendArchitecture #ReactPatterns #JavaScript #FrontendEngineer
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