New blog on function declarations vs function expressions in JavaScript. Both are ways to define functions, but they behave differently in practice, especially in terms of when they can be used and how they’re created in the code. If you’re learning JavaScript fundamentals, this might help: https://lnkd.in/gn6DtpZJ Feedback is welcome. Chai Aur Code Hitesh Choudhary Piyush Garg
JavaScript Function Declarations vs Expressions
More Relevant Posts
-
ES2025 Dropped: Say Hello to switch Expressions with Pattern Matching! ✨ Tired of verbose `if/else` chains? What if your `switch` could do *more* than just simple equality checks? Get ready, JavaScript wizards! While hypothetical for ES2025, the concept of `switch` expressions with pattern matching is a game-changer we're all dreaming of. Imagine writing cleaner, more readable conditional logic that also returns a value! No more messy `if/else if` ladders or limited `switch` statements. This isn't just about checking values; it's about destructuring, type checking, and matching complex structures directly. Dive into this snippet to see how it could make your future JS code shine! What do you think of this potential future JS? Drop your thoughts below! 👇 Explaination: `switch` expressions with pattern matching, a hypothetical ES2025 feature, would revolutionize conditional logic in JavaScript. Instead of just equality checks, you could destructure, type check, and apply conditions directly within `case` clauses, making your code significantly cleaner and more expressive. Plus, it returns a value! 1. `switch` expressions return a value, unlike traditional `switch` statements. 2. Pattern matching allows for destructuring, type checking, and conditional logic (`when` clause) directly in `case` statements. 3. Simplifies complex `if/else if` chains into readable, declarative patterns. 4. Enhances code readability and maintainability by grouping related logic. 5. Aims to make JavaScript more powerful for data processing and state management. ⚙️ Built using my automated code-to-image server and n8n. If you spot anything improvable, I’d love your feedback.
To view or add a comment, sign in
-
-
🧠 𝗗𝗼 𝗬𝗼𝘂 𝗥𝗲𝗮𝗹𝗹𝘆 𝗞𝗻𝗼𝘄 𝗪𝗵𝗮𝘁 `new` 𝗗𝗼𝗲𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? ⤵️ The new Keyword in JavaScript: What Actually Happens ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/dyAXzDHD 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ What actually happens internally when you use `new` ⇢ The 4-step process: create → link → run → return ⇢ Constructor functions & how they really work ⇢ Prototype linking & why it matters ⇢ How instances share methods but keep separate data ⇢ Recreating `new` manually (deep understanding) ⇢ What goes wrong when you forget `new` ⇢ Debugging real-world bugs related to constructors ⇢ new vs ES6 classes — what's really different ⇢ Key tradeoffs & hidden pitfalls Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Programming #SystemDesign #Frontend #Hashnode
To view or add a comment, sign in
-
JavaScript Event Loop (Microtask vs Macrotask) — explanation We often see this code: console.log("start") setTimeout(() => { console.log("timeout") }, 0) Promise.resolve().then(() => { console.log("promise") }) console.log("end") Output: start end promise timeout Why does this happen? Basic: JavaScript is single-threaded That means it runs one thing at a time (Call Stack) But async tasks like setTimeout and Promise go to different queues. There are two types of queues: Microtask Queue (high priority) Promise.then() async/await Macrotask Queue (low priority) setTimeout setInterval DOM events Event Loop rule (very important): First, all synchronous code runs Then, all microtasks run Then, one macrotask runs Then the loop continues Easy way to remember: Sync → Microtask → Macrotask → Repeat Example breakdown: console.log("start") // sync setTimeout(() => { console.log("timeout") // macrotask }, 0) Promise.resolve().then(() => { console.log("promise") // microtask }) console.log("end") // sync Step by step: start → prints end → prints promise → runs next (microtask, higher priority) timeout → runs last (macrotask) Common mistake: Many people think: “setTimeout with 0ms runs immediately” This is wrong It only goes to the queue, it does not run immediately Final takeaway: JavaScript runs synchronous code first Then microtasks (Promise) Then macrotasks (setTimeout) Pro tip: If you understand this concept well, it will help you with: API handling React state updates Debugging async issues
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗮𝘀𝗶𝗰𝘀 𝗼𝗳 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗩𝘀 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 You write code in JavaScript. But do you know how it runs? - Synchronous code runs line by line, one after another. - Asynchronous code does not wait. Here is an example of Synchronous code: console.log("Start") function slowTask() { for (let i = 0; i < 1e9; i++) {} console.log("Task Done") } slowTask() console.log("End") Output: Start Task Done End Here is an example of Asynchronous code: console.log("Start") setTimeout(() => { console.log("Task Done") }, 2000) console.log("End") Output: Start End Task Done JavaScript is single-threaded. This means it can only do one task at a time. Asynchronous code helps with this. It lets your website keep running while it waits for something to happen. There are three main ways to write Asynchronous code in JavaScript: - Callback: an old method - Promise: a better method - Async/Await: the best and most modern method You can use Async/Await like this: function fetchData() { return new Promise((resolve) => { setTimeout(() => { resolve("Data fetched") }, 2000) }) } async function getData() { let data = await fetchData() console.log(data) } getData() Source: https://lnkd.in/gxZ4NMhr
To view or add a comment, sign in
-
🚀 Shallow Copy vs Deep Copy in JavaScript Ever copied an object and accidentally changed the original? That’s not a bug… that’s reference behavior in JavaScript. 🧠 What Happens When You Copy Data? In JavaScript, objects and arrays are stored by reference, not by value. 👉 So when you “copy” them, you might just be copying the address, not the actual data. 🔹 1. Shallow Copy (⚠️ Partial Copy) A shallow copy copies only the top level. Nested objects/arrays still share the same reference. 📌 Example: const student = { name: "Javascript", marks: { math: 90 } }; const copy = { ...student }; copy.marks.math = 50; console.log(student.marks.math); // 50 (original changed!) What just happened? 👉 You changed the copy… 👉 But the original also changed! 💡 Reason: Only the outer object was copied marks is still the same reference ✅ How to Create Shallow Copy // Objects const copy1 = { ...obj }; const copy2 = Object.assign({}, obj); // Arrays const arrCopy = [...arr]; 🔹 2. Deep Copy (✅ Full Independent Copy) A deep copy creates a completely new object, including all nested levels. 👉 No shared references → No accidental changes 📌 Example: const deepCopy = structuredClone(student); deepCopy.marks.math = 50; console.log(student.marks.math); // ✅ 90 (original safe) ✅ Modern Way (Recommended) const deepCopy = structuredClone(user); 👉 Handles nested objects properly ⚡ Key Takeaway 👉 If your object has nested data, shallow copy is NOT enough #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Understanding Prototypal Inheritance and the Prototype Chain Dive into the fascinating world of prototypal inheritance in JavaScript. Let's unravel the prototype chain together! hashtag#javascript hashtag#prototypalinheritance hashtag#programming hashtag#webdevelopment ────────────────────────────── Core Concept Have you ever wondered how JavaScript objects inherit properties? Prototypal inheritance allows one object to access properties and methods of another object — but how does that play out in practice? Key Rules - All JavaScript objects have a prototype. - The prototype chain is a series of links between objects. - Properties or methods not found on an object can be looked up on its prototype. 💡 Try This const animal = { eats: true }; const rabbit = Object.create(animal); rabbit.hops = true; console.log(rabbit.eats); // true ❓ Quick Quiz Q: What does the Object.create method do? A: It creates a new object with the specified prototype object. 🔑 Key Takeaway Mastering prototypal inheritance can unlock powerful patterns in your JavaScript projects! ────────────────────────────── 🔗 Read the full detailed guide with code examples, comparison tables & step-by-step instructions: https://lnkd.in/gKG6Ez9k
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Unlocking the Power of Proxy and Reflect in JavaScript Let's dive into the Proxy and Reflect APIs in JavaScript and how they can enhance your coding skills. #javascript #proxy #reflect #webdevelopment ────────────────────────────── Core Concept Have you ever wished you could intercept and customize operations on objects? The Proxy and Reflect APIs might be just what you need! They allow you to define custom behavior for fundamental operations (like property lookup and assignment) on objects. Are you ready to explore how they work? Key Rules • Proxies can intercept operations on objects (e.g., get, set). • Reflect provides methods to operate on objects directly, making it easier to manipulate them. • Both tools enable more dynamic and robust code, reducing boilerplate. 💡 Try This const target = { name: 'Alice' }; const handler = { get: (obj, prop) => Hello, ${obj[prop]}! }; const proxy = new Proxy(target, handler); console.log(proxy.name); // Outputs: Hello, Alice! ❓ Quick Quiz Q: What is the primary purpose of using a Proxy in JavaScript? A: To define custom behavior for fundamental operations on objects. 🔑 Key Takeaway Leverage Proxy and Reflect to write cleaner, more powerful JavaScript code!
To view or add a comment, sign in
-
𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 𝗜𝗻 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Destructuring in JavaScript reduces code verbosity and speeds up writing array or object data manipulation. You can use it with arrays and objects to see its features and advantages. It is a special syntax for unpacking array items or object property access. This provides a concise way to reduce code verbosity without modifying the original data. To destructure an array, use square brackets on the left side and put the array reference on the right side. You can catch items in variables. - const items = ["apple", "ball", "cat"] - const [first, second, third] = items - console.log(first) // apple - console.log(second) // ball - console.log(third) // cat You can skip values by using extra commas: - const [first, , third] = items - console.log(first) // apple - console.log(third) // cat Object destructuring is similar, but uses curly brackets and catches properties by their actual keys. - const user = {name: "anoop", age: 21} - const {name, age} = user - console.log(name) // anoop - console.log(age) //
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗡𝗲𝗪 𝗞𝗲𝗬𝗪𝗼𝗥𝗱 𝗜𝗡 𝗝𝗮𝗩𝗮𝗦𝗰𝗿𝗶𝗽𝗧 You use the new keyword to create instances from classes in JavaScript. But what does new actually do? - It tells JavaScript to treat a function as a constructor and create a new object instance. - It links the new object's prototype to the constructor's prototype. - It binds this to the new object. - It executes the constructor body. - It returns the new object. Here's an example: ``` is not allowed, so function Person(name, age) { this.name = name; this.age = age; } const ritam = new Person("Ritam", 22); JavaScript does these steps: - Creates a new empty object. - Links the new object's prototype to Person.prototype. - Binds this to the new object. - Executes the constructor body. - Returns the new object. This creates a fully-formed instance with its own properties, linked to the shared prototype. - Every instance has an internal link pointing to the constructor's prototype object. - You can add methods to the prototype, and all instances will share them. Using new gives you a unique instance each time: - const ritam = new Person("Ritam", 22); - const priya = new Person("Priya", 20); Each instance has its own properties, but they share the same prototype methods. Understanding the new keyword helps you debug prototype chains and write advanced patterns. Source: https://lnkd.in/gsGQpDeR
To view or add a comment, sign in
-
Day 8/100 of JavaScript 🚀 Today’s Topic: Objects and their manipulation Objects in JavaScript store data in key-value pairs Example: const user = { name: "Apsar", age: 24 }; 🔹Accessing values user.name user["age"] 🔹Adding / updating user.city = "Chennai"; user.age = 25; 🔹Deleting delete user.city; 🔹Iteration for (let key in user) { console.log(key, user[key]); } 🔹Useful methods Object.keys(user); Object.values(user); Object.entries(user); 🔹Copy (shallow) const newUser = { ...user }; 🔹Object.freeze() Object.freeze(user); user.age = 30; // ❌ no change Prevents adding, deleting, or updating properties 🔹Object.seal() Object.seal(user); user.age = 30; // ✅ allowed user.city = "Chennai"; // ❌ not allowed Allows update, but prevents add/delete 🔹Object.assign() const obj = Object.assign({}, user); Used to copy or merge objects Objects are reference types. Methods like "freeze" and "seal" help control how data can be modified #Day8 #JavaScript #100DaysOfCode
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