💡 Understanding Scope in JavaScript One of the most important concepts in JavaScript is Scope. Scope defines where variables can be accessed in your code. There are three main types of scope in JavaScript: 🔹 Global Scope Variables declared outside any function are accessible anywhere in the program. let name = "Muneeb"; function showName() { console.log(name); } showName(); // Accessible because it's global 🔹 Function Scope Variables declared inside a function can only be used inside that function. function greet() { let message = "Hello"; console.log(message); } greet(); // console.log(message); ❌ Error 🔹 Block Scope Variables declared with "let" and "const" inside "{ }" are only accessible within that block. if (true) { let age = 25; console.log(age); } // console.log(age); ❌ Error 📌 Understanding scope helps developers write cleaner code and avoid bugs related to variable access. Mastering these fundamentals makes JavaScript much easier to understand and improves problem-solving skills. #JavaScript #WebDevelopment #FrontendDeveloper #Coding #LearnToCode
JavaScript Scope: Global, Function, Block
More Relevant Posts
-
Day 4/100 of JavaScript 🚀 Today’s focus: Functions in JavaScript Functions are reusable blocks of code used to perform specific tasks Some important types with example code: 1. Parameterized function → takes input function greet(name) { return "Hello " + name; } greet("Apsar"); 2. Pure function → same input always gives same output, no side effects function add(a, b) { return a + b; } add(2, 3); 3. Callback function → function passed into another function function processUser(name, callback) { callback(name); } processUser("Apsar", function(name) { console.log("User:", name); }); 4.Function expression → function stored in a variable const multiply = function(a, b) { return a * b; }; 5.Arrow function → shorter syntax const square = (n) => n * n; Key understanding: Functions are first-class citizens in JavaScript — they can be passed, returned, and stored like values #Day4 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
🔥 Understanding callback functions in JavaScript! 🚀 Callback functions are functions passed as arguments to other functions to be executed later. They are commonly used in event handling, asynchronous actions, and more. ⚡️ Why it matters: Callback functions allow developers to write more flexible and reusable code. They are essential in handling tasks that need to be executed at a specific time. 🔹 Step by step breakdown: 1️⃣ Define the main function that will execute the callback. 2️⃣ Create the callback function to be passed as an argument. 3️⃣ Call the main function and pass the callback as an argument. 👨💻 Code example: ```javascript function mainFunction(callback) { // Do something callback(); } function callbackFunction() { console.log('Callback executed!'); } mainFunction(callbackFunction); ``` 💡 Pro tip: Keep callback functions simple and focused on a specific task for better code readability. ⚠️ Common mistake: Forgetting to invoke the callback within the main function, resulting in the function not executing as intended. ❓ Have you ever used callback functions in your projects? Share your experiences below! 💬 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaScript #CallbackFunctions #AsyncProgramming #CodeNewbie #WebDevelopment #LearnToCode #DeveloperTips #FunctionCallbacks #EventHandling #AsynchronousJavaScript
To view or add a comment, sign in
-
-
🚀 Day 22 – Understanding the this Keyword in JavaScript If there’s one concept that confuses almost every JavaScript developer at some point… it’s this 😅 But once you get it right, everything starts to make sense 🔥 🧠 The Truth About this 👉 this doesn’t refer to where the function is written 👉 It refers to how the function is called That’s the game changer. ⚡ What I Learned Today ✔️ In objects → this refers to the object ✔️ In regular functions → this is global (or undefined in strict mode) ✔️ In arrow functions → no own this (inherits from parent) ✔️ In event listeners → this is the element 👨💻 Angular Dev Tip If you’ve ever lost this inside setTimeout or callbacks… you’re not alone 😄 👉 Arrow functions are your best friend here: They preserve the component context ✅ 💡 Why This Matters Understanding this helps you: Write cleaner, bug-free code Avoid unexpected behavior Master advanced JS concepts #JavaScript #Angular #FrontendDevelopment #WebDevelopment #100DaysOfCode #LearnInPublic
To view or add a comment, sign in
-
-
5 JavaScript concepts that make everything else click. Learn these deeply and frameworks stop being magic. 1. Closures A function that remembers the scope it was created in. This is how callbacks, event listeners, and setTimeout actually work. Not understanding closures = constant bugs you can't explain. 2. The Event Loop JavaScript is single-threaded. The event loop is how async code doesn't block everything else. If you've ever wondered why setTimeout(fn, 0) still runs after synchronous code — this is why. 3. Prototypal Inheritance Every object in JS has a prototype chain. Classes are just syntax sugar over this. Knowing this means you understand how methods are shared and where "cannot read properties of undefined" is actually coming from. 4. this - and how it changes 'this' is not fixed. It depends on how a function is called, not where it's defined. Arrow functions inherit 'this' from their enclosing scope. Regular functions create their own. This one trips up everyone. 5. Promises and the microtask queue Promises don't just "make async code cleaner." They run in the microtask queue, which runs before the next macrotask (setTimeout). Understanding this makes async debugging dramatically easier. Which of these gave you the biggest headache? 👇 #webdeveloper #coding #javascript
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop (In Simple Terms) If you’ve ever wondered how JavaScript handles multiple tasks at once, the answer lies in the Event Loop. 👉 JavaScript is single-threaded, meaning it can execute one task at a time. 👉 But with the help of the Event Loop, it can handle asynchronous operations efficiently. 🔹 How it works: 1. Call Stack – Executes synchronous code (one task at a time) 2. Web APIs – Handles async operations like setTimeout, API calls, DOM events 3. Callback Queue – Stores callbacks from async tasks 4. Event Loop – Moves tasks from the queue to the call stack when it’s empty 🔹 Microtasks vs Macrotasks: - Microtasks (Promises, MutationObserver) → Executed first - Macrotasks (setTimeout, setInterval, I/O) → Executed later 💡 Execution Order Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 👉 Output: Start End Promise Timeout 🔥 Key Takeaways: ✔ JavaScript doesn’t run tasks in parallel, but it handles async smartly ✔ Microtasks always run before macrotasks ✔ Event Loop ensures non-blocking behavior Understanding this concept is a game-changer for writing efficient and bug-free JavaScript code 💻 #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Programming #EventLoop
To view or add a comment, sign in
-
-
🚀 Why Does null Show as an Object in JavaScript? 🤯 While practicing JavaScript, I came across something interesting: let myVar = null; console.log(typeof myVar); // Output: object At first, it feels confusing… why is null an object? 🤔 💡 Here’s the simple explanation: null is actually a primitive value that represents "no value" or "empty". But when JavaScript was first created, there was a bug in the typeof operator. Due to this bug, typeof null returns "object" instead of "null". ⚠️ This behavior has been kept for backward compatibility, so changing it now would break existing code. 🔍 Key Takeaways: null → means "nothing" (intentional empty value) typeof null → returns "object" (this is a historical bug) Objects (like {}) also return "object" 💻 Example: let myObj = { name: "John" }; console.log(typeof null); // object ❌ (bug) console.log(typeof myObj); // object ✅ (correct) 📌 Conclusion: Even though both return "object", they are completely different in meaning. 👉 JavaScript is powerful, but it has some quirky behaviors—this is one of them! #JavaScript #WebDevelopment #CodingJourney #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
🧠 Day 13 — Class vs Prototype in JavaScript (Simplified) JavaScript has both Classes and Prototypes — but are they different? 🤔 --- 🔍 The Truth 👉 JavaScript is prototype-based 👉 class is just syntactic sugar over prototypes --- 📌 Using Class (Modern JS) class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}`); } } const user = new Person("John"); user.greet(); // Hello John --- 📌 Using Prototype (Core JS) function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log(`Hello ${this.name}`); }; const user = new Person("John"); user.greet(); // Hello John --- 🧠 What’s happening? 👉 Both approaches: Create objects Share methods via prototype Work almost the same under the hood --- ⚖️ Key Difference ✔ Class → Cleaner, easier syntax ✔ Prototype → Core JavaScript mechanism --- 🚀 Why it matters ✔ Helps you understand how JS works internally ✔ Useful in interviews ✔ Makes debugging easier --- 💡 One-line takeaway: 👉 “Classes are just a cleaner way to work with prototypes.” --- #JavaScript #Prototypes #Classes #WebDevelopment #Frontend #100DaysOfCode
To view or add a comment, sign in
-
🚀 JavaScript Concepts Series – Day 3 / 30 👀 Let's Revise the Basics🧐 Understanding the difference between var, let, and const is a fundamental concept in JavaScript. Choosing the right variable declaration helps prevent bugs and makes your code more predictable. 🔹 var Function scoped Can be redeclared Can be reassigned Hoisted (initialized with undefined) 🔹 let Block scoped Cannot be redeclared in the same scope Can be reassigned Hoisted but stays in Temporal Dead Zone (TDZ) until initialized 🔹 const Block scoped Cannot be redeclared Cannot be reassigned Must be initialized during declaration 💡 Key Insight var → Old way of declaring variables (function scoped) let → Use when the value may change const → Use when the value should not change Using let and const helps write safer and more maintainable JavaScript code. More JavaScript concepts coming soon. 🚀 #javascript #js #webdevelopment #frontenddeveloper #coding #programming #softwaredeveloper #developers #learnjavascript #javascriptdeveloper #codinglife #devcommunity #webdev #reactjs #mernstack #codingjourney #codeeveryday #techlearning #developerlife #100daysofcode
To view or add a comment, sign in
-
-
✨ Object Methods in JavaScript Objects are one of the most fundamental parts of JavaScript, and knowing how to work with them efficiently can make your code much more powerful and readable. In today’s post, I’ve covered important object methods in JavaScript that every developer should know. Understanding these methods helps you manipulate data structures more effectively and write cleaner, more efficient code. If you work with JavaScript regularly, mastering object methods is definitely a must. 👇 Which JavaScript object method do you use the most in your projects? Follow Muhammad Nouman for more useful content #learningoftheday #1000daysofcodingchallenge #FrontendDevelopment #WebDevelopment #JavaScript #React #Next #CodingCommunity
To view or add a comment, sign in
Explore related topics
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