🚀 Add Two Numbers WITHOUT Using + in JavaScript 😳 Here’s a classic trick that interviewers LOVE 👇 Instead of using +, we use bitwise operators: 👉 XOR (^) → gives sum without carry 👉 AND (&) → gives carry 👉 << 1 → shifts carry to correct position 💡 Logic: Keep adding the partial sum and carry until carry becomes 0 Why this matters? Because this is exactly how computers perform addition internally at the binary level. 🧠 It’s not just a trick — it’s understanding how systems really work. 🔥 Example: 5 (0101) + 3 (0011) → Result = 8 (1000) 🎯 Where this helps: ✔️ Coding interviews ✔️ Bit manipulation problems ✔️ Deep understanding of low-level operations ✅ Using Bitwise Operators: function sum(a, b) { while (b !== 0) { let carry = a & b; // common bits (carry) a = a ^ b; // sum without carry b = carry << 1; // shift carry } return a; } 🔢 Example: sum(5, 3) First convert numbers to binary: 5 = 0101 3 = 0011 🧠 Core Idea This function mimics how addition works at the bit level: XOR (^) → adds bits without carry AND (&) → finds the carry << 1 → moves carry to the next position 🔁 Step-by-Step Execution 👉 Iteration 1 a = 0101 (5) b = 0011 (3) Step 1: carry carry = a & b = 0101 & 0011 = 0001 Step 2: sum without carry a = a ^ b = 0101 ^ 0011 = 0110 (6) Step 3: shift carry b = carry << 1 = 0001 << 1 = 0010 (2) 👉 Iteration 2 a = 0110 (6) b = 0010 (2) Step 1: carry carry = 0110 & 0010 = 0010 Step 2: sum without carry a = 0110 ^ 0010 = 0100 (4) Step 3: shift carry b = 0010 << 1 = 0100 (4) 👉 Iteration 3 a = 0100 (4) b = 0100 (4) Step 1: carry carry = 0100 & 0100 = 0100 Step 2: sum without carry a = 0100 ^ 0100 = 0000 (0) Step 3: shift carry b = 0100 << 1 = 1000 (8) 👉 Iteration 4 a = 0000 (0) b = 1000 (8) Step 1: carry carry = 0000 & 1000 = 0000 Step 2: sum without carry a = 0000 ^ 1000 = 1000 (8) Step 3: shift carry b = 0000 << 1 = 0000 ✅ Loop Ends Now b = 0, so loop stops. 👉 Final Answer: a = 1000 (8) 🎯 Final Understanding (Important for Interviews) We keep adding partial sum (a ^ b) And carry separately ((a & b) << 1) Repeat until no carry left 🔥 One-Line Intuition 👉 “This is binary addition where we separate sum and carry, then combine them until carry becomes zero.” Follow for more real-world coding insights 🚀 #javascript #coding #webdevelopment #programming #100daysofcode #developer #tech #interviewprep #bitwise #learncoding #dsa #ai
Add Numbers Without Plus in JavaScript Using Bitwise Operators
More Relevant Posts
-
💡 JavaScript IIFE (Immediately Invoked Function Expression) and Interview Classic: The setTimeout + var Trap Ever seen this weird-looking function? 👇 (function() { console.log("Hello World"); })(); 🤔 Looks different, right? 🧠 What is an IIFE? 👉 An IIFE (Immediately Invoked Function Expression) is a function that: ✔️ Is defined ✔️ And executed immediately No need to call it separately! 🔍 How does it work? (function(name) { console.log("Hello " + name); })("Javascript"); 👉 Output: Hello Javascript 🚀 Why do we use IIFE? 🔒 1. Creates a private scope Variables inside it cannot be accessed outside (function() { var secret = "hidden"; })(); ❌ secret is not accessible outside 🌍 2. Avoids global scope pollution Keeps your code clean and prevents conflicts. ⚡ 3. Helps with closures (classic interview use-case) This is one of the most famous questions asked in interviews 👇 for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 🤔 What will be the output? 👉 Most people expect: 0 1 2 3 4 ❌ But the actual output is: 5 5 5 5 5 🧠 What’s happening here? 🔹 var is function-scoped, not block-scoped 🔹 The loop finishes execution first → i becomes 5 🔹 setTimeout runs later (asynchronously) 🔹 All callbacks share the same reference of i 👉 So every console.log prints 5 ✅ How to fix it? 🔹a) Using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 0 1 2 3 4 🔹b) Using Closure (if you must use var): for (var i = 0; i < 5; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } What is this (function(i) { ... })(i)? 👉 This is an Immediately Invoked Function Expression (IIFE) (It runs immediately after being defined) So for each loop iteration: 🔹A new function is created 🔹It gets its own copy of i as a parameter 👉How closure helps here Inside the loop: First iteration → i = 0 → function runs with i = 0 → setTimeout remembers this i Second iteration → i = 1 → new function with i = 1 → new closure created 👉 This happens for all iterations So instead of sharing one i, we now have 5 different i values stored separately Final result After 1 second: 0 1 2 3 4 ✅ Each setTimeout prints its own preserved value 🔥 Simple analogy Think of it like: ❌ Without closure → 5 people sharing one notebook ✅ With closure → each person gets their own notebook 🚀 Key takeaway 👉 Closures allow functions to remember the variables from their scope 👉 IIFE creates a new scope for each iteration 👉 That’s why this fixes the var problem #JavaScript #CodingInterview #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
💡 JavaScript Shallow Copy vs Deep Copy 1. Shallow Copy: 📌 Copies only top-level properties (primitives). 📌 Nested objects (arrays, objects) share the same reference. 🎙️ Modifying a top-level primitive in the copy does not affect the original, but modifying a nested object will affect the original, because both share the same reference. 💡 Example: const original= { a: 1, b: { c: 2 } }; const copy= { ...original }; copy.a =100; copy.b.c =200; console.log(original.a); // 1 top-level primitive unaffected console.log(original.b.c); // 200 nested object changed 2. Deep Copy: 📌 Creates a completely independent copy of the object, including all nested objects or arrays. 📌 Modifying any part of the deep copy, including deeply nested properties, has no affect on the original object ⚙️ Methods: Simple objects: JSON.parse(JSON.stringify(obj)) Complex objects: structuredClone(obj) or lodash.cloneDeep(obj) 💡 Example: const original = { name: "Vijay", hobbies: ["Acting", "Dancing"], address: { city: "Ramnad", country: "India" } }; const copy = structuredClone(original); copy.name = "Ajith"; copy.hobbies.push("Racing"); copy.address.city = "Chennai"; console.log(original); /* { name: "Vijay", hobbies: ["Acting", "Dancing"], address: { city: "Ramnad", country: "India" } } */ console.log(copy); /* { name: "Ajith", hobbies: ["Acting", "Dancing", "Racing"], address: { city: "Chennai", country: "India" } } */ #JavaScript #Coding #Programming #TechPost #ShallowCopy #DeepCopy
To view or add a comment, sign in
-
🔐 JavaScript Closures — the concept that confuses juniors, impresses interviewers, and powers half your codebase without you realizing it. Let's break it down simply. No jargon. No confusion. —————————————————— What is a Closure? —————————————————— A closure is a function that remembers the variables from its outer scope — even after the outer function has finished executing. Think of it like this: Imagine you write a letter, seal it in an envelope, and give it to someone. Even after you leave the room, the letter still carries your words. That sealed envelope = a closure. —————————————————— Let's see it in code 👇 —————————————————— function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 outer() has finished. But inner() still holds a reference to count. That's a closure. The inner function carries its environment with it — like a backpack full of variables. —————————————————— Why does this matter? Real-world use cases 🔥 —————————————————— ✅ Data privacy — encapsulate private variables, no class needed ✅ Factory functions — create configurable functions dynamically ✅ Memoization — cache results using a closed-over object ✅ Event handlers — capture loop variables correctly in callbacks —————————————————— The classic interview gotcha ⚠️ —————————————————— for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } // Prints: 3, 3, 3 ❌ Fix it with let — which creates a new binding per iteration: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } // Prints: 0, 1, 2 ✅ —————————————————— 💡 Quick recap: → Closure = function + its surrounding scope → The scope is preserved even after the outer function returns → Used everywhere: React hooks, event listeners, module patterns, caching —————————————————— Closures aren't magic — they're just functions with a good memory. 🧠 Once you truly understand closures, concepts like React's useState, debounce, and the module pattern all start to make perfect sense. Save this post for your next JS interview prep session! 🔖 What's the closure concept that tripped you up the most? Drop it below 👇 ♻️ Repost to help a fellow dev crack this once and for all. #JavaScript #Closures #WebDevelopment #Frontend #Programming #JSInterviewPrep #LearnJavaScript #SoftwareEngineering #100DaysOfCode #CodeNewbie #TechCommunity #DeveloperTips #ReactJS
To view or add a comment, sign in
-
-
⏱️ 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗖𝗼𝗱𝗲 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Async testing in JavaScript is one of those areas where things look correct — but fail silently if done wrong. 📞 🔙 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸-𝗕𝗮𝘀𝗲𝗱 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 When your function depends on callbacks, your test must explicitly tell the test runner when it's done. it("should fetch data (callback)", (done) => { fetchData((err, data) => { if (err) return done(err); expect(data).toBe("hello"); done(); // critical! }); }); ❯❯❯❯ If you see callbacks → use done carefully. ⏳ 𝗣𝗿𝗼𝗺𝗶𝘀𝗲-𝗕𝗮𝘀𝗲𝗱 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 Cleaner than callbacks, but still easy to mess up. You must return the promise from your test. it("should fetch data (promise)", () => { return expect(fetchData()).resolves.toBe("hello"); }); ❯❯❯❯ Always return the promise OR use .resolves/.rejects. 🔄 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 (𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱) The cleanest and most readable approach. it("should fetch data (async/await)", async () => { const data = await fetchData(); expect(data).toBe("hello"); }); Handling errors - it("should throw error", async () => { await expect(fetchData()).rejects.toThrow("error"); }); ❯❯❯❯ If you use async, always use await where needed. ✍ 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ♦️ Callbacks → use done() ♦️ Promises → return the promise ♦️ Async/Await → use await properly ♦️ Always test both success AND failure paths. 👉 We’ll dive deeper into 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝘀𝗲𝘀 𝗼𝗳 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 in the upcoming posts. Stay tuned!! 🔔 Follow Nitin Kumar for daily valuable insights on LLD, HLD, Distributed Systems and AI. ♻️ Repost to help others in your network. #javascript #nodejs #testing #tdd #mocha #sinon #async
To view or add a comment, sign in
-
-
🔥 From JavaScript Interview Questions Challenge: Refactor a function to use lazy evaluation, processing only what’s necessary. Problem Statement The following function calculates the squares of all numbers in a large array and sums them. However, it computes all squares upfront, wasting resources. function sumOfSquares(arr) { const squares = arr.map((num) => num ** 2); return squares.reduce((sum, square) => sum + square, 0); } console.log(sumOfSquares([1, 2, 3, 4, 5])); Solution Use a generator function to calculate squares lazily, avoiding upfront computation. Optimized Code function* lazySquares(arr) { for (const num of arr) { yield num ** 2; // Compute squares lazily } } function sumOfSquares(arr) { let sum = 0; for (const square of lazySquares(arr)) { sum += square; } return sum; } console.log(sumOfSquares([1, 2, 3, 4, 5])); // 55 Explanation 1. Lazy Evaluation: Squares are computed only when required, saving memory for large arrays. 2. Efficiency: Eliminates intermediate storage, reducing space complexity. #javascript #lazyevaluation #generators #interviewprep
To view or add a comment, sign in
-
-
Most developers use JavaScript string methods daily. But very few understand how they actually work under the hood. So I decided to go deeper. In this blog, I break down: • What string methods really are • Why polyfills exist and when they matter • How to implement methods like includes, indexOf, and trim from scratch • Common string problems asked in interviews • The core logic behind string manipulation once you understand the logic, you don’t rely on memorization anymore. https://lnkd.in/gpAPF2_7 #javascript #webdevelopment #frontend #coding #programming #learninpublic #developers #softwareengineering #interviewprep
To view or add a comment, sign in
-
Most JavaScript bugs aren't caused by complex logic. They come from choosing the wrong array method. The difference between find() and filter(), map() and forEach(), or some() and every() looks small-until it reaches production. That's where performance, readability, and hidden bugs start to matter. Examples: filter()[0] instead of find() → unnecessary full array scan Using forEach() when map() should return transformed data → broken data pipelines Calling sort() directly in React state silent mutation bugs Using filter().length > 0 instead of some() → extra work for no reason Overusing reduce() for simple logic → clever code, poor readability Great developers don't just know array methods. They know: When to use them When not to use them Their performance cost Their side effects Their production impact Simple rule: Code should not only work. It should be readable, predictable, and efficient. Because in real applications, small method choices create big system behavior. The engineers I respect most don't use reduce() to look smart. They use find() instead of filter()[0]. They spread before sort(). They know forEach() returns nothing. That's the difference between writing JavaScript and engineering with Javascript
To view or add a comment, sign in
-
-
Many developers struggle with unexpected bugs when working with objects in JavaScript — especially when copying data. One of the most misunderstood concepts is: Deep Copy vs Shallow Copy If not handled properly, it can lead to data mutation issues and hard-to-debug problems in real applications. In this article, I’ve broken it down in a simple and practical way: ✔ Clear definition of shallow copy and deep copy ✔ Real-world examples you can relate to ✔ Differences explained in a structured format ✔ When to use which approach ✔ Common pitfalls to avoid Whether you're a beginner or preparing for interviews, this will strengthen your fundamentals. 🔗 Read the full article: https://lnkd.in/gt9zcmkP Would love to hear your thoughts — have you faced this issue before? #JavaScript #Programming #WebDevelopment #Frontend #SoftwareDevelopment #Coding #Developers
To view or add a comment, sign in
-
🧪 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 - 𝗦𝘁𝘂𝗯𝘀 𝘃𝘀 𝗦𝗽𝗶𝗲𝘀 𝘃𝘀 𝗠𝗼𝗰𝗸𝘀 When you start writing serious unit tests in JavaScript, you quickly realize that testing real dependencies (APIs, databases) makes your tests slow, flaky, and produces side effects. That’s where Stubs, Spies and Mocks come in. 🔍 𝗦𝗽𝗶𝗲𝘀 — “𝗢𝗯𝘀𝗲𝗿𝘃𝗲, 𝗱𝗼𝗻’𝘁 𝗶𝗻𝘁𝗲𝗿𝗳𝗲𝗿𝗲” A spy is used when you want to track how a function is called without changing its actual behavior. 𝗨𝘀𝗲 𝗖𝗮𝘀𝗲𝘀 ♦️ Was the function called? ♦️ How many times? ♦️ With what arguments? 👉 The original function still runs — you're just watching it. 🎭 𝗦𝘁𝘂𝗯𝘀 — “𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝘁𝗵𝗲 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿” A stub not only tracks calls but also replaces the actual implementation. 𝗨𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 ♦️ Avoid calling real APIs ♦️ Return predefined values ♦️ Simulate function execution 👉 The real function is never executed. 🎯 𝗠𝗼𝗰𝗸𝘀 — “𝗘𝘅𝗽𝗲𝗰𝘁𝗮𝘁𝗶𝗼𝗻 + 𝗩𝗲𝗿𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻” A mock is like a strict version of a stub, you define expectations upfront and test fails if expectations are not met. 𝗨𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 ♦️ When interaction itself is critical ♦️ You want strict contract testing Example - const mock = sinon.mock(api); mock.expects("getUser") .once() .returns({ id: 1 }); api.getUser(); mock.verify(); 👉 If getUser() is not called → test fails. 🧠 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗪𝗵𝗮𝘁? 🔍 Use Spies → When you want visibility (logging, analytics, side effects) 🎭 Use Stubs → When you need control (API, DB, randomness) 🎯 Use Mocks → When behavior contract matters (critical flows) 🧰 𝗦𝗶𝗻𝗼𝗻.𝗷𝘀 𝗟𝗶𝗯𝗿𝗮𝗿𝘆 Sinon.js is a powerful standalone library for - ♦️ Spies ♦️ Stubs ♦️ Mocks ♦️ Fake timers ♦️ Works with any test framework (Mocha, Jest, etc.) 👉 We’ll dive deeper into 𝗔𝘀𝘆𝗻𝗰 𝗖𝗼𝗱𝗲 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 in the upcoming posts. Stay tuned!! 🔔 Follow Nitin Kumar for daily valuable insights on LLD, HLD, Distributed Systems and AI. ♻️ Repost to help others in your network. #javascript #nodejs #testing #tdd #mocha #sinon
To view or add a comment, sign in
-
-
✅ JavaScript Advanced Concepts You Should Know 🔍💻 These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps. 1️⃣ Closures A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Promises & Async/Await Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O. // Promise chain fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err)); // Async/Await (cleaner) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 3️⃣ Hoisting Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone." console.log(x); // undefined (hoisted, but not initialized) var x = 5; console.log(y); // ReferenceError (temporal dead zone) let y = 10; 4️⃣ The Event Loop JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block. 5️⃣ this Keyword Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding. const obj = { name: "Sam", greet() { console.log(`Hi, I'm ${this.name}`); }, }; obj.greet(); // "Hi, I'm Sam" // In arrow function, this is lexical const arrowGreet = () => console.log(this.name); // undefined in global 6️⃣ Spread & Rest Operators Spread (...) expands iterables; rest collects arguments into arrays. const nums = [1, 2, 3]; const more = [...nums, 4]; // [1, 2, 3, 4] function sum(...args) { return args.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 7️⃣ Destructuring Extract values from arrays/objects into variables. const person = { name: "John", age: 30 }; const { name, age } = person; // name = "John", age = 30 const arr = [1, 2, 3]; const [first, second] = arr; // first = 1, second = 2 8️⃣ Call, Apply, Bind Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function. function greet() { console.log(`Hi, I'm ${this.name}`); } greet.call({ name: "Tom" }); // "Hi, I'm Tom" const boundGreet = greet.bind({ name: "Alice" }); boundGreet(); // "Hi, I'm Alice" 9️⃣ 💡 Practice these in a Node.js REPL or browser console to see how they interact. 💬 Tap ❤️ if you're learning something new!
To view or add a comment, sign in
More from this author
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
Follow for more