JavaScript’s eval() — the feature everyone avoids, but few truly understand.. There’s a reason eval() has a bad reputation in JavaScript. But instead of just accepting “never use it”, I wanted to understand why. So I explored it—not for production use, but to understand how JavaScript actually thinks at runtime. What eval() really does At its core, eval() takes a string and executes it as JavaScript code in the current execution context. const x = 10; console.log(eval("x + 5")); // 15 This isn’t magic—it’s JavaScript dynamically injecting code into the engine’s execution phase. The real eye-opener: scope awareness What surprised me most is that direct eval has access to local scope: function testEval() { const secret = "hidden"; eval("console.log(secret)"); } testEval(); // "hidden" This single behavior explains both its power and its danger. It operates inside the scope chain, not outside it. Direct vs Indirect eval — a deep JS concept This distinction reveals how execution context is resolved: const x = 10; // Direct eval eval("x + 5"); // 15 // Indirect eval (0, eval)("x + 5"); // ReferenceError Indirect eval runs in the global scope, not the local one. This subtle difference says a lot about how JavaScript binds scope at runtime. Why JavaScript engines hate it. After experimenting, the concerns make total sense: Executes arbitrary code (huge security risk) Breaks JIT optimizations Defeats static analysis and makes debugging painful eval(userInput); // never trust runtime strings This is why linters, compilers, and senior engineers all warn against it. Does it have any valid use? In rare, tightly controlled scenarios—yes. For example, evaluating validated math expressions: function safeMath(expr) { if (!/^[0-9+\-*/() ]+$/.test(expr)) { throw new Error("Unsafe input"); } return eval(expr); } Even then, safer alternatives usually exist. My key takeaway Exploring eval() taught me far more than avoiding it ever could: How JavaScript resolves scope How execution contexts work Why some features exist even if we rarely use them How runtime behavior impacts performance and security Understanding what not to use is part of becoming a stronger engineer. I won’t use eval() in production—but I’m glad I understood it. Curiosity like this is what helps me write safer, more predictable JavaScript. #JavaScript #FrontendEngineering #WebDevelopment #JSInternals #LearningByDoing #SoftwareEngineering
Understanding JavaScript's eval() function and its implications
More Relevant Posts
-
🚀 Day 13 of JavaScript Daily Series JavaScript Strings — slice, substring, toUpperCase, trim (Super Easy Hinglish + Real-Life Examples) Aaj hum JavaScript ke 4 most useful string methods seekhenge. Yeh daily life coding me 100% use hote hain — chahe forms ho, search bars ho, validation ho ya UI formatting. 📝 What is a String? (Simple English Definition) A string is a sequence of characters used to store text like names, messages, sentences, etc. Example: let name = "Ritesh Singh"; 1️⃣ slice() — Cut & Extract Part of the String 🔹 Definition Returns a portion of string from start index to end index (end not included). 🧠 Hinglish Explanation Socho tum movie clip ka ek scene cut karke nikalna chahte ho → yahi slice karta hai. 📱 Real-Life Example Instagram username crop karna: let username = "aapanrasoi_official"; let shortName = username.slice(0, 10); console.log(shortName); // "aapanraso" 2️⃣ substring() — Extract Part of String (Like slice, but safer) 🔹 Definition Works like slice but doesn’t accept negative indexes. 🧠 Hinglish Explanation Slice ka hi shareef version — negative cheezein nahi leta. 😄 📱 Example let text = "JavaScript"; console.log(text.substring(4, 10)); // "Script" 3️⃣ toUpperCase() — Convert to CAPITAL Letters 🔹 Definition Returns the string in uppercase. 🧠 Hinglish Explanation Whatsapp pe aise lagta hai jaise koi chillaa kar message bhej raha ho. 😆 📱 Example let city = "varanasi"; console.log(city.toUpperCase()); // "VARANASI" 4️⃣ trim() — Remove Extra Spaces 🔹 Definition Removes spaces from start and end. 🧠 Hinglish Explanation Form bharte time users extra space daal dete hain, trim unko clean kar deta hai. 📱 Real-Life Example (Form Input Clean) let email = " ritesh@gmail.com "; console.log(email.trim()); // "ritesh@gmail.com" 🔥 Quick Summary Table MethodKaamReal Useslice()Part nikalnaUsername / Title Shortensubstring()Safe extractionWord pickingtoUpperCase()Text ko caps meLabels / Highlightstrim()Extra space hatanaForm inputs 🧠 Why These 4 Methods Matter? ✔ Clean data ✔ Better UI ✔ Faster string manipulation ✔ Interviews me 100% pooch lete hain
To view or add a comment, sign in
-
🚀 Currying, Closures & Functional Thinking in JavaScript Explored how functions in JavaScript can be composed, extended, and even behave like objects. Here’s what stood out 👇 🧠 Currying (Function Transformation) Transforming a function with multiple arguments into a chain of single-argument functions. function add(a) { return function (b) { return a + b; }; } add(2)(3); // 5 💡 Why it works: Closures allow the inner function to retain access to a. 🔁 Infinite Currying Built flexible patterns like: sum(1)(2)(3)(); // 6 console.log(sum(1)(2)(3)); // 6 Using: • Closures • Functions as objects • toString() override • Symbol.toPrimitive This shows how JavaScript allows deep control over function behavior. ⚙️ Functions Are Objects In JavaScript: • Functions can store properties • Functions can override default behavior • Functions can control type coercion 💡 Insight: Functions are not just callable — they’re fully dynamic objects. 🎯 Takeaway: JavaScript becomes predictable when you understand: • Closures • Execution context • Type coercion • Prototype behavior 🧩 Problem Solving — Sliding Window Optimization Solved: Longest Substring Without Repeating Characters Approach evolution: • Set-based → expand/shrink window (O(n)) • Map-based → store last seen index l = Math.max(l, lastSeen[s[r]] + 1); 💡 Key Insight: Instead of shrinking step-by-step, jump the left pointer directly. 🎯 Pattern Understanding: Sliding Window = • Expand when valid • Shrink when invalid • Never move pointers backward Building stronger functional thinking and optimized problem-solving patterns. 💪 #JavaScript #FunctionalProgramming #DSA #ProblemSolving #FrontendDeveloper #MERNStack “Closures allow functions to remember variables even after execution — that’s the power behind currying.”
To view or add a comment, sign in
-
-
JavaScript in 2026: Resources to Master JavaScript InfoWorld's Jan '26 roundup hits hard JS isn't dying, it's thriving. First month of 2026 gone, no superintelligent AGI eating the power grid, and human programmers? Very much alive and evolving. The biggest shifts shaking up frontend dev: TypeScript Type Stripping – Game-changer alert! Types treated as whitespace. Run TS directly in Node.js – zero builds, zero source maps, instant feedback, perfect stack traces. Biggest TS upgrade since day one. Say goodbye to compile waits forever. Angular's Epic Comeback Modern reactive workflows + community-driven roadmap = Angular suddenly JS's hottest project. Signals, standalone components, better DX than ever. If you've slept on Angular, wake up! Hotwire (HTMX-powered HTML-over-wire) Sick of JSON/SPA bloat? Server sends HTML fragments directly. Logic lives backend, frontend stays simple. Reclaims your sanity while delivering buttery interactivity. React Holds the Throne Endless framework churn, but React = reactivity gold standard. Fundamentals endure when hype fades. Security Reality Check npm/Yarn holes letting attackers slip Shai-Hulud defenses – package security STILL critical in 2026. Triple-check dependencies! Mind-blowing ecosystem moves: jQuery 4.0 drops IE10, goes full ES modules Chrome 144's declarative geolocation element (UX/security win, camera/mic next) ChatGPT containers running bash + npm installs? AI/IDE merger happening NOW Gleam leveling up external types Even C# snagged 2025's top language honors – healthy competition! My Complete 2026 JavaScript Mastery Path Phase 1: Foundation (Weeks 1-4) ES2025+ mastery (async iterators, private fields, top-level await) DOM → declarative thinking 5 vanilla projects: calculator, todo, weather, chat, game Phase 2: Framework Deep Dive (Months 2-3) React Track → React 19 + Next.js 15 + TypeScript + tRPC + TanStack Query Angular Track → Angular 19 + Signals + Standalone + RxJS 8 Hotwire Track → Rails 8/Hotwire + HTMX + Stimulus + Turbo Phase 3: No-Build Turbo Mode (Month 4) Node 24+ TypeScript direct execution Vite + esbuild + SWC compiler pipeline Biome (Rust-powered linter/formatter) Turbopack dev server (Next.js 15) esbuild bundler for prod Phase 4: Production Pro (Ongoing) Socket.dev / Snyk security scanning PWA + Workbox service workers Vercel/Netlify/Cloudflare deployment Core Web Vitals obsession Playwright E2E + Vitest unit GitHub Actions CI/CD Phase 5: 2026 Edge (Advanced) AI dev tools (ChatGPT containers, Cursor.ai) WebGPU for compute-heavy apps WebTransport for low-latency multiplayer Temporal API for complex date/time The 2026 Reality: Tools get faster, patterns simpler, security tighter. JS isn't going anywhere – it's getting better. Human creativity + AI acceleration = unstoppable. #JavaScript #TypeScript #WebDev #Frontend #Hotwire #Angular #ReactJS #NextJS #NoBuild #WebPerformance #DevTools #2026Trends
To view or add a comment, sign in
-
-
🔑 Prototype & Inheritance in JavaScript 1. Prototype Chain Every JavaScript object has a hidden property called [[Prototype]]. When you try to access a property that doesn’t exist on the object itself, JavaScript looks up the prototype chain to find it. Example: const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new When you use the new keyword, JavaScript creates a new object and links it to the constructor’s prototype. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const varun = new Person("Varun"); console.log(varun.greet()); // Hello, Varun 3. ES6 Classes (Syntactic Sugar) JavaScript classes are just syntactic sugar over prototype-based inheritance. They make the code cleaner and more readable, but under the hood, they still use prototypes. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. 📌 Quick Interview Tip Interviewers often ask: “Explain the prototype chain.” “What’s the difference between class inheritance and prototype inheritance?” “Why are methods added to the prototype instead of inside the constructor?” const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new Jab tum new keyword use karte ho, ek naya object banata hai jo constructor ke prototype se link hota hai. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const champ= new Person("Champ"); console.log(champ.greet()); // Hello, Champ 3. ES6 Classes (syntactic sugar) Classes JS me bas prototype-based inheritance ka cleaner syntax hain. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. #React #ReactJS #Frontend #WebDevelopment #JavaScript #Interviews #SoftwareEngineering #infy
To view or add a comment, sign in
-
🚀 Class Expressions in JavaScript — A Powerful Yet Underrated Feature Most developers know about class declarations in JavaScript… But fewer truly leverage Class Expressions to write cleaner, more dynamic code. Let’s break it down 👇 --- 📌 What is a Class Expression? A Class Expression is a way to define a class inside an expression rather than as a standalone declaration. Unlike traditional class declarations, class expressions can be: ✔ Assigned to variables ✔ Passed as arguments ✔ Created dynamically ✔ Defined conditionally They offer more flexibility in structuring your logic. --- 🏷 Named Class Expression A Named Class Expression includes an internal class name. 🔹 That internal name is only accessible inside the class itself 🔹 Helpful for debugging 🔹 Useful for self-referencing logic It improves stack traces and clarity in complex applications. --- 👤 Anonymous Class Expression An Anonymous Class Expression does not include an internal name. 🔹 Cleaner and shorter 🔹 Common in modern JavaScript patterns 🔹 Ideal when internal referencing isn’t needed Most developers use this form in practical scenarios. --- 🎯 Where Are Class Expressions Useful? Class expressions shine when you need: ✨ Scoped class definitions ✨ Dynamic behavior ✨ Encapsulation ✨ Factory patterns ✨ Flexible architecture They’re especially helpful in modular and component-based systems. --- 🔄 Passing a Class as an Argument In JavaScript, classes are first-class citizens. This means you can: 👉 Pass a class into a function 👉 Return a class from a function 👉 Store it in variables This is extremely powerful for: ✔ Dependency injection ✔ Plugin systems ✔ Strategy patterns ✔ Reusable architecture --- ⚡ Conditional Class Definition One of the biggest advantages: You can define different classes based on runtime conditions. This makes your code adaptable for: 🔹 Feature flags 🔹 Environment-based behavior 🔹 Config-driven systems Clean. Flexible. Scalable. --- 🤔 When Should You Use Class Expressions? Use them when: ✅ The class is needed only in a limited scope ✅ You need dynamic or conditional class creation ✅ You want to pass classes around like data ✅ You’re implementing advanced design patterns Avoid them when: ❌ You need a globally accessible, clearly structured top-level class --- 💡 Final Thought Class expressions give you architectural flexibility. They may not be used every day — but when needed, they are incredibly powerful. Mastering them makes you think like a JavaScript architect, not just a coder. --- If this helped you level up your JavaScript knowledge, React 👍 and share with your network 🚀 #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #Programming #Developers #Tech #CleanCode #CodingTips
To view or add a comment, sign in
-
🚀 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲, __𝗽𝗿𝗼𝘁𝗼__, 𝗮𝗻𝗱 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Most JavaScript developers use objects daily… But not everyone truly understands how JavaScript inheritance actually works under the hood. Let’s break it down simply 👇 🔹 𝟭️ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲? In JavaScript, every function automatically gets a special property called: 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗡𝗮𝗺𝗲.𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲 It is used when we create objects using new. Example: 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗣𝗲𝗿𝘀𝗼𝗻(𝗻𝗮𝗺𝗲) { 𝘁𝗵𝗶𝘀.𝗻𝗮𝗺𝗲 = 𝗻𝗮𝗺𝗲; } 𝗣𝗲𝗿𝘀𝗼𝗻.𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲.𝘀𝗮𝘆𝗛𝗲𝗹𝗹𝗼 = 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 () { 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴("𝗛𝗲𝗹𝗹𝗼 " + 𝘁𝗵𝗶𝘀.𝗻𝗮𝗺𝗲); }; 𝗰𝗼𝗻𝘀𝘁 𝘂𝘀𝗲𝗿 = 𝗻𝗲𝘄 𝗣𝗲𝗿𝘀𝗼𝗻("𝗔𝗺𝗮𝗻"); 𝘂𝘀𝗲𝗿.𝘀𝗮𝘆𝗛𝗲𝗹𝗹𝗼(); // 𝗛𝗲𝗹𝗹𝗼 𝗔𝗺𝗮𝗻 Here: sayHello is not copied into every object It is shared via the prototype This saves memory 🔹 𝟮️ 𝗪𝗵𝗮𝘁 𝗶𝘀 __𝗽𝗿𝗼𝘁𝗼__? __proto__ is a reference to an object's parent prototype. console.log(user.__proto__ === Person.prototype); // true Important: prototype → belongs to functions __proto__ → belongs to objects Think of it like this: function → prototype object → __proto__ 🔹 𝟯️ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲 𝗖𝗵𝗮𝗶𝗻𝗶𝗻𝗴? When you try to access a property: user.sayHello() JavaScript searches like this: Does user have sayHello? ❌ Check user.__proto__ (Person.prototype) ✅ If not found, go to next prototype Eventually reaches Object.prototype This chain is called: 👉 Prototype Chaining 🔹 𝟰️.𝗪𝗵𝘆 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗣𝗼𝘄𝗲𝗿𝗳𝘂𝗹? Because JavaScript inheritance is: Dynamic Memory efficient Flexible Every object in JavaScript is connected to a prototype. Even this works: [].__proto__ === Array.prototype Everything eventually links to: Object.prototype 🔥 Final Takeaway prototype → used by constructor functions __proto__ → internal link to parent Prototype chaining → how JavaScript finds properties Arrow functions ❌ don’t have prototype 𝗜𝗳 𝘆𝗼𝘂'𝗿𝗲 𝗹𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗱𝗲𝗲𝗽𝗹𝘆, 𝗱𝗼𝗻’𝘁 𝘀𝗸𝗶𝗽 𝗽𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲𝘀. 𝗧𝗵𝗲𝘆 𝗮𝗿𝗲 𝘁𝗵𝗲 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 𝗼𝗳 𝗵𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗿𝗲𝗮𝗹𝗹𝘆 𝘄𝗼𝗿𝗸𝘀. 💡 #JavaScript #WebDevelopment #Programming #CodingTips #CareerGrowth #DevCommunity
To view or add a comment, sign in
-
-
Understanding the difference between the logical OR operator( || ) and Nullish Coalescing (??) in JavaScript The room is quiet. Across the table, the interviewer leans back in his chair, folds his arms, and slides a sheet of paper toward you. On it, just one line of code: const name = userInput || "Guest"; He looks up. “What happens if userInput is an empty string?” It’s a simple question. Almost too simple. But in that moment, you realize this isn’t about syntax. It’s about understanding how JavaScript thinks. About knowing the difference between something that is falsy… and something that is truly missing. And that’s where many developers discover the quiet power of ??. You answer the interviewer carefully. “If userInput is an empty string… the result will be 'Guest'.” He nods. Because in JavaScript, the logical OR operator || doesn’t ask, “Is this value missing?” It asks something else: “Is this value truthy?” And in JavaScript, an empty string "" is not truthy. Neither is 0. Neither is false. Neither is NaN. They are all falsy. So when you write: const name = userInput || "Guest"; JavaScript evaluates userInput. If it is falsy - any falsy value at all, it immediately replaces it with "Guest". An empty string? Replaced. Zero? Replaced. False? Replaced. And sometimes… that’s a problem. Imagine you’re building a dashboard. A user sets their notification count to 0 because they’ve cleared everything. That’s correct. That’s intentional. But your code says: const notificationCount = count || 10; Suddenly, the UI shows 10 notifications. Not because the user has 10. But because 0 was treated like something was wrong. That’s not a syntax error. That’s a logic error. And logic errors are the most dangerous kind - because your code runs perfectly. This is where the nullish coalescing operator ?? enters the story. Unlike ||(Logical OR operator), it doesn’t panic at every falsy value. It asks a more precise question: “Is this value actually missing?” In JavaScript, “missing” means only two things: null undefined Nothing else. So when you write: const notificationCount = count ?? 10; Now JavaScript behaves differently. If count is: 0 -> keep it false -> keep it "" -> keep it But if it’s: null -> use 10 undefined -> use 10 Suddenly, your defaults become intentional instead of accidental. Think of it this way: || is generous. Maybe too generous. It replaces anything that looks weak or empty. ?? is precise. It only steps in when something is truly absent. One replaces falsy values. The other replaces nullish values. That distinction may seem small. But in production systems - in financial apps, dashboards, admin panels, user preferences, that distinction can decide whether your application behaves correctly… or quietly lies. And the best developers? They understand not just how operators work - but what questions those operators are really asking behind the scenes.
To view or add a comment, sign in
-
I spent years not truly understanding the JavaScript event loop. I read the blog posts. Watched the videos. Nodded along. But I never *saw* it happen in real time. So I built something about it. 👇 ────────────────────── 🚀 Introducing JS Visualizer ────────────────────── A production-grade, desktop-only JavaScript Event Loop Debugger. Paste any JS code. Click Run. Watch your runtime come alive — step by step. Here's what it visualizes in real time: 🔵 Call Stack — see every function push and pop with smooth animations 🟢 Execution Context — track variable bindings per scope, live 🟠 Web APIs — watch async operations delegate out of the main thread 🔴 Task Queue — setTimeout, setInterval callbacks waiting their turn 🟣 Microtask Queue — Promises resolving before any macro-task fires 🟡 Event Loop — an animated indicator ticking between queues 🩵 Console — simulated output at every step You can step forward. Step backward. Scrub to any point on the timeline. Read a plain-English description of exactly what's happening at each moment. ────────────────────── The stack underneath: ────────────────────── ⚛️ React 19 + TypeScript (strict mode, zero `any`) 🎨 Tailwind CSS v4 — not a single line of raw CSS 🐻 Zustand — global state, minimal boilerplate 🟢 GSAP 3 — every push, pop, and tick is animated with production-level easing 📝 CodeMirror 6 — Dracula + Catppuccin Macchiato themes, autocomplete ⚡ Pre-computed step snapshots — deterministic, time-travel-ready The execution engine is designed to be WASM-replaceable. Swap in a QuickJS Wasm build and get byte-perfect simulation — the UI doesn't change at all. ────────────────────── What I learned building this: ────────────────────── → The microtask queue runs to completion before the event loop checks the task queue. Every time. No exceptions. → async/await is just Promise syntax — `await` suspends the function and puts the resume callback in the microtask queue → Zero-delay `setTimeout` still fires after all Promises resolve → GSAP is still unmatched for imperative DOM animation at this level of precision This is the tool I wish existed when I was learning. 🔗 Live: https://lnkd.in/gnG_UXv3 💻 GitHub: https://lnkd.in/gM5EtUst Drop a ⭐ if it helps you finally understand the event loop. What JavaScript concept confused you the longest? I'd love to know 👇 #JavaScript #WebDevelopment #OpenSource #React #TypeScript #EventLoop #DevTools #Frontend #100DaysOfCode #Programming
To view or add a comment, sign in
-
-
🚀 JavaScript Output Challenge — Can You Guess Them All? Let’s test your core JavaScript knowledge — Event Loop, Closures, Hoisting, and Shallow Copy. 👇 Try to guess the output before running the code. 🧩 Question 1 — Event Loop + Promises + setTimeout console.log(1) const promise = new Promise((resolve) => { console.log(2) resolve() console.log(3) }) console.log(4) promise.then(() => { console.log(5) }).then(() => { console.log(6) }) console.log(7) setTimeout(() => { console.log(8) }, 10) setTimeout(() => { console.log(9) }, 0) 👉 What is the exact order of logs? 🧩 Question 2 — Spread Operator (Shallow Copy) let person = { name: "Ram", age: 29, marks: { math: 21, physics: 25 } } let person2 = { ...person } person2.name = "Shyam" person2.age = 21 person2.marks.math = 50 console.log(person, person2) 👉 Will both objects change or only person2? 🧩 Question 3 — Closure Inside Loop function test(arr, x) { var a, c = 0; for (var i = 0; i < arr.length; i++) { if (i === x) { a = function () { console.log(i, c++) } } } return a; } var t = test([1,2,3,4,5,6,7,8,9], 5) t(); t(); t(); 👉 What gets printed each time and why? 🧩 Question 4 — Hoisting + Scope Confusion var a = 10; var b = 100; function test() { a = 30; var a; console.log(a); b = 200; console.log(b); b = 300; } test(); console.log(a); console.log(b); 👉 What are the final values of a and b? 💬 Drop your answers in the comments (no cheating 😄). I’ll share detailed explanations in the next post! #JavaScript #FrontendDevelopment #WebDevelopment #InterviewPrep #JSChallenge #100DaysOfCode
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