🚀 Day 29/30 – Design ArrayWrapper Class in JavaScript 🧠 📌 Problem : Create a class ArrayWrapper that ✅ Feature 1 – Addition (+ operator) When two instances are added: obj1 + obj2 It should return the sum of all elements in both arrays. ✅ Feature 2 – String Conversion When calling: String(obj) It should return: "[1,2,3]" Exactly like a normal array string format. 🧠 Example const obj1 = new ArrayWrapper([1,2]); const obj2 = new ArrayWrapper([3,4]); obj1 + obj2; // 10 String(obj1); // "[1,2]" String(obj2); // "[3,4]" 💡 JavaScript Solution class ArrayWrapper { constructor(nums) { this.nums = nums; } valueOf() { return this.nums.reduce((sum, num) => sum + num, 0); } toString() { return `[${this.nums.join(",")}]`; } } 🔎 Why This Works : 🔹 valueOf() JavaScript calls valueOf() when using the + operator on objects. So: obj1 + obj2 Becomes : obj1.valueOf() + obj2.valueOf() Which returns the total sum. 🔹 toString() When String(obj) is called, JavaScript invokes: 🔹 obj.toString() So we return a formatted array string. 🧠 What This Teaches ✅ Object-to-primitive conversion ✅ Operator overloading behavior in JS ✅ valueOf() vs toString() ✅ How JavaScript handles coercion internally ✅ Custom class design ⚡ Real-World Insight Date objects behave with + Number objects convert to primitives Custom libraries control serialization Understanding this means you now understand JavaScript coercion rules deeply. #JavaScript #30DaysOfJavaScript #CodingChallenge #OOP #JavaScriptInternals #FrontendDevelopment #WebDevelopment #SoftwareEngineering #LearnToCode #Programming #InterviewPrep #JSDeveloper #CleanCode #100DaysOfCode JavaScript valueOf example Override toString JavaScript class Operator overloading JavaScript JavaScript object to primitive conversion Custom class JavaScript interview question JavaScript + operator with objects Implement ArrayWrapper JS JavaScript coercion explained
JavaScript ArrayWrapper Class Implementation
More Relevant Posts
-
Event Loop Deep Dive The Heartbeat of JavaScript JavaScript looks simple on the surface… but behind the scenes, something powerful is running everything the Event Loop. If you truly understand this, you move from coder pro developer What is the Event Loop? The Event Loop is a mechanism that allows JavaScript to handle multiple tasks without being multi-threaded. It decides what runs now and what waits. Core Components You Must Know Call Stack Where your code executes line by line Sync code runs here instantly Web APIs (Browser/Node) Handles async tasks like: setTimeout fetch API DOM events Callback Queue (Task Queue) Stores callbacks from async operations Microtask Queue (VIP Queue) Higher priority than callback queue: Promises (.then, catch) MutationObserver Execution Flow (Simple Way) Code enters Call Stack Async tasks go to Web APIs When ready → move to Queue Event Loop checks: Is Call Stack empty? YES Execute from Microtask Queue first Then Callback Queue Golden Rule Microtasks ALWAYS run before Macrotasks Example: JavaScript Copy code console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output: Copy code Start End Promise Timeout Why This Matters Fix async bugs Optimize performance Write non-blocking code Crack interviews easily Pro Tip If your app feels slow… It’s not JavaScript It’s your understanding of the Event Loop Final Thought Mastering the Event Loop is like unlocking the brain of JavaScript. Once you get it… You don’t just write code you control execution #JavaScript #WebDevelopment #EventLoop #AsyncJS #CodingLife #FrontendDev
To view or add a comment, sign in
-
-
🚀 Just published a new blog on Understanding Objects in JavaScript. In this article, I explain what objects are, why they are important in JavaScript, and how they store data using key–value pairs. I also covered creating objects, accessing properties using dot and bracket notation, updating values, adding or deleting properties, and looping through object keys. 📖 Read the full article here: https://lnkd.in/gbxx6N2G Inspired by the amazing teaching of Hitesh Choudhary Sir and Piyush Garg Sir from Chai Aur Code. ☕💻 #javascript #webdevelopment #learninginpublic #chaiAurCode
To view or add a comment, sign in
-
🚀 Day 74 — Understanding Variable Access Behavior in JavaScript (Closures) Today I explored one of the most powerful and interesting behaviors in JavaScript — how functions access variables, even after execution is completed. This concept is known as Closures. 🔹 The Question I Had How can a function remember variables that were created inside another function? Logically, once a function finishes execution, its variables should disappear from memory. But in JavaScript… they don’t always. 🔹 Example function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 🔎 What Actually Happens? When outer() runs: ✅ A Lexical Environment is created ✅ Variable count is stored in memory ✅ The inner() function is returned Even after outer() finishes execution, JavaScript does not destroy the variable count. Why? Because the returned function (inner) still references it. This preserved connection between a function and its surrounding environment is called a Closure. 🔹 Variable Access Behavior Explained JavaScript follows Lexical Scoping, meaning: 👉 A function accesses variables based on where it was defined, not where it is executed. So inner() always has access to: Its own variables Parent function variables Global variables This chain of access explains how variable lookup works internally. 🔹 Why Closures Matter in Real Applications Closures are used for: ✅ Data hiding & private variables ✅ Maintaining state ✅ Event handlers ✅ Callbacks ✅ React hooks & modern frameworks Example of data privacy: function createUser() { let password = "secret"; return { getPassword: () => password }; } Here, password cannot be accessed directly from outside. 📌 Key Takeaway Functions in JavaScript are not just blocks of code. They carry their memory, scope, and environment wherever they go. Understanding closures helped me finally connect: ✔ Scope Chain ✔ Lexical Environment ✔ Variable Access Behavior JavaScript feels less magical and more logical now. #Day74 #JavaScript #Closures #WebDevelopment #LearningInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
JavaScript is easy to start with - but surprisingly hard to truly understand. Many developers can write JavaScript. Far fewer understand what actually happens under the hood. And that difference is often what separates someone who just writes code from someone who can truly reason about it. Here are a few core JavaScript internals every developer should understand: 🔹 Execution Context & Call Stack JavaScript code runs inside execution contexts. Each function call creates a new execution context that gets pushed onto the call stack. Understanding this explains recursion behavior, stack overflows, and how scope is resolved during execution. 🔹 Event Loop JavaScript itself runs on a single thread, but asynchronous behavior is enabled by the runtime (e.g., the browser or Node.js). The event loop coordinates the call stack, task queue (macrotasks), and microtask queue (Promises, queueMicrotask, etc.) to decide when callbacks are executed. 🔹 Closures A closure occurs when a function retains access to variables from its lexical scope, even after the outer function has finished executing. Closures are widely used for encapsulation, stateful functions, and many library/framework patterns. 🔹 Prototypes & Inheritance JavaScript uses prototype-based inheritance. Objects can inherit properties and methods through the prototype chain. Even modern "class" syntax is syntactic sugar on top of this mechanism. 🔹 Hoisting During the creation phase of an execution context, declarations are processed before code execution. Function declarations are fully hoisted, while "var" is hoisted but initialized with "undefined". "let" and "const" are hoisted but remain in the Temporal Dead Zone until initialization. 🔹 The "this" keyword "this" is determined by how a function is called, not where it is defined. Its value depends on the call-site (method call, constructor call, explicit binding with "call/apply/bind", or arrow functions which capture "this" lexically). Once you understand these mechanics, JavaScript stops feeling "magical" - and becomes far more predictable. What JavaScript concept took you the longest to fully understand? #javascript #webdevelopment #softwareengineering #frontend
To view or add a comment, sign in
-
-
Revisiting the JavaScript Event Loop Sometimes going back to fundamentals is just as important as building new things. Today I revisited how the JavaScript Event Loop works a concept we use daily but don’t always think about deeply. A quick refresher: • JavaScript runs on a single-threaded call stack • Async operations are handled outside the main thread • Completed tasks move into queues • The Event Loop executes them when the call stack is empty One thing worth remembering: Promises (microtasks) are always prioritized over callbacks like setTimeout Even after working with async code regularly, understanding why things execute in a certain order is what really helps in debugging and writing better code. 📖 Article: https://lnkd.in/dnYVfHrQ #JavaScript #NodeJS #EventLoop #AsyncProgramming #BackendDevelopment
To view or add a comment, sign in
-
📢 Next Blog is Here! The Magic of this, call(), apply() and bind() in JavaScript ✨ 🔗 Read here: https://lnkd.in/gmmYsRqv Topics covered ✍️: ⟶ What this means in JavaScript ⟶ this inside normal functions and objects ⟶ What call() does and how to use it ⟶ What apply() does (with array arguments) ⟶ What bind() does and why it's different ⟶ Difference between call, apply, and bind ⟶ Hands-on assignment to practice all three I would also like to extend a special thanks to my mentors, Hitesh sir and Piyush sir, for their invaluable guidance and support #WebDev #JavaScript #100DaysOfCode #Chai Aur Code
To view or add a comment, sign in
-
What do you think will be the output of these expressions in javascript? {} + [] [] + {} {} + {} [] + [] At first glance, most developers assume JavaScript will treat these as normal object or array operations. But the real reason behind the output is type coercion and how JavaScript converts objects and arrays into primitive values when using the + operator. When the + operator is used with objects or arrays, JavaScript tries to convert them into primitive values (usually strings). An empty array [] becomes an empty string "" An object {} becomes "[object Object]" After this conversion, the + operator performs string concatenation. So the expressions effectively become: "[object Object]" + "" "" + "[object Object]" "[object Object]" + "[object Object]" "" + "" Understanding this behavior is important because JavaScript’s implicit type coercion can sometimes lead to unexpected results in real-world applications. A simple rule to remember: {} → "[object Object]" [] → "" Once you remember this conversion, these puzzles become much easier to reason about. For more insightful content checkout below: 🟦 𝑳𝒊𝒏𝒌𝒆𝒅𝑰𝒏 - https://lnkd.in/dwi3tV83 ⬛ 𝑮𝒊𝒕𝑯𝒖𝒃 - https://lnkd.in/dkW958Tj 🟥 𝒀𝒐𝒖𝑻𝒖𝒃𝒆 - https://lnkd.in/dDig2j75 or Priya Frontend Vlogz 🔷 𝐓𝐰𝐢𝐭𝐭𝐞𝐫 - https://lnkd.in/dyfEuJNt #frontend #javascript #react #reactjs #html #css #typescript #es6 #interviewquestions #interview #interviewpreparation
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop (Clearly & Practically) | Post 2 JavaScript is single-threaded — yet it handles asynchronous tasks like a pro. The secret behind this is the Event Loop 🔁 --- 📌 What is the Event Loop? The Event Loop is a mechanism that continuously checks: 👉 “Is the Call Stack empty?” If yes, it pushes pending tasks into execution. --- 🧩 Core Components 🔹 Call Stack Executes synchronous code line by line. 🔹 Web APIs (Browser / Node.js) Handles async operations like: - setTimeout - API calls - File operations 🔹 Callback Queue Stores callbacks once async tasks are completed. 🔹 Event Loop Moves callbacks from the queue to the Call Stack when it's free. --- 🔁 How It Works 1. Execute synchronous code 2. Send async tasks to Web APIs 3. Once done → push to Callback Queue 4. Event Loop checks → moves to Call Stack --- 🧠 Example console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); 👉 Output: Start → End → Async Task Even with "0ms", async tasks wait until the stack is empty. --- ⚡ Important Concept 👉 Microtasks vs Macrotasks ✔️ Microtasks (High Priority) - Promise.then - async/await ✔️ Macrotasks - setTimeout - setInterval 📌 Microtasks always execute before macrotasks. --- 🎯 Why You Should Care Understanding the Event Loop helps you: ✅ Write non-blocking, efficient code ✅ Debug async behavior easily ✅ Build scalable applications ✅ Crack JavaScript interviews --- 💬 Mastering this concept is a game-changer for every JavaScript developer. #JavaScript #EventLoop #WebDevelopment #NodeJS #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽: 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗮𝗻𝗱 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗖𝗼𝗱𝗲 You want to understand how JavaScript works. Let's look at an example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you think the output will be? - Start - End - Promise - Timeout This happens because JavaScript runs code in a specific order. - Synchronous code runs line by line. - Asynchronous code runs in the background. JavaScript uses something called the Event Loop to manage tasks. - The Event Loop checks for tasks to run. - It uses two queues: microtasks and macrotasks. - Microtasks are small, important tasks like Promises. - Macrotasks are normal asynchronous tasks like setTimeout. When you run the code, here's what happens: 1. JavaScript runs the synchronous code: Start 2. It schedules the setTimeout task. 3. It runs the final synchronous line: End 4. The Event Loop checks the microtask queue and runs the Promise callback: Promise 5. Finally, it checks the macrotask queue and runs the setTimeout callback: Timeout Understanding the Event Loop helps you work with: - API requests - Asynchronous tasks Try to predict the output of this code: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Use the rule we learned: - Synchronous code - Microtasks (Promises) - Macrotasks (Timers, setTimeout) Write your answer in the comments. Source: https://lnkd.in/gbAJefcw
To view or add a comment, sign in
-
🚀 JavaScript Functions — Explained Functions are the backbone of JavaScript What is a Function? >> A function is a reusable block of code designed to perform a specific task. 1. Function Declaration: A function defined using the function keyword with a name. function greet(name) { return "Hello " + name; } ✔️ Hoisted (can be used before declaration) 2. Function Expression: A function stored inside a variable. const greet = function(name) { return "Hello " + name; }; ❌ Not hoisted like declarations 3. Arrow Function: A shorter syntax for writing functions using =>. const greet = (name) => "Hello " + name; ✔️ Clean and concise ⚠️ Does not have its own this 4. Parameters: Variables listed in the function definition. function add(a, b) { } >> a and b are parameters 5. Arguments: Actual values passed to a function when calling it. add(2, 3); >> 2 and 3 are arguments 6. Return Statement: The return keyword sends a value back from a function and stops execution. function add(a, b) { return a + b; } 7. Callback Function: A function passed as an argument to another function. function greet(name) { console.log("Hello " + name); } function processUser(callback) { callback("Javascript"); } 8. Higher-Order Function: A function that takes another function as an argument or returns a function. >> Examples: map(), filter(), reduce() 9. First-Class Functions: In JavaScript, functions are treated like variables. ✔️ Can be assigned to variables ✔️ Can be passed as arguments ✔️ Can be returned from other functions #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #LearnToCode
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