Day 7: First-Class Functions, Function Statement, Function Expression & Anonymous Functions (JavaScript) JavaScript treats functions as first-class citizens. But what does that actually mean? 🔹 1️⃣ First-Class Functions In JavaScript, functions can: ✅ Be assigned to a variable ✅ Be passed as arguments ✅ Be returned from another function function greet() { return "Hello"; } function execute(fn) { console.log(fn()); } execute(greet); 👉 This ability makes concepts like callbacks, closures, and higher-order functions possible. 🔹 2️⃣ Function Statement (Function Declaration) function add(a, b) { return a + b; } ✔️ Hoisted completely ✔️ Can be called before definition 🔹 3️⃣ Function Expression const add = function(a, b) { return a + b; }; ✔️ Treated like a variable ❌ Not fully hoisted (lives in Temporal Dead Zone if let/const) 🔹 4️⃣ Anonymous Function A function without a name. setTimeout(function() { console.log("Hello"); }, 1000); 👉 Usually used in function expressions or callbacks. 🧠 Mental model to remember 🔥 Key Difference (Interview Favorite) Function Statement → Hoisted with definition Function Expression → Hoisted as variable (undefined / TDZ) Anonymous → No function name First-Class Function → Ability, not a type #Javascript #FirstClassFunction #FunctionExpression #FunctionStatement #AnonymousFunction #WebDevelopment #LearningInPublic
JavaScript First-Class Functions & Function Types Explained
More Relevant Posts
-
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
-
-
Day 8: Higher Order Functions in JavaScript If you understand Higher Order Functions, you understand real JavaScript. 💡 Because in JavaScript, functions are first-class citizens. 🔹 What is a Higher Order Function? A function that: ✅ Takes another function as an argument OR ✅ Returns another function 🔹 Example 1: Function as Argument function greet(name) { return "Hello " + name; } function processUserInput(callback) { const name = "Shiv"; console.log(callback(name)); } processUserInput(greet); Here, processUserInput is a Higher Order Function because it accepts another function as a parameter. 🔹 Example 2: Function Returning Function function multiplier(x) { return function(y) { return x * y; }; } const double = multiplier(2); console.log(double(5)); // 10 This is the foundation of: ✔️ Closures ✔️ Currying ✔️ Functional programming 🔥 Real-Life Examples in JavaScript You already use Higher Order Functions daily: array.map() array.filter() array.reduce() All of them take a function as input. #Javascript #HigherOrderFunction #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
One of the first things that trips up JavaScript developers — at every level — is the `this` keyword. It doesn't work like most other languages. In JavaScript, `this` is not about where a function is written. It's about how it is called. Once you understand the 4 binding rules, it becomes very predictable. 01 — Default binding When called alone, `this` is the global object (or `undefined` in strict mode) 02 — Implicit binding When called on an object, `this` is that object 03 — Explicit binding `.call()`, `.apply()`, and `.bind()` let you set `this` manually 04 — Arrow functions They don't have their own `this`. They inherit it from the surrounding scope // Rule 2 — implicit const user = { name: "Aman", greet() { console.log(this.name); } }; user.greet(); // "Aman" — this = user // Rule 3 — explicit greet.call({ name: "Aman" }); // "Aman" — this = the object you passed // Rule 4 — arrow function inside a method const timer = { start() { setTimeout(() => console.log(this), 1000); // this = timer ✓ } }; The most practical takeaway from Rule 4: 🔵 Regular function → `this` is set by the caller 🟢 Arrow function → `this` is set by the enclosing scope This is why arrow functions are so useful inside callbacks and event handlers — they hold onto the `this` you actually want, without any extra work. Which rule do you find most developers struggle with? I'd love to hear your experience in the comments. 👇 #JavaScript #WebDevelopment #SoftwareEngineering #Programming #100DaysOfCode
To view or add a comment, sign in
-
Day 11: Callback Functions in JavaScript JavaScript is single-threaded… so how does it handle async tasks? 🤔 The answer starts with Callbacks. 🔹 What is a Callback? A callback function is a function that is: ✅ Passed as an argument to another function ✅ Executed later 🔹 Basic Example function greet(name) { console.log("Hello " + name); } function processUser(callback) { const name = "Shiv"; callback(name); } processUser(greet); Here, greet is a callback function. 🔹 Async Example setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 👉 The function runs after a delay 👉 JavaScript does not block execution 🔥 Why Callbacks Are Important ✔️ Foundation of async JavaScript ✔️ Used in APIs, event listeners, timers ✔️ Core concept before learning Promises ⚠️ The Problem: Callback Hell When callbacks are nested too much: api1(function() { api2(function() { api3(function() { console.log("Done"); }); }); }); This leads to: ❌ Hard-to-read code ❌ Pyramid structure ❌ Difficult debugging This problem was later solved using Promises and Async/Await. #Javascript #CallBack #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
You say you’re “comfortable with JavaScript”? Cool. Let’s test that. Answer these in the comments 👇 🧠 1. What will this output? Why? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + []); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + {}); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨({} + []); Most developers get at least one wrong. ⚡ 2. Predict the output: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘰𝘶𝘵𝘦𝘳() { 𝘭𝘦𝘵 𝘤𝘰𝘶𝘯𝘵 = 0; 𝘳𝘦𝘵𝘶𝘳𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘪𝘯𝘯𝘦𝘳() { 𝘤𝘰𝘶𝘯𝘵++; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘤𝘰𝘶𝘯𝘵); }; } 𝘤𝘰𝘯𝘴𝘵 𝘧𝘯 = 𝘰𝘶𝘵𝘦𝘳(); 𝘧𝘯(); 𝘧𝘯(); 𝘧𝘯(); What concept is this testing? 🔥 3. What’s the difference between these two? 𝘖𝘣𝘫𝘦𝘤𝘵.𝘧𝘳𝘦𝘦𝘻𝘦(𝘰𝘣𝘫); 𝘖𝘣𝘫𝘦𝘤𝘵.𝘴𝘦𝘢𝘭(𝘰𝘣𝘫); When would you use one over the other in production? 🧩 4. True or False? 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵" 𝘐𝘧 𝘵𝘳𝘶𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 𝘐𝘧 𝘧𝘢𝘭𝘴𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 🚀 5. Async trap — what happens here? 𝘢𝘴𝘺𝘯𝘤 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() { 𝘳𝘦𝘵𝘶𝘳𝘯 42; } 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘵𝘦𝘴𝘵()); What exactly gets logged? If you can answer all 5 confidently, you’re not just “using” JavaScript. You understand it. Drop your answers below 👇 Let’s see who’s interview-ready. #javascript #frontenddeveloper #codinginterview #webdevelopment #softwareengineering #DAY73
To view or add a comment, sign in
-
The JavaScript "this" Trap 🪤🔥 The Puzzle: What is the output? 🤔 const obj = { name: "JS", getName() { console.log(this.name); } }; const fn = obj.getName; fn(); Output: undefined Why? 🧠 In JavaScript, this depends on HOW a function is called, not where it is written. Lost Context: const fn = obj.getName only copies the function reference. Standalone Call: When you call fn(), there is no object (no dot) before the function. Global Context: It now runs in the Global Context (window object). Since window.name is not "JS", it returns undefined. How to Fix? 🛠️ ✅ Use .bind(): const fn = obj.getName.bind(obj); ✅ Use .call(): fn.call(obj); ✅ Use Arrow Functions: They inherit this from the surrounding scope. Interview Tip: 💡 Always check the "Call Site." No dot before the function call (like fn()) usually means this is lost! #JavaScript #CodingTips #365DaysOfCode #InterviewPrep #WebDev #FullStack #mern #react #node
To view or add a comment, sign in
-
Day 15: The this Keyword in JavaScript this is one of the most misunderstood concepts in JavaScript 🤯 Its value depends on HOW a function is called, not where it is written. 🔹 1️⃣ Global Scope console.log(this); 👉 In browser → window 👉 In Node → {} (module.exports) 🔹 2️⃣ Inside a Regular Function function show() { console.log(this); } show(); 👉 In non-strict mode → window 👉 In strict mode → undefined 🔹 3️⃣ Inside an Object Method const user = { name: "Shiv", greet: function() { console.log(this.name); } }; user.greet(); 👉 this refers to the object → user 🔹 4️⃣ Arrow Function const user = { name: "Shiv", greet: () => { console.log(this); } }; user.greet(); 👉 Arrow functions do NOT have their own this 👉 They inherit from their lexical scope 🔥 Key Rule this depends on: ✔️ How the function is called ✔️ Whether it’s arrow or regular ✔️ Strict mode 🧠 Why Important? ✔️ Core interview topic ✔️ Important in React ✔️ Needed for call, apply, bind #JavaScript #thisKeyword #Frontend #Webdevelopment #learnInPublic
To view or add a comment, sign in
-
If JavaScript is single‑threaded, how does it still handle Promises, API calls, and Timers without blocking the application? The answer lies in the Event Loop. Let’s take a simple example: What would be the output of the below code? console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Some may guess the output to be: Start End Timeout Promise But the actual output is: Start End Promise Timeout So what is happening behind the scenes? 🔵 Synchronous Code Being synchronous, console.log("Start") and console.log("End") run immediately in the Call Stack. 🔵 Promises Resolved promises go to the Microtask Queue which is executed next. 🔵 setTimeout Timer callbacks go to the Macrotask Queue, even if the delay is '0ms', which is executed last. ✅ Simple flow to remember Synchronous Code → Promises (Microtasks) → setTimeout (Macrotasks) So even with 0 delay, Promises will always execute before setTimeout. Understanding this small but important detail will help developers debug async behavior and write more predictable JavaScript applications. #javascript #webdevelopment #eventloop #asyncprogramming
To view or add a comment, sign in
-
Understanding the JavaScript Event Loop is a game changer for writing efficient asynchronous code. Many developers use setTimeout and Promise daily — but fewer truly understand what happens behind the scenes. Here’s a quick breakdown 👇 🔹 JavaScript is single-threaded 🔹 Synchronous code runs first (Call Stack) 🔹 Then all Microtasks execute (Promises, queueMicrotask) 🔹 Then one Macrotask runs (setTimeout, setInterval, DOM events) 🔹 The loop repeats 📌 Execution Priority: Synchronous → Microtasks → Macrotasks Example: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); ✅ Output: 1 → 4 → 3 → 2 Understanding this helps in: ✔ Debugging async issues ✔ Optimizing performance ✔ Writing better React applications ✔ Cracking frontend interviews I’ve created a simple infographic to visually explain the entire Event Loop process. If you're preparing for JavaScript or React interviews, mastering this concept is essential. 💬 Now Your Turn 👇 What will be the output of this code? console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => { console.log("C"); }); console.log("D"); 👨💻 Follow for daily React, and JavaScript 👉 Arun Dubey Drop your answer in the comments 👇 Let’s see who really understands the Event Loop 🔥 #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #EventLoop #CodingInterview
To view or add a comment, sign in
-
-
JavaScript Tip 💡: Use the Array "at()" method to access last Array element easily! The "at()" method in JavaScript provides a simpler way to access elements in an array, especially the last one. Traditionally, getting the last element required using arr[arr.length - 1], but .at(-1) now handles this directly and more cleanly. With "at()", positive indices retrieve elements from the start, while negative indices count backward from the end. This makes .at(-1) a straightforward and readable alternative for accessing the last item in an array. Hope this helps ✅️ Do Like 👍 & Repost 🔄 #html #css #javascript #typescript #react
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