🚀 𝗙𝗶𝗿𝘀𝘁 - 𝗖𝗹𝗮𝘀𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 In JavaScript, functions are first-class values. That means the language allows functions to be treated the same way as any other value. Practically, this gives us three abilities: • assign a function to a variable • pass a function as an argument • return a function from another function Example:- 1. when assigned as a value const sayHi = function () console.log("Hi"); } => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘄𝗵𝘆 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗲𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀, 𝗮𝗻𝗼𝗻𝘆𝗺𝗼𝘂𝘀 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀, 𝗮𝗻𝗱 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗻𝗼𝘁 𝘀𝗽𝗲𝗰𝗶𝗮𝗹 𝗰𝗮𝘀𝗲𝘀 , 𝘁𝗵𝗲𝘆’𝗿𝗲 𝗷𝘂𝘀𝘁 𝘃𝗮𝗹𝘂𝗲𝘀. 2. function passed as an argument function executeFunc (callback) { callback(); } executeFunc(sayHi) => 𝗧𝗵𝗶𝘀 𝗶𝘀 𝘁𝗵𝗲 𝗳𝗼𝘂𝗻𝗱𝗮𝘁𝗶𝗼𝗻 𝗳𝗼𝗿 𝗰𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀, 𝗲𝘃𝗲𝗻𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝗿𝘀, 𝗮𝗻𝗱 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲. 𝗧𝗵𝗲 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗶𝘀 𝗷𝘂𝘀𝘁 𝗯𝗲𝗶𝗻𝗴 𝗽𝗮𝘀𝘀𝗲𝗱 𝗹𝗶𝗸𝗲 𝗱𝗮𝘁𝗮. 3. Returning from another function function outer() { return function inner() { console.log("Inner function executed"); }; } const fn = outer(); fn(); => 𝗧𝗵𝗶𝘀 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗲𝗻𝗮𝗯𝗹𝗲𝘀 𝗰𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗮𝗻𝗱 𝗵𝗶𝗴𝗵𝗲𝗿-𝗼𝗿𝗱𝗲𝗿 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 (𝗺𝗮𝗽, 𝗳𝗶𝗹𝘁𝗲𝗿, 𝗿𝗲𝗱𝘂𝗰𝗲). Most JavaScript patterns work because functions can be passed around like data. First-class functions are the rule that makes that possible. #Javascript #Functions #WebDevelopment #Frontend
JavaScript Functions as First-Class Values
More Relevant Posts
-
📌 Understanding JSON.parse() in JavaScript In JavaScript, data often travels between systems in JSON (JavaScript Object Notation) format — especially when working with APIs. To use that data inside your application, JavaScript provides the JSON.parse() method. 👉 What does JSON.parse() do? 🔹 JSON.parse() converts a JSON string into a JavaScript object. 👉 In simple terms: 🔹 It helps JavaScript understand and work with JSON data. 👉 Example Explanation: 🔹 The API response is a string 🔹 JSON.parse() converts it into an object 🔹 Now we can access properties using dot notation 👉 Why is JSON.parse() important? 🌐 Used when handling API responses 💾 Converts data from localStorage / sessionStorage 🔄 Helps transform string data into usable objects 🚀 Essential for backend–frontend communication 💠 Common Error to Watch Out For 🔹 JSON.parse() only works on valid JSON. 🔹 Invalid JSON will throw an error. 🔹 JSON.parse("{name: 'Hari'}"); // ❌ Error ✔ Correct JSON format: JSON.parse('{"name":"Hari"}'); // ✅ JSON.parse() is a fundamental JavaScript method that plays a key role in real-world applications, especially while working with APIs and stored data. #JavaScript #WebDevelopment #Frontend #JSON #CodingTips #LearnJavaScript
To view or add a comment, sign in
-
-
🤔 Ever wondered why editing an object inside a function affects the original, but editing a number doesn’t? JavaScript makes this feel confusing. 🧠 JavaScript interview question Is JavaScript pass by value or pass by reference? ✅ Short answer • JavaScript always passes arguments by value • For primitives, the value is the actual data • For objects, the value being copied is a reference (a pointer) • Mutating the object changes what both references point to • Reassigning the parameter does not affect the original variable 🔍 A bit more detail • Primitives (string, number, boolean, null, undefined, symbol, bigint) are copied as direct values • Objects (arrays, functions, plain objects, maps, sets) are not copied as a whole • The function receives a copy of the reference, not a deep copy of the object 💻 Example // 1) Primitive: no change outside function inc(n) { n = n + 1; } let a = 5; inc(a); console.log(a); // 5 // 2) Object mutation: change is visible outside function setName(obj) { obj.name = "Alex"; } const user = { name: "Sam" }; setName(user); console.log(user.name); // "Alex" // 3) Reassigning param: does NOT affect outside function replace(obj) { obj = { name: "New" }; } replace(user); console.log(user.name); // "Alex" ⚠️ Common misconception • “Arrays are passed by reference” • Not exactly. The reference is passed by value. 🎯 Takeaway • Primitives: you copy the value • Objects: you copy the pointer to the same object • Want to avoid accidental mutation? Clone before changing #javascript #frontend #webdevelopment #react #typescript #codinginterview #learninpublic #programming
To view or add a comment, sign in
-
Did you know that when you use an array inside a JavaScript template literal, it doesn’t behave like an array at all? If you write something like: `Stack: ${['React', 'Node', 'TypeScript']}` you might expect JSON-style output or the array structure. But JavaScript actually produces: "Stack: React,Node,TypeScript" That’s because template literal interpolation triggers implicit coercion: .toString() → .join(',') This isn’t a quirk — it’s part of the language design, and arrays have always been stringified using commas. Where this is useful There are a few scenarios where this implicit join is convenient: 1 - quick logging or debugging 2 - passing arrays into string-based utilities 3 - small helper functions where formatting doesn’t matter, etc. Where it becomes risky In more sensitive areas — UI text, error messages, URLs, file paths, nested arrays — this implicit join can lead to subtle formatting bugs or unreadable output, especially if you didn’t intend commas. My recommendation For clarity and predictability in production code, being explicit is usually the better choice: `Technologies: ${tech.join(', ')}` Making the formatting intentional helps avoid surprises and keeps code easier to understand for everyone reading it. #JavaScript #React #WebDevelopment #FrontendEngineering
To view or add a comment, sign in
-
-
'5'+1 = '51' & '4'-1 = 3 How is possible in JS!. 🧠 Mastering JavaScript — One Concept at a Time (3/32) I realized something simple but powerful. 📦 What Are Data Types? A data type defines what kind of data is being stored a number, text, boolean, object, and so on. In JavaScript, data types are divided into two main categories: 🔹 1. Primitive Types These are copied by value (they create a separate copy). String, Number, Boolean, Undefined, Null, Symbol, BigInt. Primitives are simple and predictable — changing one doesn’t affect another. 🔹 2. Reference Types (Non-Primitive) These are copied by reference, not by value. Object, Array, Function. Instead of copying the actual data, JavaScript copies the memory reference. That’s why modifying one object can sometimes affect another variable pointing to the same object — and that’s where many beginners get confused. 🔍 The typeof Operator JavaScript gives us a tool to check types — typeof. Most results are straightforward: string → "string" number → "number" boolean → "boolean" undefined → "undefined" But then there’s one famous quirk: 👉 typeof null returns "object" This is actually a long-standing JavaScript bug — and it still exists today. Understanding this prevents a lot of confusion during debugging. 🔁 Type Coercion (The Sneaky Part) JavaScript sometimes automatically converts types during operations. For example: When a string and number are added together, JavaScript may perform concatenation instead of addition. Subtraction forces numeric conversion. Booleans, null, and undefined can also behave unexpectedly in arithmetic operations. This automatic behavior is called type coercion — and it’s one of the most misunderstood parts of JavaScript. Instead of memorizing outputs, I’m now trying to understand: How values are stored How they are copied How JavaScript decides to convert them That clarity changes everything. What was the most confusing type behavior you faced when learning JavaScript? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
Understanding the difference between map() method and Map in JavaScript 40 minutes. One capital letter. Not a missing semicolon. Not broken logic. Not a failed API call. Just map vs Map. JavaScript doesn't care about your confidence. It cares about your precision. Here's the difference, simply put: map() - lowercase, An array method. It loops through your array and transforms each item, returning a brand new array. Think of it as a data processor. [1,2,3].map(n => n *10) -> [10, 20, 30] Map - uppercase, A data structure. It stores information as key-value pairs, and unlike regular objects, it accepts any data type as a key, preserves the exact order items were added, and comes with clean built-in methods like .set(), .get(), and .has(). One word. Two very different jobs. map() transforms. Map stores. The best developers aren't the ones who never make small mistakes, they're the ones who understand why the mistake happened. Has a tiny detail in JavaScript ever cost you real time? Share it in the comments. If this saved you a future headache, repost so it saves someone else's too.
To view or add a comment, sign in
-
Understanding the behavior of `this` in JavaScript can be tricky. Here’s a breakdown of the output from the provided code: The output is: ``` undefined Jyoti ``` **Why this output occurs (Step-by-Step):** 1️⃣ **Method reference loses `this`:** When we reference the method like this: ```javascript const fn = user.getName; ``` `fn` becomes a regular function reference and is no longer associated with the `user` object. Thus, when we call: ```javascript fn(); ``` `this` refers to the global object (or `undefined` in strict mode). This is why the output is: ``` fn() → undefined ``` 2️⃣ **`bind` permanently fixes `this`:** When we use `bind`: ```javascript const boundFn = fn.bind(user); ``` It creates a new function where `this` is permanently set to `user`. Therefore, calling: ```javascript boundFn(); ``` results in: ``` boundFn() → "Jyoti" ``` 🔑 **Key Takeaways:** - The value of `this` depends on how a function is called, not where it is defined. - Extracting a method from its object breaks its original context. - `bind` creates a new function with a fixed `this`. - `call` and `apply` set `this` temporarily, while `bind` sets it permanently. Losing the `this` context is a common pitfall in JavaScript development. #JavaScript #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS #CallBindApply
To view or add a comment, sign in
-
-
Day 14: Async / Await in JavaScript Promises improved async code… But Async/Await made it beautiful. ✨ Async/Await lets us write asynchronous code that looks like synchronous code. 🔹 What is async? When you add async before a function: 👉 It automatically returns a Promise async function greet() { return "Hello"; } greet().then(res => console.log(res)); Even though we return a string, JavaScript wraps it inside a Promise. 🔹 What is await? await pauses execution until the Promise resolves. async function fetchData() { const data = await fetch("/api/data"); console.log(data); } 👉 await can only be used inside an async function. 🔹 Error Handling with try/catch async function getData() { try { const res = await fetch("/api/data"); const data = await res.json(); console.log(data); } catch (error) { console.log("Error:", error); } } Much cleaner than multiple .then().catch() chains. 🔥 Why Async/Await is Better? ✅ Cleaner & more readable ✅ Avoids Promise chaining complexity ✅ Easier error handling ✅ Looks synchronous but runs asynchronously #Remeber :Important Interview Point Even with await, JavaScript is still single-threaded. Async/Await works because of: ✔️ Promises ✔️ Event Loop ✔️ Microtask Queue #JavaScript #AsyncAwait #Promises #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
JavaScripts some Importand topic and Advanced If you are learn, you are master in javascript. 1. Core (Fundamental) Objects Object – Base object for all JavaScript objects Function – Functions are special objects Boolean – Wrapper for true/false Symbol – Unique identifier Error – Base object for errors 2. Numbers & Dates Number – Number wrapper object BigInt – Large integers Math – Mathematical operations Date – Date and time handling 3. Text Processing String – String wrapper object RegExp – Regular expressions 4. Indexed Collections Array – Ordered collection Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array 5. Keyed Collections Map – Key-value pairs Set – Unique values WeakMap – Weakly referenced keys WeakSet – Weakly referenced values 6. Structured Data JSON – JSON parsing and stringifying 7. Control Abstraction Objects Promise – Asynchronous operations Generator – Generator functions AsyncFunction – Async functions 8. Reflection Reflect – Interceptable operations Proxy – Custom behavior for objects 9. Internationalization Intl – Internationalization API 10. Web Browser Objects (Not Core JS but Important) window – Global object in browser document – DOM document console – Logging localStorage sessionStorage
To view or add a comment, sign in
-
⚔️ Normal JavaScript vs. War‑Style JavaScript What works locally often breaks in production. Here’s how to tell the difference—and why it matters. 🧪 Normal JavaScript You write it in a sandbox. The data is clean, the network is fast, and the user follows the happy path. ✅ No null or undefined to worry about ✅ Async/await with no .catch() ✅ const user = data.user.profile.email; – works every time This is lab‑grade code. Great for prototypes. Dangerous in production. 🛡️ War‑Style JavaScript This code has seen things. It’s been through code reviews, pentesting, and a 3am outage. 🔹 Defensive reading const email = data?.user?.profile?.email ?? 'fallback@example.com'; 🔹 Error handling that actually handles try { await riskyCall(); } catch (err) { logger.error(err); // Recover, don’t just crash } 🔹 Input validation – never trust the client 🔹 Performance under load – debouncing, throttling, memoization 🔹 Security – escape user input, validate JWTs, use Helmet.js 🔹 Observability – logs, metrics, structured errors War‑style code assumes the worst: 📉 Network fails 🧨 Third‑party API changes shape 🐞 Users type “eval()” into a text box 📈 The Real Difference Normal JS War‑Style JS Works on my machine Works for 10k concurrent Throws undefined Shows a friendly error One developer knows it Handover‑ready, documented “It’s fine for now” “How will this scale?” 🔥 Why This Matters War‑style isn’t over‑engineering—it’s respect. Respect for your users, your future self, and the people who will maintain your code. Start by auditing your last PR. Did you handle the unhappy paths? Did you log failures? Did you assume nothing? Normal JavaScript gets the job done. War‑style JavaScript keeps the job done. 💬 What’s one “war‑style” habit you always practice? I’ll go first: optional chaining and nullish coalescing are non‑negotiable. 👇
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