Today I Learned: The Power of Callbacks in JavaScript While working with event listeners, I ran into something interesting — and it made me appreciate how JavaScript handles function calls vs callbacks. Here’s the situation 👇 If I write: button.addEventListener('click', add(1, 2)); It doesn’t wait for the click. Instead, add(1, 2) gets called immediately, and the result (not the function) is passed to addEventListener. That’s why the correct approach is: button.addEventListener('click', () => add(1, 2)); Now, the function add() executes only when the event occurs — not before. 💡 Key takeaway: In JavaScript, add(1,2) executes a function, But () => add(1,2) defines a function to be executed later. This is the essence of callbacks — passing a reference to a function instead of executing it immediately. Tiny details like this make a huge difference when building interactive, event-driven apps. #JavaScript #WebDevelopment #LearningInPublic #FrontendDevelopment #Callbacks #ProgrammingTips
How to use callbacks in JavaScript for event-driven apps
More Relevant Posts
-
🧠 Is JavaScript Really Single-Threaded? You’ve probably heard that JavaScript is single-threaded — it runs one task at a time. So how does it call an API, wait for the response, and still keep your app running smoothly? 🤔 Let’s break it down 👇 ⚙️ One Thread, Many Helpers JavaScript runs on one main thread — meaning it can do only one thing at a time. But the browser or Node.js gives it helpers that work in the background: 🌐 Network threads → handle things like fetch() and API calls ⏰ Timer threads → handle setTimeout() and setInterval() 🧠 Web workers → handle heavy background tasks 🎨 Render threads → draw the UI on your screen So while JavaScript itself does one thing at a time, the environment it runs in (the browser) uses multiple threads. #JavaScript #WebDevTips #JavaScriptTips #CodingJourney
To view or add a comment, sign in
-
🚀 Bridging the Past and Present of JavaScript: Polyfills Explained! Ever wondered how modern JavaScript features like Promise, fetch, or Array.flat() work even in older browsers that never knew they existed? 🤔 That’s where Polyfills come to the rescue 💪 🧩 What exactly is a Polyfill? A polyfill is a piece of JavaScript that adds modern functionality to older browsers that don’t support it natively. It acts like a translator — helping new features communicate with old environments. ⚙️ Why Polyfills Matter in Modern Development: They make your modern web apps run consistently across all browsers 🌍 Help developers use the latest ECMAScript features without worrying about backward compatibility 🧠 Reduce maintenance headaches by automatically filling in the missing browser features 🔧 🧠 Modern Tech Integration: Today, tools like Babel, core-js, and Webpack can automatically inject polyfills during the build process. So developers can write clean, future-proof code — and the tools handle the compatibility magic behind the scenes ✨ 💬 In short — Polyfills ensure your JavaScript stays modern while your users stay happy. #JavaScript #WebDevelopment #Frontend #Coding #Polyfills #ModernWeb #TechLearning
To view or add a comment, sign in
-
-
The JavaScript Feature You’ve Probably Never Used Allows Running Untrusted JavaScript Safely Recently I learnt about JavaScript feature while debugging a tricky multi-iframe app last month, and it completely changed how I think about code isolation. Maybe you have been in this situation before when you build a feature that runs third-party code. Suddenly your app breaks because someone polluted your global objects. That’s the problem related to JavaScript Realm. Let me show you what Realms actually are, why they matter more than you think, and how you can use them to build safer, more predictable JavaScript applications. #javascript #typescript https://lnkd.in/dqSFiDqY
To view or add a comment, sign in
-
Svelte is changing how we build web applications in a simple way. Unlike other JavaScript frameworks, Svelte shifts a lot of work to the build step. This means your app can run faster and be easier to maintain. With Svelte, you write your components using straightforward HTML, CSS, and JavaScript. Once you build your app, Svelte compiles everything to highly optimized JavaScript. This leads to smaller bundle sizes and improved performance. If you're looking to try it out, here’s a small example of a Svelte component: ```html <script> let count = 0; function increment() { count += 1; } </script> <button on:click={increment}> Count: {count} </button> ``` This code creates a simple button that counts how many times it's clicked. It's easy to understand and get started with. Have you tried Svelte? What do you think of it compared to other frameworks?
To view or add a comment, sign in
-
-
If you're writing modern JavaScript, you must master asynchronous handling! Callbacks and Promises are two key ways to manage tasks like fetching data without freezing your app. Here's the breakdown: -> Callbacks: Simple and direct, but multiple tasks lead to nested, messy, unreadable code known as "Callback Hell". -> Promises: They are objects that guarantee an eventual outcome (fulfillment or rejection). They let you chain tasks neatly (the .then() method) and handle errors simply with one .catch() . Cleaner code and simpler error handling make them the modern standard. Swipe to see the difference between the nested Callback Hell and clean Promise Chaining! 🚀 Which do you prefer: Promises or are you already using Async/Await? Share below! 👇 To learn more, follow JavaScript Mastery #JavaScript #JS #Promises #Callbacks #Asynchronous #WebDevelopment #CodingTips #Developer
To view or add a comment, sign in
-
Web Development — JavaScript Practice 🧠 Today’s practice session was all about diving deeper into JavaScript fundamentals and browser interactions! We focused on: 1- Fetch API – to make network requests and handle data from external sources. 2- Promises & Async/Await – for writing cleaner, more efficient asynchronous code. 3- Advanced DOM Manipulation – understanding how to access and traverse the DOM using: parentElement, children, nextElementSibling, previousElementSibling, and more. Why are these important? Because real-world web apps rely heavily on handling data dynamically and updating the UI efficiently. Mastering these helps you create smoother user experiences and gives you deeper control over how your web pages behave. Always great to see how powerful JavaScript becomes when you understand the DOM inside out! GitHub: https://lnkd.in/e5Q86pGX #JavaScript #WebDevelopment #LearningJourney #FrontendDevelopment
To view or add a comment, sign in
-
What I built may look simple, but it taught me a lot! I created a personal portfolio website using React, Tailwind CSS, and EmailJS. Highlights: Reusable ProjectCard component for all projects Contact form sending emails directly with EmailJS Responsive layout and hover animations Challenges: Figuring out environment variables in Vite and integrating EmailJS without a backend. Takeaways: Small projects can teach big lessons — reusable components, front-end email integration, and responsive design all in one project! GitHub Link: https://lnkd.in/ezgW65aW Video Link: https://lnkd.in/eCMHc8uy W3Schools.com React Coding Ninjas Placement Cell JavaScript Developer JavaScript Mastery What small project taught you the most? #React #WebDevelopment #Portfolio #LearningByDoing #EmailJS”
To view or add a comment, sign in
-
🚀 Mastering JavaScript Events – The Backbone of Interactive Web Apps! 💡 Ever wondered how a simple click, hover, or keypress instantly brings a website to life? 🤔 That’s the magic of JavaScript Events – the powerful triggers that respond to user interactions and make web pages dynamic & engaging! 🎯 In my latest breakdown, I explore: ✅ What JavaScript Events are ✅ How Event Listeners work ✅ Common events like onclick, onkeyup, onchange, onsubmit ✅ Event Bubbling vs Capturing ✅ Real-world examples & use cases 💻 Whether you’re a beginner learning DOM manipulation or preparing for frontend interviews, understanding events is a game-changer! ✨ If you want a deeper dive with examples + best practices, let me know in the comments – I’d love to share a full guide or cheat sheet! 📌 Follow Uzma Begum Shaik for daily JS insights, frontend tips & developer-friendly guides! For Learning :) W3Schools.com JavaScript Mastery 🔥 #JavaScript #FrontendDevelopment #WebDevelopment #DOMEvents #CodingTips #ReactJS #LearnToCode #Developers #CodeWithUzma #TechContent
To view or add a comment, sign in
-
🔍 Deep Dive into JavaScript Events — The Pulse of Interactive Web Apps Ever wondered how your browser knows when you click, type, or scroll? That magic happens through JavaScript Events the heartbeat of every interactive website. 💡 In my latest deep dive, I explored everything that makes event handling so powerful in JavaScript: 🎯 Event Listeners – The way we “watch” for actions like clicks or keypresses. 🧠 Event Objects – Packed with info about what triggered the action. ⌨️ Keyboard & Mouse Events – Capturing user interaction in real-time. 🧩 Event Bubbling & Delegation – The unsung heroes behind efficient event management. 📋 Form & Input Events – Validations and dynamic feedback made easy. 🌐 Window Events – Listening at the browser level for resize, scroll, or load actions. Understanding these concepts doesn’t just make your code functional — it makes it alive, dynamic, and user focused. ⚡ 💬 Have you explored how event bubbling or delegation can optimize your DOM handling? Drop your thoughts or favorite use cases in the comments 👇 Follow Muhammad Nouman for more useful content #JavaScript #WebDevelopment #Frontend #Coding #EventListeners #TechLearning #JSDeepDive #Programming #DeveloperCommunity #JS #Events
To view or add a comment, sign in
-
🧠 Did you know JavaScript quietly creates classes behind the scenes — even when you don’t? While JavaScript is known for being flexible and dynamic, under the hood it uses a powerful optimization trick called Hidden Classes to make object access lightning-fast ⚡ When you create objects like: const user = { name: "username", age: 25 }; The JS engine (like V8 in Chrome or Node.js) secretly builds an internal blueprint to store the location of each property efficiently. This blueprint is called a Hidden Class — and it allows JavaScript to behave almost like statically typed languages (C++/Java) in terms of performance. But here’s the catch 👇 If you modify objects inconsistently — adding or removing properties in different orders — the engine has to rebuild those hidden classes, causing de-optimization (a fancy way of saying: “your code runs slower”). So next time you’re building an app, remember: ✨ Consistency in object structure = faster performance. #JavaScript #WebDevelopment #Performance #CodingTips #Frontend #NextJS #React #TechInsights
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