Most developers see this JavaScript pattern and ignore it: (function () { ... } )(); It’s called an IIFE (Immediately Invoked Function Expression) — a function that runs instantly. But here’s a real use case 👇 Imagine a webpage that needs to initialize analytics when it loads. You need some config values, helper functions, and setup logic — but you don’t want to pollute the global scope. (function () { const config = { trackingId: "UA-123456", env: "production" }; function initAnalytics() { console.log("Analytics started with:", config.trackingId); // load scripts, send page view, etc. } initAnalytics(); })(); Now: • Setup runs immediately on load • Config stays private • No global variables leaked • Other scripts stay safe Today, ES modules handle this better. But understanding IIFE helps you grasp scope, closures, and how JavaScript isolates logic. Old pattern. Still teaches powerful fundamentals. #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering
Understanding IIFE: Scope, Closures, and JavaScript Fundamentals
More Relevant Posts
-
💡 The JavaScript .sort() Surprise: Why [10, 2, 5] isn't [2, 5, 10] Ever had code that worked perfectly until the numbers got bigger? Check out this classic JavaScript quirk. 😅 In the screenshot, you'll notice: ✅ [3, 1, 4, 2].sort() results in [1, 2, 3, 4] (Perfect!) ❌ [10, 2, 5].sort() results in [10, 2, 5] (Wait... what?) The "Why" behind the weirdness: By default, JavaScript’s .sort() method converts elements into strings and compares their UTF-16 code unit values. It’s not looking at the numeric value; it’s looking at the characters. Just like "Apple" comes before "Banana," the string "10" comes before "2" because "1" comes before "2" in the dictionary. The Fix: To sort numbers correctly, you need to provide a compare function. This tells JavaScript exactly how to handle the math: let arr2 = [10, 2, 5]; // The correct way to sort numerically: arr2.sort((a, b) => a - b); console.log(arr2); // [2, 5, 10] tandard behavior is great for strings, but for data structures and algorithms (DSA), the compare function is your best friend! Have you ever been bitten by a default behavior in a programming language? Let’s hear your "favorite" bug in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #Programming #SoftwareEngineering #DSA #LearningToCode
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝘁𝗵𝗮𝘁 𝗡𝗲𝘃𝗲𝗿 𝗙𝗼𝗿𝗴𝗲𝘁𝘀: 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 🧠 Hi everyone! I’ve just released Part 5 of my JavaScript deep-dive series: 𝗧𝗵𝗲 𝗠𝗲𝗰𝗵𝗮𝗻𝗶𝗰𝘀 𝗼𝗳 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀. Closures are often treated like a "magic trick" in JavaScript interviews, but they are actually a logical result of how the engine links scopes together. If you’ve ever struggled with why a setTimeout in a loop logs the "wrong" number, or how "private" variables actually work in a language without a private keyword, this article is for you. 𝗜𝗻 𝘁𝗵𝗶𝘀 𝗽𝗮𝗿𝘁, 𝗜 𝗱𝗶𝘃𝗲 𝗶𝗻𝘁𝗼: • 𝗧𝗵𝗲 𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝗦𝗹𝗼𝘁𝘀: Meet [[Environment]] and [[OuterEnv]], the two hidden connectors that make closures possible. • 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝘃𝘀. 𝗩𝗮𝗹𝘂𝗲𝘀: Why closures link to "live" variables (and why that leads to the famous loop trap). • 𝗧𝗵𝗲 𝗜𝗜𝗙𝗘 𝘃𝘀. 𝗟𝗲𝘁: How we used to fix closures in the old days vs. the modern ES6 solution. • 𝗘𝗻𝗰𝗮𝗽𝘀𝘂𝗹𝗮𝘁𝗶𝗼𝗻: How to use closures to create "vaults" for your data. Stop guessing how your functions remember data and start understanding the architecture behind it! Read the full article here: https://lnkd.in/dR_TngGA 🔗 𝗡𝗲𝘅𝘁 𝘂𝗽: We tackle the "Grand Design" of JavaScript objects, 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲𝘀. #JavaScript #SoftwareEngineering #WebDevelopment #Coding #Closures #ProgrammingTips #TechCommunity #ScopeChain
To view or add a comment, sign in
-
📊 Day 13 – Poll Answer & Explanation ```javascript const a = [1, 2, 3]; const b = a; b.push(4); console.log(a); console.log(b); ``` ### ❓ What will be the output? ## ✅ Correct Answer: **B** ``` [1,2,3,4] [1,2,3,4] ``` --- ## 📌 Step-by-Step Explanation **1️⃣ Arrays are Reference Types** In **JavaScript**, arrays are **objects**. Objects are stored in **memory by reference**, not by value. --- **2️⃣ Assigning `b = a`** ```javascript const b = a; ``` This **does NOT create a new array**. Instead, **both `a` and `b` point to the same array in memory**. ``` a ──► [1,2,3] b ──► ``` --- **3️⃣ Modifying the Array** ```javascript b.push(4); ``` Since **`b` references the same array**, the original array is modified. ``` a ──► [1,2,3,4] b ──► ``` --- **4️⃣ Final Output** ```javascript console.log(a); // [1,2,3,4] console.log(b); // [1,2,3,4] ``` Both variables print the **same updated array**. --- ## 💡 Key Takeaway 👉 **Arrays and objects in JavaScript are stored by reference.** 👉 If multiple variables reference the **same object**, modifying one **affects all of them**. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode
To view or add a comment, sign in
-
JavaScript is single-threaded. So why doesn't it freeze during an API call? When I first started learning JS, this felt like a magic trick. If it can only do one thing at a time, how does it handle timers, database queries, and network requests without crashing? The secret is the Event Loop. How it works (The Simplified Flow) :- Call Stack :- Where your code lives. JS executes functions here one by one. Web APIs :- When an async task (like setTimeout) appears, JS hands it off to the browser/Node.js environment. Callback Queue :- Once the task is done, the callback waits here in line. The Event Loop: The "Traffic Cop." It waits until the Call Stack is empty, then pushes the next task from the Queue into the Stack. The Example: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); The Result :- Start End Async Task Why? Even with a 0'ms delay, that callback must visit the Web API and wait in the Queue until the main execution (the Stack) is totally clear. It’s the difference between guessing how your code works and knowing exactly why it’s behaving that way. #javascript #webdevelopment #programming #100DaysOfCode #softwareengineering #SheryianshCodingSchool Harsh Vandana Sharma
To view or add a comment, sign in
-
-
𝗦𝗶𝗺𝗽𝗹𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗿𝗶𝗰𝗸𝘀 𝗧𝗼 𝗠𝗮𝗸𝗲 𝗬𝗼𝗎𝗿 𝗖𝗼𝗱𝗲 𝗕𝗲𝘁𝘁𝗲𝗿 JavaScript is a flexible language. But most developers only use a part of what it offers. You can make your code cleaner and more professional with a few simple tricks. - Use object destructuring: const { name, email, age } = getUser(); - Set default function parameters: function greet(name = "Guest") { return `Hello ${name}`; } - Use optional chaining: console.log(user?.profile?.name); - Create objects with less code: const user = { name, age }; - Use .at() for cleaner indexing: const lastItem = array.at(-1); - Use ?? for safer default values: const username = input ?? "Guest"; - Transform objects with Object.fromEntries(): const obj = Object.fromEntries(entries); These small features can reduce bugs, improve readability, and make your code feel more professional. You can write less code that communicates more. What's one JavaScript trick you use that most developers don't know about? Source: https://lnkd.in/gbakTraz
To view or add a comment, sign in
-
I just added a new article to my series on functional programming for the web. It's actually a new variation on a previous article, but using lazy evaluation as allowed by JavaScript through iterators, and it shows some possibilities that will help in many other cases.
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗠𝗼𝘀𝘁 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗔𝗿𝗿𝗮𝘆 𝗠𝗲𝗧𝗵𝗼𝗱𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You need to know how to work with arrays in JavaScript. Arrays are a key part of programming. Here are the basics: - JavaScript has 8 main data types - A string is text - A boolean is true or false - Numbers are numeric values - BigInt is for very large numbers - Undefined is when no value is assigned - Null is an empty value - Symbol creates a unique identifier - Objects store multiple values An array is a data structure that stores multiple values in one variable. You can store different data types in the same array. Some key array methods are: - push() adds elements to the end - pop() removes the last element - shift() removes the first element - unshift() adds elements to the beginning - map() creates a new array by applying a function - filter() creates a new array with elements that match a condition - reduce() reduces all elements into a single value - forEach() runs a function for each element These methods are used in modern JavaScript development. Practice them to write cleaner and more efficient code. Source: https://lnkd.in/gyY3cNir
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗠𝗼𝘀𝘁 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗔𝗿𝗿𝗮𝘆 𝗠𝗲𝗧𝗵𝗼𝗱𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You need to know how to work with arrays in JavaScript. Arrays are a key part of programming. Here are the basics: - JavaScript has 8 main data types - A string is text - A boolean is true or false - Numbers are numeric values - BigInt is for very large numbers - Undefined is when no value is assigned - Null is an empty value - Symbol creates a unique identifier - Objects store multiple values An array is a data structure that stores multiple values in one variable. You can store different data types in the same array. Some key array methods are: - push() adds elements to the end - pop() removes the last element - shift() removes the first element - unshift() adds elements to the beginning - map() creates a new array by applying a function - filter() creates a new array with elements that match a condition - reduce() reduces all elements into a single value - forEach() runs a function for each element These methods are used in modern JavaScript development. Practice them to write cleaner and more efficient code. Source: https://lnkd.in/gyY3cNir
To view or add a comment, sign in
-
🌐 Learning Frontend Day 14: JavaScript Data Types JavaScript data types are the building blocks of all logic in web development. They define how values are stored, manipulated, and interpreted. 🔑 Key Data Types in JS: Primitive Types String → "Hello World" Number → 42, 3.14 Boolean → true / false Null → intentional empty value Undefined → variable declared but not assigned Symbol → unique identifiers BigInt → large integers beyond Number limits Non-Primitive (Reference) Types Object → collections of key-value pairs Array → ordered lists [1,2,3] Function → reusable blocks of code #FrontendDevelopment #JavaScript #WebDevelopment #LearningJourney #CodingLife #100DaysOfCode #TechSkills #DeveloperCommunity #JSBasics #CodeNewbie
To view or add a comment, sign in
-
-
These are the things that most interest me after finishing Chapter 1 of the Javascript course. Template literals: using backticks ` ` are powerful. They allow multi-line strings and, more importantly, expressions inside strings using ${}. const age = 18; console.log(`I will drink ${age >= 18 ? 'water' : 'alcohol'}`); Ternary Operator: That’s also conditional logic written cleanly in one line using the ternary operator ?. It doesn’t replace if/else, but it makes quick decisions more readable. Type conversion and coercion in JavaScript is also interesting: ‘7’ + 4 + ‘3’ → “743” ‘7’ - 4 - ‘3’ → 0 With +, if one value is a string, JavaScript concatenates. With - and other arithemetic operator, it converts values to numbers and performs arithmetic. Understanding this makes Number() and String() important when handling user input, since inputs are strings by default. Logical operators: && → all conditions must be true || → at least one condition must be true ! → reverses a boolean value. These symbols will control how decisions are made in code.
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