10 JavaScript Questions That Reveal How Well You Really Understand the Language 1. Why does adding decimals sometimes give strange results? JavaScript stores numbers using a binary floating-point system. Because values like 0.1 can’t be represented exactly in binary, small inaccuracies appear during calculations. These tiny errors add up and show unexpected results in decimal math. 2. Why does "" == 0 evaluate to true? When using loose equality, JavaScript converts both sides to a common type. An empty string becomes 0, and the number 0 stays the same so the comparison succeeds. This is a classic example of type coercion at work. 3. Why isn’t NaN equal to anything even itself? NaN represents an undefined numeric result, like dividing zero by zero. Since it indicates a failed computation, JavaScript treats it as incomparable, making every equality check with NaN return false. 4. Why does accessing a let variable before declaration throw an error? Variables declared with let and const exist in memory but remain inaccessible until execution reaches their declaration. This prevents accidental use before initialization and results in a runtime error if accessed too early. 5. How can functions store data like objects? Functions in JavaScript are callable objects. This means you can attach properties directly to them, allowing a function to remember values, store configuration data, or keep internal state across calls. 6. Why do Promises run before setTimeout? Promise callbacks are placed in the microtask queue, which has higher priority than the macrotask queue used by timers. After the current code finishes, JavaScript clears all microtasks before handling any scheduled timers. 7. What really happens when you create an object with a constructor? Using a constructor links a new object to a prototype, assigns properties through this, and sets up inheritance automatically. This process allows methods to be shared efficiently across instances. 8. Why is chaining functions considered a good practice? Chaining encourages small, single-purpose functions that work together. This makes code easier to test, reason about, and reuse, especially in data transformation pipelines. 9. Why does "5" + 3 return "53" instead of 8? When one operand is a string, JavaScript switches to string concatenation. The number is converted into a string, and both values are joined together instead of being added numerically. 10. How can template literals be customized with logic? By attaching a function to a template literal, JavaScript lets you intercept and modify how strings and expressions are combined. This is useful for localization, escaping user input, or building custom DSLs. For help and guidance in you carrier path https://lnkd.in/gH3paVi7 Join my dev community for resources📚, tech talks🧑🏻💻and learning 🧠 https://lnkd.in/gt8WeZSt #frontend #interview #javascript
Rohan kumar’s Post
More Relevant Posts
-
𝗪𝗲𝗹𝗹-𝗞𝗻𝗼𝘄𝗻 𝗦𝘆𝗺𝗯𝗼𝗹𝘀 𝗮𝗻𝗱 𝗧𝗵𝗲𝗶𝗿 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀 JavaScript has evolved over time. One major update was the introduction of Symbols in ECMAScript 2015. Well-Known Symbols provide a unique way to define behavior and properties in JavaScript. To understand Well-Known Symbols, you need to know what symbols are. Before ECMAScript 2015, JavaScript did not have a way to create private object properties. Developers used tricks like prefixes or closures to manage uniqueness. The introduction of Symbols solved this problem. A Symbol is a unique identifier created using the Symbol() function. Here are some key Well-Known Symbols: - Symbol.hasInstance: customizes the instanceof operator behavior - Symbol.isConcatSpreadable: determines if an object should be flattened when using Array.prototype.concat - Symbol.iterator: defines the default iterator for an object - Symbol.match: specifies a function used for pattern matching with regex - Symbol.replace: customizes the behavior of String.prototype.replace - Symbol.search: customizes the behavior of String.prototype.search - Symbol.split: determines how String.prototype.split performs on an object You can use Symbol.hasInstance to define custom behaviors for the instanceof operator. For example: class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance) && instance.length > 0; } } You can also use Symbol.iterator to define object iteration. For example: class Fibonacci { constructor() { this.current = 0; this.next = 1; } [Symbol.iterator]() { return this; } next() { const current = this.current; [this.current, this.next] = [this.next, this.current + this.next]; return { value: current, done: false }; } } Well-Known Symbols can streamline code and improve architecture. However, they can also impact performance. Using Symbols can incur a cost, especially when abstracting data structures or heavy computational tasks. Many modern frameworks and libraries use Well-Known Symbols for internal management. For example, React and Vue use Symbols to handle component states uniquely. To debug issues with Well-Known Symbols, you can use console logging and debugging tools like Chrome DevTools. Source: https://lnkd.in/d_8if4qz
To view or add a comment, sign in
-
JavaScript bugs rarely come from bad syntax. They come from misunderstanding what a variable actually holds. Once memory clicks, behavior stops feeling random. 👉 Pass by value vs pass by reference isn’t theory. 👉 It’s runtime behavior and most hard bugs come from getting it wrong. Here’s the mental model that changed how I reason about code. 🧠 What variables actually store In JavaScript, variables don’t all store data the same way. • Primitives (number, string, boolean, null, undefined) → store the actual value • Objects, arrays, classes → store a memory address That single distinction explains: • shared state bugs • broken equality checks • “random” side effects • functions mutating things they shouldn’t ⚡ Why primitives feel predictable let a = 10; let b = a; b++; Two variables. Two independent values. That’s why primitives: • are passed by value • stay isolated across function calls • don’t leak changes across scopes Safe. Local. Predictable. 🌐 Why reference types behave differently let a = []; let b = a; b.push(1); You didn’t update b. You updated the memory both point to. Because: • assignment copies the address, not the data • multiple variables can point to the same location • mutation affects every shared reference This is where subtle bugs are born. ❌ Equality checks that look wrong (but aren’t) [] === [] // false Not because JavaScript is weird, but because it compares addresses, not structure. Two identical-looking objects: • separate allocations • different addresses • not equal Miss this, and conditionals silently fail. This is also a common interview discussion point. 🧨 Mutation vs reassignment (the real distinction) Same syntax. Very different mechanics. • Mutation (push, property update) → changes data at the address → affects all references • Reassignment (= new object) → creates a new address → breaks the link Understanding this explains: • why functions mutate external state • why “local changes” aren’t always local ⚠️ Why const still allows mutation const arr = []; arr.push(1); Valid because: • the reference didn’t change • only the data inside it did const locks the address not, the contents. This alone removes confusion around: • immutability • state updates • “why this still changed” 🎯 Why this actually matters If you don’t understand reference vs value: • you can’t reason about state • you can’t trust function boundaries • you’ll ship bugs that are hard to reproduce • debugging feels like chasing ghosts Once you do understand it, you start to: • predict side effects instead of reacting to them • design safer APIs • write code that scales mentally, not just technically For me, this was the shift from writing code to reasoning about runtime behavior. If you enjoy thinking about how systems actually behave not just how code looks let’s connect 🤝 #JavaScript #SoftwareEngineering #ProgrammingConcepts #SystemThinking #Debugging #DeveloperMindset
To view or add a comment, sign in
-
10 Unique JavaScript Questions to Challenge Your Understanding 𝟭. 𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 𝟬.𝟭 + 𝟬.𝟮 !== 𝟬.𝟯 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? Because JavaScript uses IEEE 754 floating-point math — decimals aren’t stored exactly, leading to tiny precision errors. This leads to rounding errors. The result of 0.1 + 0.2 is actually 0.30000000000000004. 𝟮. 𝗪𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝘄𝗵𝗲𝗻 𝘆𝗼𝘂 𝗰𝗼𝗺𝗽𝗮𝗿𝗲 [] == ![]? Surprisingly, this evaluates to true. The right side ![] coerces to false, then [] == false causes both sides to convert to numbers - An empty array converts to 0, and false converts to 0, so 0 == 0 is true 𝟯. 𝗘𝘅𝗽𝗹𝗮𝗶𝗻 𝘄𝗵𝘆 𝘁𝘆𝗽𝗲𝗼𝗳 𝗡𝗮𝗡 𝗿𝗲𝘁𝘂𝗿𝗻𝘀 "𝗻𝘂𝗺𝗯𝗲𝗿" - NaN stands for "Not-a-Number" but ironically, its type is "number" because it represents an invalid numeric operation result. - It's the only value in JavaScript that isn't equal to itself: NaN !== NaN is true. 𝟰. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝘁𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗱𝗲𝗮𝗱 𝘇𝗼𝗻𝗲 (𝗧𝗗𝗭)? let and const are hoisted but unusable before declaration — accessing them early throws a ReferenceError. 𝟱. 𝗪𝗵𝘆 𝗰𝗮𝗻 𝘆𝗼𝘂 𝗮𝗱𝗱 𝗽𝗿𝗼𝗽𝗲𝗿𝘁𝗶𝗲𝘀 𝘁𝗼 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? - Functions in JavaScript are first-class objects, meaning they can have properties and methods just like any other object. - You can attach data or behavior to functions: myFunc.cache = {} or myFunc.count = 0. 𝟲. 𝗪𝗵𝗮𝘁'𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗺𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 𝗮𝗻𝗱 𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀? - Microtasks execute after the current script but before the next macrotask. Macrotasks (setTimeout, setInterval, I/O) execute in the next iteration of the event loop. 𝟳. 𝗘𝘅𝗽𝗹𝗮𝗶𝗻 𝗵𝗼𝘄 𝗻𝗲𝘄 𝗸𝗲𝘆𝘄𝗼𝗿𝗱 𝘄𝗼𝗿𝗸𝘀 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆 - When you use new, JavaScript creates an empty object, sets the object's prototype to the constructor's prototype,executes the constructor with this bound to the new object, and returns the object. 𝟴. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗰𝗼𝗺𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻 𝗮𝗻𝗱 𝘄𝗵𝘆 𝗶𝘀 𝗶𝘁 𝘂𝘀𝗲𝗳𝘂𝗹? - Function composition is combining multiple functions where the output of one function becomes the input of another. It promotes code reusability, readability, and follows functional programming principles. 𝟵. 𝗪𝗵𝘆 𝗱𝗼𝗲𝘀 [𝟭, 𝟮, 𝟯].𝗺𝗮𝗽(𝗽𝗮𝗿𝘀𝗲𝗜𝗻𝘁) 𝗻𝗼𝘁 𝘄𝗼𝗿𝗸 𝗮𝘀 𝗲𝘅𝗽𝗲𝗰𝘁𝗲𝗱? - This returns [1, NaN, NaN] because map passes three arguments to the callback. parseInt(string, radix) uses the index as radix, causing parseInt('1', 0), parseInt('2', 1), parseInt('3', 2), where base 1 and base 2 (for '3') are invalid. 𝟭𝟬. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝘁𝗮𝗴𝗴𝗲𝗱 𝘁𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗹𝗶𝘁𝗲𝗿𝗮𝗹𝘀? - Tagged templates allow you to parse template literals with a function. The function receives an array of string values and the interpolated values separately. 💡 If these made you pause — that’s good. That pause is where real understanding begins. Save this. Revisit it. Master it.
To view or add a comment, sign in
-
𝗜𝗳 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗖𝗼𝗻𝗳𝘂𝘀𝗲𝘀 𝗬𝗼𝘂, 𝗬𝗼𝘂𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 𝗔𝗿𝗲𝗻’𝘁 𝗦𝘁𝗿𝗼𝗻𝗴 Ask a JavaScript developer one simple question: “What is hoisting?” Most people answer confidently: “JavaScript moves variables and functions to the top.” And that’s exactly how you know… they don’t really understand JavaScript. Because JavaScript never moves your code. The Hoisting Illusion Hoisting isn’t magic. It’s not code rearrangement. It’s not a compiler trick. Hoisting is a side effect of how JavaScript creates memory before execution. That difference matters, a lot. What Actually Happens (The Real Story) Before any JavaScript code runs, the engine does two phases: 1. Memory Creation Phase Allocates memory for variables and functions Function declarations get fully stored Variables declared with var get undefined let and const are placed in the Temporal Dead Zone (TDZ) 2. Execution Phase Code runs line by line Values are assigned Functions are invoked No code moves. Only memory is prepared. Why Fake Confidence Falls Apart People who memorize hoisting say things like: “let is not hoisted” “Functions are hoisted but variables are not” Both are wrong. Everything is hoisted. The difference is how it’s initialized. That’s why this breaks people: console.log(a); // undefined var a = 10; But this crashes: console.log(b); // ReferenceError let b = 10; Same hoisting. Different memory rules. The Interview Trap Hoisting is dangerous because: Beginners memorize rules Intermediates repeat slogans Seniors explain execution context Interviewers know this. That’s why hoisting questions aren’t about syntax — they’re about mental models. If you understand hoisting, you understand: Execution context Scope Closures The event loop (indirectly) Miss hoisting, and everything else is shaky. Production Reality Check Hoisting bugs don’t show up in tutorials. They show up as: undefined values in production Weird behavior after refactors “Works on localhost, breaks in prod” And the dev says: “JavaScript is weird.” No. Your understanding was shallow. The Real Test of JavaScript Skill If someone can clearly explain: Why var behaves differently What TDZ actually is Why function declarations work before definition They don’t just know JavaScript, they understand it. Final Thought Hoisting doesn’t expose beginners. It exposes pretenders. If you want real JavaScript confidence: Stop memorizing rules Start understanding the engine That’s where real senior devs are made. #javascript
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
-
🔥 Day 4 of my JavaScript Daily Series! Aaj hum dekhenge JavaScript Strings aur kuch basic methods jo daily coding me bahut kaam aate hain. 💡 What is a String? (Easy English) A String is a sequence of characters — letters, words, or sentences. Basically, text ko store karne ke liye use hota hai. 🧠 Hinglish Explanation Strings: Simple text data type. Name → "Ritesh" Message → "Hello World!" Email → "ritesh@gmail.com" 👉 Real-Life Example: Socho aap apne WhatsApp me message type karte ho — ye sab strings hi hai. 📱 Important String Methods (With Examples) 1️⃣ length Count of characters in string. let name = "Ritesh"; console.log(name.length); // 6 Real-life: Aapke username me kitne letters hai check karna. 2️⃣ toUpperCase() / toLowerCase() Uppercase ya lowercase me convert karna. let city = "mirzapur"; console.log(city.toUpperCase()); // MIRZAPUR console.log(city.toLowerCase()); // mirzapur Real-life: Name standard format me likhna. 3️⃣ charAt(index) Index se character nikalna. let name = "Ritesh"; console.log(name.charAt(0)); // R Real-life: First letter of name ko badge pe show karna. 4️⃣ slice(start, end) String ka part nikalna. let message = "Hello World"; console.log(message.slice(0, 5)); // Hello Real-life: Email ka domain nikalna. 5️⃣ includes(substring) Check karna ki string me word present hai ya nahi. let msg = "I love JavaScript"; console.log(msg.includes("Java")); // true Real-life: Search bar me keyword check karna. 🔥 Quick Summary Table MethodExampleReal-Life Meaninglength"Ritesh".length → 6Count letterstoUpperCase()"mirzapur".toUpperCase() → "MIRZAPUR"Standard formatcharAt(0)"Ritesh".charAt(0) → "R"First letter of nameslice(0,5)"Hello World".slice(0,5) → "Hello"Part of textincludes("x")"I love JS".includes("JS") → trueSearch keyword
To view or add a comment, sign in
-
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
To view or add a comment, sign in
-
Understanding Event Loop Behavior Through Common Mistakes: While revising the JavaScript event loop, I realized that most confusion doesn’t come from understanding what the event loop is, but from incorrect assumptions we tend to make as beginners. These small misunderstandings can easily lead to wrong conclusions when reasoning about asynchronous code and debugging real-world issues. Trap 1: “setTimeout(fn, 0) runs immediately” Reality: setTimeout callbacks go to the callback queue. They run only after: • the call stack is empty • the microtask queue is fully drained Example: setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); Output: promise timeout 0 ms does not mean immediate. Trap 2: “Microtasks run only once per loop” Reality: • The microtask queue is drained completely every time it is checked. • If a microtask schedules another microtask, it also runs in the same cycle. Example: Promise.resolve().then(() => { console.log("A"); Promise.resolve().then(() => console.log("B")); }); Output: A B Microtasks can chain indefinitely. Trap 3: “Callback tasks run back-to-back” Reality: After each callback task, the event loop: • re-checks the microtask queue • drains it fully • only then executes the next callback Example: setTimeout(() => { console.log("task1"); Promise.resolve().then(() => console.log("micro")); }, 0); setTimeout(() => console.log("task2"), 0); Output: task1 micro task2 Microtasks interrupt callback execution. Trap 4: “Promises are handled by Web APIs” Reality: Promises are part of JavaScript itself. Web APIs only trigger promise resolution (like fetch), but: • .then() callbacks go to the microtask queue Promises are part of JS; Web APIs only resolve them. Trap 5: “fetch callbacks are macrotasks” Reality: • fetch resolves a Promise. • Its .then() callback goes to the microtask queue, not the callback queue. Example: fetch(url).then(() => console.log("fetch")); setTimeout(() => console.log("timeout"), 0); Output: fetch timeout Trap 6 (Node.js): “Browser and Node event loops are identical” Reality: • The concept is the same, but the implementation differs. • Node.js has multiple phases (timers, poll, check, etc.), which affects execution order. Understanding these traps helped me reason about async code more confidently instead of relying on assumptions. If you know other event loop misconceptions that confused you early on, I’d be interested to hear them. #LearnInPublic #CodingJourney #WebDevelopment #JavaScript #ReactJS #DeveloperCommunity #TechContent #Programming
To view or add a comment, sign in
-
Demystifying JavaScript Functions: The Complete Beginner's Guide 🧠 As a developer, understanding functions is like learning to walk in JavaScript—it's fundamental to everything you'll build. Let me break down every type of function in the simplest way possible! 1️⃣ Function Declaration (The Classic) The most basic way to define a function. Gets "hoisted" so you can call it before declaring it. ```javascript function greet(name) { return `Hello, ${name}!`; } console.log(greet('Sasi')); // Hello, Sasi! ``` 2️⃣ Function Expression (The Flexible) Assigning a function to a variable. More flexible but not hoisted. ```javascript const greet = function(name) { return `Hello, ${name}!`; }; ``` 3️⃣ Arrow Function (The Modern) ES6's concise syntax. Perfect for callbacks and one-liners! ```javascript const greet = (name) => `Hello, ${name}!`; // Single parameter? No parentheses needed! const square = x => x * x; ``` 4️⃣ IIFE (Immediately Invoked) Runs immediately after definition. Great for isolated scopes. ```javascript (function() { console.log('I run immediately!'); })(); ``` 5️⃣ Higher-Order Functions (The Smart Ones) Functions that take other functions as arguments or return them. ```javascript // map() is a higher-order function const numbers = [1, 2, 3]; const doubled = numbers.map(x => x * 2); ``` 6️⃣ Generator Functions (The Pausable) Can pause execution and resume later. Use function* and yield. ```javascript function* countUp() { let count = 0; while (true) { yield count++; } } ``` 7️⃣ Async Functions (The Patient) Simplify working with promises using async/await. ```javascript async function fetchData() { const response = await fetch('url'); const data = await response.json(); return data; } ``` 🔄 Function Types Quick Guide: · Regular functions: Your all-purpose workhorse · Arrow functions: Short, clean, no this binding · Async functions: Handle promises elegantly · Generator functions: Control execution flow · IIFEs: Run once, protect scope · Higher-order: Treat functions as data 🎯 When to Use What: · Need this binding? → Regular functions · Writing callbacks? → Arrow functions · Working with APIs? → Async functions · Need reusable logic? → Function expressions · Want clean, modern code? → Arrow functions 💡 Pro Tip: Arrow functions don't have their own this context—they inherit it from the parent scope. Regular functions do have their own this. --- Let's Discuss! 👇 · Which function type do you use most often? · What's your favorite "aha!" moment with JavaScript functions? 🔥 Want more practical insights like this? ✅ Follow Sasikumar S for daily JavaScript tips ✅ Like & Repost to help other developers ✅ Comment your function questions below! #JavaScript #WebDevelopment #Programming #Coding #Frontend #Developer #WebDev #Tech #SoftwareEngineering #LearnToCode #ProgrammingTips #CodeNewbie #JavaScriptTips #Functions #ES6 #AsyncJavaScript
To view or add a comment, sign in
-
Garbage Collection (GC) in JavaScript is often simplified to the notion that "JavaScript automatically frees memory." While this is true, it is an incomplete explanation. The essence of GC is that it removes memory that your program can no longer access. The core concept is straightforward: - If an object is reachable, it remains in memory. - If it is unreachable, it can be collected. Garbage Collection is based on reachability rather than whether you still "use" something conceptually. Here's a simplified overview of how the GC process works: - JavaScript maintains a set of roots, which include global variables, active function scopes, closures, and the call stack. - The GC starts from these roots and marks everything they reference. - Anything that cannot be reached from these roots is deemed garbage, and that memory is reclaimed. This method is known as mark-and-sweep, forming the foundation of modern JavaScript engines. A common misunderstanding arises with examples like: ```javascript let user = { name: "Kishor" }; user = null; ``` In this case, the object becomes unreachable and is eligible for GC. However, consider: ```javascript let cache = []; cache.push({ data: 123 }); ``` Even if you "stop using" that object, it remains reachable through the cache, preventing GC from removing it. This is a primary cause of memory leaks in JavaScript. Closures also play a significant role in memory management. They can extend the lifetime of memory; if a closure references a large object, that object stays in memory as long as the closure exists. This can be powerful but potentially dangerous if not properly understood. While GC is automatic, it is not without cost. It runs when the engine determines it can pause execution briefly, and large object graphs can make GC more resource-intensive. This is why long-running applications still require memory awareness. The key takeaway is that Garbage Collection does not prevent memory leaks; it only cleans up memory
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