Demystifying the Prototype in JavaScript If there’s one concept that confuses most developers (even experienced ones), it’s the Prototype. Unlike traditional class-based languages, JavaScript uses prototypal inheritance — meaning objects can inherit directly from other objects. Every JS object has a hidden reference called its prototype, and this is what makes inheritance possible. 🔹 How It Works When you access a property like obj.prop1: 1️⃣ JS first checks if prop1 exists on the object itself. 2️⃣ If not, it looks at the object’s prototype. 3️⃣ If still not found, it continues up the prototype chain until it either finds it or reaches the end. So sometimes a property seems to belong to your object — but it actually lives further down the chain! Example const person = { firstname: "Default", lastname: "Default", getFullName() { return this.firstname + " " + this.lastname; } }; const john = Object.create(person); john.firstname = "John"; john.lastname = "Doe"; console.log(john.getFullName()); // "John Doe" Here’s what happens: JS looks for getFullName on john. Doesn’t find it → checks person (its prototype). Executes the method with this referring to john. Key Takeaways The prototype is just a hidden reference to another object. Properties are looked up the prototype chain until found. The this keyword refers to the object calling the method, not the prototype. Avoid using __proto__ directly — use Object.create() or modern class syntax. One-liner: The prototype chain is how JavaScript lets one object access properties and methods of another — simple, flexible, and core to the language. If you found this helpful, follow me for more bite-sized explanations on JavaScript, React, and modern web development #JavaScript #WebDevelopment #Frontend #React #TypeScript #Coding #LearningInPublic #SoftwareEngineering #TechEducation #WebDevCommunity
Understanding JavaScript Prototypes: A Simple Explanation
More Relevant Posts
-
⚙️ Prototype & Inheritance Made Simple In JavaScript, everything is an object (well, almost 😉). Every object has a hidden property called [[Prototype]], which points to another object — its prototype. This prototype acts like a fallback: if an object doesn’t have a property or method, JavaScript automatically looks for it in its prototype. This chain continues until it reaches Object.prototype, which is the root of all objects. Here’s a simple example to visualize this: const person = { greet() { console.log("Hello!"); } }; const student = Object.create(person); student.study = function() { console.log("Studying JS..."); }; student.greet(); // Inherited from person student.study(); // Defined in student When we call student.greet(), JavaScript doesn’t find greet in the student object. So it climbs up the prototype chain and finds it in person. That’s prototypal inheritance in action — objects inheriting behavior from other objects. Modern JS syntax like class and extends is just syntactic sugar built on top of this same prototype system. So when you write: class User { sayHi() { console.log("Hi!"); } } class Admin extends User { manage() { console.log("Managing users..."); } } const admin = new Admin(); admin.sayHi(); // Inherited from User admin.manage(); // Defined in Admin …it’s still prototypes doing the magic behind the scenes. Understanding prototypes gives you deep insight into how JavaScript actually builds and connects objects. Once you grasp it, you’ll stop thinking of JS as a “weird language” and start seeing it as one of the most flexible and powerful object systems ever designed. #JavaScript #Prototype #Inheritance #WebDevelopment #MERNStack #NodeJS #ReactJS #Frontend #CodingCommunity #LearnInPublic #100DaysOfCode
To view or add a comment, sign in
-
JS Learners & Web Devs! Ever wondered why you can call a function before it’s defined in JavaScript, but let or const throw a ReferenceError? Our latest blog dives deep into Hoisting in JavaScript: How JS engine really works Understanding the Temporal Dead Zone (TDZ) Function vs variable hoisting Common pitfalls & best practices Stop guessing and start writing safer, cleaner JS code! https://lnkd.in/dCeqNnRf #javascript #webdevelopment #hoistinginjs #learnjavascript #coding #programming #FrontendDevelopment #webdev #CodeNewbie #wenowadays
To view or add a comment, sign in
-
💡 Deep Dive into JS Concepts: How JavaScript Code Executes ⚙️ Ever wondered what really happens when you hit “Run” in JavaScript? 🤔 Let’s take a simple, visual deep dive into one of the most powerful JS concepts — ✨ The Execution Context & Call Stack! 🧠 Step 1: The Global Execution Context (GEC) When your JS file starts, the engine (like Chrome’s V8) creates a Global Execution Context — the environment where everything begins 🌍 It has two phases: 🧩 Creation Phase Memory allocated for variables & functions Variables set to undefined (Hoisting!) Functions fully stored in memory ⚡ Execution Phase Code runs line by line Variables get actual values Functions are executed 🚀 🔁 Step 2: Function Execution Context (FEC) Every time a function is called, a brand-new Execution Context is created 🧩 It also runs through creation + execution phases. When the function finishes — it’s removed from memory 🧺 🧱 Step 3: The Call Stack Think of the Call Stack like a stack of plates 🍽️ Each function call adds (pushes) a new plate When done, it’s removed (popped) JS always executes the topmost plate first Example 👇 function greet() { console.log("Hello"); } function start() { greet(); console.log("Welcome"); } start(); 🪜 Execution Order: 1️⃣ GEC created 2️⃣ start() pushed 3️⃣ greet() pushed 4️⃣ greet() popped 5️⃣ start() popped 6️⃣ GEC popped ✅ ⚙️ Step 4: Quick Recap 🔹 JS runs inside Execution Contexts 🔹 Each function = its own mini world 🔹 Contexts live inside the Call Stack 🔹 Each runs through Creation → Execution “JavaScript doesn’t just run line-by-line — it builds a whole world (context) for your code to live and execute inside.” 🌐 #javascript #webdevelopment #frontend #developers #learnjavascript #executionscontext #callstack #jsengine #programming #deeplearning
To view or add a comment, sign in
-
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
Today's Topic: Promise Chaining in JavaScript In JavaScript, Promise chaining allows you to execute asynchronous tasks one after another, ensuring that each step waits for the previous one to finish. Instead of nesting callbacks (callback hell ), promises make your code cleaner and easier to maintain. Example: function step1() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 1 completed ✅"); resolve(10); }, 1000); }); } function step2(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 2 completed ✅"); resolve(value * 2); }, 1000); }); } function step3(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 3 completed ✅"); resolve(value + 5); }, 1000); }); } // Promise Chaining step1() .then(result => step2(result)) .then(result => step3(result)) .then(finalResult => console.log("Final Result:", finalResult)) .catch(error => console.error("Error:", error)); ✅ Output (after 3 seconds): Step 1 completed ✅ Step 2 completed ✅ Step 3 completed ✅ Final Result: 25 Each .then() runs after the previous promise resolves — making async flow easy to read and manage. --- 🔖 #JavaScript #WebDevelopment #PromiseChain #AsyncProgramming #CodingTips #FrontendDevelopment #Developers #JSConcepts #CodeLearning #100DaysOfCode #WebDevCommunity
To view or add a comment, sign in
-
-
💡 Ever changed a copy of an object… and accidentally changed the original too? If you’ve worked with JavaScript, you know this painful trap all too well! Let’s clarify the difference between shallow copy and deep copy, and see how modern JS handles it. 🔹 Shallow Copy A shallow copy duplicates only the top-level properties. Nested objects or arrays are still shared. const original = { name: "Alice", details: { age: 25 } }; const shallowCopy = { ...original }; shallowCopy.details.age = 30; console.log(original.details.age); // 30 → original object changed! ✅ Top-level copied. ⚠️ Nested objects still reference the same memory. 🔹 Deep Copy A deep copy duplicates everything, including nested objects, so changes don’t affect the original. 1️⃣ Using JSON.stringify() + JSON.parse() const original = { name: "Alice", details: { age: 25 } }; const deepCopy = JSON.parse(JSON.stringify(original)); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ⚠️ Limitation: Doesn’t handle Dates, Maps, Sets, functions, or circular references. 2️⃣ Using structuredClone() (Modern JS) const original = { name: "Alice", details: { age: 25 } }; const deepCopy = structuredClone(original); deepCopy.details.age = 30; console.log(original.details.age); // 25 → safe! ✅ Handles most types, including Date, Map, Set, etc. ⚠️ Available in modern browsers & Node.js v17+. #JS #JavaScript #WebDevelopment #DeepCopy #ShallowCopy #CodingTips #Programming
To view or add a comment, sign in
-
👉 Think You’re Copying Objects Correctly in JavaScript? Think Again! Many developers (even experienced ones) get unexpected results when working with object copies, leading to sneaky bugs! Let’s break it down 👇 🧠 Shallow vs Deep Copy in JavaScript A shallow copy only copies the first layer of the object, while a deep copy duplicates everything, including nested objects. 💡 Why it matters: Understanding these differences is crucial when managing state in frameworks like React or Vue. A shallow copy can cause unwanted side effects, especially when updating complex data structures. Choosing the right method (like structuredClone, JSON.parse(JSON.stringify()), or libraries like lodash.cloneDeep) ensures cleaner, more predictable code. 🤔 Your turn: How do you usually handle object copying in your projects? Do you prefer built-in methods or libraries? Let’s discuss! #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #ReactJS
To view or add a comment, sign in
-
-
🚀 Understanding Functions in JavaScript — The Building Blocks of Logic! While exploring JavaScript, I realized that functions are at the heart of writing clean, reusable, and organized code. They help us break down complex logic into smaller, manageable parts. Here’s a quick breakdown of different types of functions in JavaScript 👇 🟢 1. Function Declaration function greet() { console.log("Hello, World!"); } ✅ Hoisted — can be called before their definition. 🟣 2. Function Expression const greet = function() { console.log("Hello, World!"); }; ⚠️ Not hoisted — must be defined before use. 🔵 3. Arrow Function (ES6) const greet = () => console.log("Hello, World!"); 💡 Short, modern syntax — great for callbacks and concise logic. 🟠 4. Anonymous Function Used without a name, often inside event handlers or callbacks. setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 🔴 5. Immediately Invoked Function Expression (IIFE) Runs immediately after it’s defined. (function() { console.log("IIFE executed!"); })(); Useful for creating isolated scopes. 🟢 6. Higher-Order Function A function that takes another function as an argument or returns one. function operate(a, b, callback) { return callback(a, b); } operate(2, 3, (x, y) => x + y); // Output: 5 🔁 Common in methods like .map(), .filter(), and .reduce(). ✨ Functions are like the brain of your JavaScript code — they decide how everything works together! 💬 What’s your favorite type of JavaScript function and why? Let’s discuss how each type fits into modern JS coding! #JavaScript #WebDevelopment #Frontend #Coding #Programming #LearningJourney
To view or add a comment, sign in
-
POST 5: Vanilla JavaScript vs Frameworks: The Pragmatic Choice ⚡ Why I Chose Simplicity Over Sophistication With the backend sorted, I faced the classic dilemma: Framework or Vanilla JavaScript? Here’s the reality I was working with: - Limited coding experience - Tight weekend-only timeline - Solo developer (just me) - Hosted locally on my laptop - Non-tech teammates And that’s exactly why Vanilla JS + Tailwind CSS won. - Speed That Actually Matters - No build tools, no setup hell - Test directly in browser - Instant feedback loop - Less to break, easier to fix 📚 Debugging I Could Actually Understand - Stack traces made sense - No “framework magic” to decode - console.log() was my best friend - Chrome DevTools just worked flawlessly 🎯 Clean & Functional Codebase <div class="bg-white rounded-lg shadow-md p-6"> <h2 class="text-xl font-bold mb-4">Rankings</h2> <div id="leaderboard"></div> </div> Simple authentication logic: function authenticate(key) { return fetch(`${API_URL}/Users!A:F`) .then(response => response.json()) .then(data => validateKey(data, key)); } 🎨 Tailwind CSS Benefits - Zero custom CSS to maintain - Consistent design system -Mobile-responsive out of the box - Professional look: no designer needed 📊 The Final Stats ~300 lines of JavaScript Clean, readable, maintainable code Works across all devices Future developers can jump in instantly ⚙️ Performance on Local Network Sub-100ms page loads Real-time updates via API Zero framework bloat Sometimes “basic” tech is exactly what you need. Next up: Building authentication without a traditional database. 👉 When has the “simpler” tech stack been the right choice for you? #VanillaJS #TailwindCSS #WebDevelopment #LowCode #KISS #PragmaticEngineering #FrontendDevelopment
To view or add a comment, sign in
-
Ever wondered how JavaScript functions remember things? The secret is Closures! 🤫 A closure is a fundamental JS concept where a function remembers the variables from its outer scope, even after that outer function has finished executing. 🚀 **Why They're Powerful:** Closures are the backbone of many advanced JavaScript patterns. They enable: 🔹 **Data Encapsulation:** Creating private variables and methods, which is crucial for protecting your data from the global scope. Think of it as a private vault for your function's state. 🔹 **Function Factories:** Building functions that can generate other functions with specific, pre-configured settings. 🔹 **Maintaining State:** Powering callbacks and event handlers in asynchronous operations, allowing them to access the variables they need long after they were created. 🤔 **Why They're Tricky:** With great power comes potential pitfalls. Closures can be tricky if you're not careful: 🔸 **Memory Leaks:** Since closures hold references to their outer scope variables, they can prevent the garbage collector from cleaning up memory if not managed properly. 🔸 **Stale Data:** In loops, closures can accidentally capture the same variable reference, leading to all of them using the final value of the loop, which can cause unexpected bugs. Mastering closures is a rite of passage for any JavaScript developer. Understanding them unlocks a new level of control, enabling you to write more modular, elegant, and robust code. What are your favorite use cases or tricky moments with closures? Share in the comments! 👇 #JavaScript #WebDevelopment #Programming #Coding #Developer #Closures #SoftwareEngineering #Frontend #TechTips #LearnToCode #JS
To view or add a comment, sign in
-
More from this author
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