🍏 JavaScript Daily Bite #8: Understanding Constructors Prototypes allow us to reuse properties across multiple instances — especially for methods. Constructor functions take this further by automatically setting the [[Prototype]] for every object created. ⚙️ Constructor Functions Constructors are just functions called with the new operator. Every instance created from a constructor automatically inherits from its prototype property. Key Concepts Constructor.prototype becomes the [[Prototype]] of all instances Constructor.prototype.constructor references the constructor function itself Returning a non-primitive from a constructor overrides the default instance 🧩 Classes vs Constructor Functions ES6 classes are syntactic sugar over constructor functions — the underlying behavior is the same. You can still manipulate Constructor.prototype to modify behavior across all instances. 🔧 Mutating Prototypes Since all instances share the same prototype object, mutating it changes behavior for every instance. However, reassigning the entire Constructor.prototype object is problematic because: Older instances will still reference the old prototype The constructor link may be lost, breaking user expectations and built-in operations 🧱 Constructor Prototype vs Function Prototype Constructor.prototype is used when creating instances. It’s separate from Constructor.[[Prototype]], which points to Function.prototype. ⚙️ Implicit Constructors of Literals Literal syntaxes in JavaScript automatically set their [[Prototype]]: Object literals → Object.prototype Array literals → Array.prototype RegExp literals → RegExp.prototype This is why array methods like map() or filter() are available everywhere — they live on Array.prototype. 🚫 Monkey Patching Warning Extending built-in prototypes (e.g., Array.prototype) is dangerous because it: Risks forward compatibility if new methods are added to the language Can “break the web” by changing shared behavior The only valid reason is for polyfilling newer features safely. 🧬 Building Longer Inheritance Chains Constructor.prototype becomes the [[Prototype]] of instances — and that prototype itself can inherit from another. Default chain: instance → Constructor.prototype → Object.prototype → null To extend the chain, use Object.setPrototypeOf() to link prototypes explicitly. In modern syntax, this corresponds to class Derived extends Base. ⚠️ Avoid legacy patterns: Object.create() can build inheritance chains but reassigns prototype, removes constructor, and can introduce subtle bugs. ✅ Best practice: Mutate the existing prototype with Object.setPrototypeOf() instead. 🌱 Next in the Series → Functions & Prototypes: A Deeper Dive #JavaScript #WebDevelopment #Frontend #Programming #LearnToCode #TechEducation #SoftwareDevelopment #JSDailyBite
Reyhaneh Khoshghadam’s Post
More Relevant Posts
-
Day 19/100 Day 10 of JavaScript Mastering String Methods in JavaScript In JavaScript, strings are sequences of characters used to represent text. But what makes them truly powerful are the built-in string methods that help us manipulate and analyze text efficiently. Let’s explore some of the most useful ones 1. length — Find String Length Returns the number of characters in a string. let name = "JavaScript"; console.log(name.length); // Output: 10 Useful when you need to validate input length, like passwords or usernames 2. toUpperCase() & toLowerCase() — Change Case Converts all characters to upper or lower case. let lang = "javascript"; console.log(lang.toUpperCase()); // JAVASCRIPT console.log(lang.toLowerCase()); // javascript Handy for case-insensitive comparisons. 3. includes() — Check if a Word Exists Checks if a string contains a specific substring. let sentence = "Learning JavaScript is fun!"; console.log(sentence.includes("JavaScript")); // true Perfect for search or filter functions. 4. indexOf() & lastIndexOf() — Find Positions Finds the index of the first or last occurrence of a substring. let text = "Hello JavaScript world!"; console.log(text.indexOf("JavaScript")); // 6 console.log(text.lastIndexOf("o")); // 19 Useful for locating specific patterns in strings. 5. slice() — Extract a Portion Extracts part of a string based on index range. let str = "JavaScript"; console.log(str.slice(0, 4)); // "Java" Often used to trim text or extract keywords. 6. replace() — Replace Text Replaces a substring with another. let msg = "I love JavaScript!"; console.log(msg.replace("JavaScript", "Python")); // "I love Python!" Useful for content formatting or dynamic text updates. 7. trim() — Remove Extra Spaces Removes whitespace from both ends of a string. let input = " Hello World! "; console.log(input.trim()); // "Hello World!" Essential for cleaning user input. 8. split() — Convert String to Array Splits a string into an array based on a delimiter. let fruits = "apple,banana,grape"; console.log(fruits.split(",")); // ["apple", "banana", "grape"] Commonly used when processing CSV data. 9. charAt() — Get Character by Index Returns the character at a specific index. let word = "Hello"; console.log(word.charAt(1)); // "e" 10. concat() — Join Multiple Strings Combines two or more strings. let first = "Hello"; let second = "World"; console.log(first.concat(" ", second)); // "Hello World" Alternative to using + for string concatenation. Quick Tip: All string methods return new strings — they don’t modify the original one since strings in JavaScript are immutable. Final Thought: Mastering string methods helps you handle text data like a pro — from formatting user inputs to processing dynamic content. #10000coders #JavaScript #WebDevelopment #CodingTips #LearnJavaScript #Developers #LinkedInLearning
To view or add a comment, sign in
-
✍️ JavaScript Tip: Optional Chaining (?.) If you’ve ever tried accessing something deep inside an object and got an error like: Cannot read property 'x' of undefined You're not alone 😅 This happens a lot when you're not sure if a value exists. For example, you’re trying to access user.profile.picture.url, but profile might be missing or picture might not be there. Without checking every step, JavaScript throws an error and your app can crash ❌ It use to happen to me too🥲 I once ran into a bug while building a simple post form where users could optionally add tags through a tags input. Everything was working fine but form submission was slow. Then decided to optimize the image upload flow by compressing images on the front end and uploading them all at once to Cloudinary, which made the form submit faster. While testing, I filled only the required fields and left out the optional tags. That’s when the form crashed. The backend expected a string to split into an array, but since tags was undefined, calling .split(',') threw an error. A simple fix like tags?.split(',') || [] would’ve handled it safely. That’s when optional chaining really made sense to me. ✅ You might be wondering what optional chaining really does to safeguard your code. Let me explain😎 Optional chaining (?.) lets you safely access nested values without having to check each level manually. Instead of writing: if (user && user.profile && user.profile.picture) { // ... } You can simply write: user?.profile?.picture?.url If anything in that chain doesn’t exist (undefined or null), JavaScript just returns undefined instead of crashing 😌 🤔 What’s Really Happening When you use optional chaining (?.), JavaScript checks step by step: 1. Does the part before ?. exist? 2. If yes, it continues 3. If not, it stops and returns undefined It skips the rest of the chain once something is missing. No errors. No drama ✅ 😀 A Simple Example const user = { name: "Ferdinand" }; console.log(user?.profile?.email); // undefined, no error In this case, since profile doesn't exist, JavaScript doesn't even try to check email. It just returns undefined safely. 🔥 When You Should Use It ✅ When working with API data ✅ When reading optional user input ✅ When you’re unsure if certain data exists ✅ When accessing settings or config data It makes your code shorter, cleaner, and safer. ⚠️ But watch out Optional chaining only stops on undefined or null. If a value is false, 0, or an empty string (""), it continues as normal. Also, don’t use it everywhere blindly. It can hide bugs if you're not sure what should or shouldn't be optional 🤨
To view or add a comment, sign in
-
-
💡 JavaScript Series | Topic 6 | Part 3 — Destructuring: Elegant Data Extraction 👇 Destructuring brought a more elegant, readable, and concise way to extract values from arrays and objects. It’s one of those features that once you start using — you’ll never want to go back. This concept is now fundamental in modern JavaScript, especially in React, Node.js, and API-driven applications. 🧩 Object Destructuring Instead of accessing properties through repetitive dot notation, destructuring lets you unpack exactly what you need — in one clean statement 👇 const user = { name: 'John', age: 30, address: { street: '123 Main St', city: 'Boston' } }; // Basic destructuring const { name, age } = user; // name = 'John', age = 30 // Nested destructuring const { address: { city } } = user; // city = 'Boston' // Renaming variables const { name: userName } = user; // userName = 'John' // Default values const { country = 'USA' } = user; // country = 'USA' (default used because country doesn’t exist) // Rest operator in destructuring const { name: firstName, ...rest } = user; /* firstName = 'John' rest = { age: 30, address: { street: '123 Main St', city: 'Boston' } } */ ⚙️ Why It Matters ✅ Cleaner syntax — eliminates repetitive code ✅ Fewer typos — no long property chains ✅ Safer code — supports defaults for missing values ✅ Easier debugging — extract only what you need 🧠 Real-World Use Cases 1️⃣ API Responses const response = await fetchUserData(); const { name, email, profile: { avatarUrl } } = response; 👉 Perfect for pulling nested API data directly. 2️⃣ React Props function UserCard({ name, age, city }) { return <div>{`${name} (${age}) - ${city}`}</div>; } 👉 Cleaner than writing props.name, props.age, etc. 3️⃣ Config or Env Objects const { PORT, NODE_ENV = 'development' } = process.env; 👉 Great for providing safe defaults in backend code. 💬 My Take: Destructuring makes your code simpler, faster, and safer. It’s not just syntax sugar — it’s a mindset for writing clear, maintainable, and declarative JavaScript. 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions, hands-on coding examples, and performance-driven frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #ES6 #Destructuring #WebDevelopment #ReactJS #NodeJS #NextJS #Coding #TypeScript #ModernJavaScript #InterviewPrep #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
Optional chaining is one of JavaScript's most useful features. But what's the performance impact? TL;DR it's massive. I recently collaborated with Simone Sanfratello on detailed benchmarks comparing noop functions to optional chaining, and the results were revealing: noop functions are 5.5x to 8.8x faster. Running 5 million iterations clearly showed the differences. Noop functions achieved 939M ops/sec as the baseline. Optional chaining with empty objects ran at 134M ops/sec (7x slower). Optional chaining with an existing method reached 149M ops/sec (6.3x slower). Deep optional chaining was the slowest, at 106M ops/sec (8.8x slower). The explanation comes down to what V8 must do. Noop functions are inlined by V8, making them essentially zero-overhead. The function call vanishes in optimized code. Optional chaining requires property lookup and null/undefined checks at runtime. V8 can't optimize these away because the checks must occur each time. This is why Fastify uses the abstract-logging module. Instead of checking logger?.info?.() throughout the code, Fastify provides a noop logger object with all logging methods as noop functions. The key is to provide noops upfront rather than checking for existence later. When logging is disabled, V8 inlines these noop functions at almost zero cost. With optional chaining, runtime checks are required every time. One reason for excessive optional chaining is TypeScript's type system encourages defensive coding. Properties are marked as potentially undefined even when runtime guarantees they exist, causing developers to add ?. everywhere to satisfy the type checker. The solution is better type modeling. Fix your interfaces to match reality, or use noop fallbacks like "const onRequest = config.hooks.onRequest || noop" and call it directly. Don't let TypeScript's cautious type system trick you into unnecessary defensive code. Context matters, though. Even "slow" optional chaining executes at 106+ million operations per second, which is negligible for most applications. Use optional chaining for external data or APIs where the structure isn't controlled, in normal business logic prioritizing readability and safety, and to reduce defensive clutter. Use noop functions in performance-critical paths, when code runs thousands of times per request, in high-frequency operations where every microsecond counts, and when you control the code and can guarantee function existence. Even a few thousand calls per request make the performance difference significant. My advice: don't optimize prematurely. Write your code with optional chaining where it enhances safety and clarity. For most applications, the safety benefits outweigh the performance costs. If profiling reveals a bottleneck, consider switching to noop functions. Profile first, optimize second. Remember: readable, maintainable code often surpasses micro-optimizations. But when those microseconds matter, now you understand the cost.
To view or add a comment, sign in
-
-
Ever struggled with managing async logic in JavaScript and felt like callbacks and promises just weren’t cutting it? Let me introduce you to an increasingly popular pattern: **Async Generators**. Async generators are like the cool versatile sibling of regular generators and async functions rolled into one. They allow you to yield promises over time, which means you can produce a stream of asynchronous values — ideal for things like reading large files chunk-by-chunk, lazy-loading data, or handling events where you don’t want to wait for everything before proceeding. Here’s a simple example to demonstrate: ```javascript async function* fetchDataInChunks(url) { const response = await fetch(url); const reader = response.body.getReader(); while(true) { const { done, value } = await reader.read(); if (done) break; yield new TextDecoder().decode(value); } } // Consuming the async generator (async () => { for await (const chunk of fetchDataInChunks('https://lnkd.in/g5V2Uq4w')) { console.log('Received chunk:', chunk); } })(); ``` What’s happening here? - The async generator function `fetchDataInChunks` reads a stream from a fetch response in chunks. - Each chunk is yielded as it arrives—without waiting for the entire file. - The consuming code uses `for await...of` to process each chunk asynchronously. Why should you care? - This pattern is becoming more relevant as web APIs push for streaming and real-time data handling. - It helps avoid loading big payloads entirely into memory, improving performance and user experiences. - It makes your async code cleaner and easier to reason about compared to nested callbacks or promise chaining. Bonus tip: Combine async generators with `AbortController` to cancel streaming operations gracefully — great for UIs where users might navigate away mid-download. Async generators are still a bit underutilized outside advanced use cases, but trust me, they’ll become a powerful tool in your JavaScript toolbox as streaming data becomes the norm. Give it a try next time you work with live data or streaming APIs! #JavaScript #AsyncProgramming #WebDevelopment #CodingTips #TechTrends #SoftwareEngineering #ModernJS #DeveloperExperience
To view or add a comment, sign in
-
⚙️ Writing Intentional JavaScript — Beyond the Syntax A mark of an experienced engineer is not just knowing what works, but why it behaves that way and when that behavior aligns with your intent. JavaScript’s flexibility is both a gift and a risk. The same expression can look simple yet carry subtle logic flows that aren’t immediately obvious. 🧩 Example 1: Understanding short-circuit evaluation const username = isReady && user.name || "Guest"; At a glance, many developers read this as: “If isReady is true, show user.name, otherwise show 'Guest'.” But that’s not how JavaScript evaluates it. Let’s unpack it: • The && operator has higher precedence than ||. • So the expression is grouped as: (isReady && user.name) || "Guest" • This means: • If isReady is falsy, the left side of && stops immediately → false || "Guest" → "Guest". • If isReady is truthy, it moves on to check user.name. • If user.name is also truthy, you get that value. • If user.name is falsy (like "", 0, or null), it still falls back to "Guest". So even though isReady is true, "Guest" may still print — which surprises many engineers who assume the first truthy condition guarantees the result. ✅ A clearer alternative when clarity is more valuable than brevity: const username = (isReady && user.name) ?? "Guest"; Or if need to check for falsy value then const username = (isReady && user.name) || "Guest"; The key isn’t to avoid these patterns, but to use them consciously, understanding their evaluation flow. 🧩 Example 2: The return-line break function getData() { return { name: "Aamir" } } This function returns undefined. Because of Automatic Semicolon Insertion (ASI), JavaScript interprets it as: return; { name: "Aamir" } ✅ Always return the object on the same line: function getData() { return { name: "Aamir" } } 🧠 The larger point JavaScript isn’t unpredictable — it’s precise. When we misread its operator precedence or parsing rules, we invite subtle bugs that the compiler won’t catch. As systems scale, understanding how the language evaluates expressions becomes more valuable than memorizing syntax patterns. That’s how we move from “it works” to “it’s intentional.” #JavaScript #EngineeringLeadership #TypeScript #SoftwareCraftsmanship #FrontendEngineering
To view or add a comment, sign in
-
🌈 DAY 58 – JavaScript Arrays (21 Must Know Methods) 🚀🔥 Today I practiced JavaScript ARRAY Methods in depth and this topic is super important for Frontend Interviews + Real Project Coding. Why Arrays Matter? Arrays are used in 👉 API Data | JSON Parsing | UI Rendering | Filters | Searching | Sorting | Analytics 💡 21 Array Methods I learned Today (with simple understanding) 1️⃣ push() – Add element at END Syntax: array.push(value) 2️⃣ pop() – Remove LAST element Syntax: array.pop() 3️⃣ unshift() – Add element at START Syntax: array.unshift(value) 4️⃣ shift() – Remove FIRST element Syntax: array.shift() 5️⃣ indexOf() – Find index of element (first match) Syntax: array.indexOf(value) 6️⃣ lastIndexOf() – Find last matched index Syntax: array.lastIndexOf(value) 7️⃣ includes() – Check exists or not Syntax: array.includes(value) 8️⃣ length – Get Array size Syntax: array.length 9️⃣ slice() – returns NEW array (original not changed) Syntax: array.slice(start,end) 🔟 splice() – Add / Remove / Replace inside original array Syntax: array.splice(start,deleteCount,item/s) 11️⃣ concat() – Merge arrays (original not changed) Syntax: array.concat(array2) 12️⃣ toString() – Convert array → comma string Syntax: array.toString() 13️⃣ join() – Join using custom symbol Syntax: array.join("-") 14️⃣ map() – Transform elements → NEW array Syntax: array.map((element)=>{ return value }) 15️⃣ find() – Returns First element that matches condition Syntax: array.find((item)=> condition) 16️⃣ findIndex() – Returns index of first match Syntax: array.findIndex((item)=> condition) 17️⃣ sort() – Sort ASC / DESC Syntax: array.sort((a,b)=> a-b) 18️⃣ reverse() – Reverse order Syntax: array.reverse() 19️⃣ copyWithin() – Copy values inside same array Syntax: array.copyWithin(target,start,end) 20️⃣ flat() – Flatten nested arrays Syntax: array.flat(depth) 21️⃣ new Array() – Create array using constructor Syntax: new Array(value) 📌 What I Realized Today Professional Developers don’t write loops everywhere… They use correct Array Method → Clean Code → Faster Development → Less Bugs ✅ Day 58 Completed 💯 Consistency → Growth → Skill Upgrade 📈🔥 special thanks to Harish M,Bhagavathula Srividya,Manivardhan Jakka,Spandana Chowdary,10000 Coders #javascript #webdevelopment #frontenddeveloper #techlearning #jsarrays #codingjourney #100daysofcode #dailycoding #softwaredeveloper #interviewpreparation #webdevcommunity #learningeveryday #linkedinfamily #programmerlife #careerbuilding
To view or add a comment, sign in
-
💡 JavaScript Series | Topic 2 | Part 3 — The Event Loop, Promises & Async/Await — The Real Concurrency Engine of JavaScript👇 If you’ve ever wondered how JavaScript handles multiple tasks at once even though it’s single-threaded — the secret lies in its Event Loop. 🌀 ⚙️ 1️⃣ JavaScript’s Single Threaded Nature JavaScript runs on one thread, executing code line by line — but it uses the event loop and callback queue to handle asynchronous tasks efficiently. console.log("Start"); setTimeout(() => console.log("Async Task"), 0); console.log("End"); 🧠 Output: Start End Async Task ✅ Even with 0ms, setTimeout goes to the callback queue, not blocking the main thread. 🔁 2️⃣ The Event Loop in Action Think of it as a traffic controller: The Call Stack runs your main code (synchronous tasks). The Callback Queue stores async tasks waiting to run. The Event Loop constantly checks: 👉 “Is the stack empty?” If yes, it moves queued tasks in. That’s how JS achieves non-blocking concurrency with a single thread! 🌈 3️⃣ Promises — The Async Foundation Promises represent a value that will exist in the future. They improve callback hell with a cleaner, chainable syntax. console.log("A"); Promise.resolve().then(() => console.log("B")); console.log("C"); 🧠 Output: A C B ✅ Promises go to the microtask queue, which has higher priority than normal callbacks. ⚡ 4️⃣ Async / Await — Synchronous Power, Asynchronous Core Async/Await is just syntactic sugar over Promises — it lets you write async code that looks synchronous. async function getData() { console.log("Fetching..."); const data = await Promise.resolve("✅ Done"); console.log(data); } getData(); console.log("After getData()"); 🧠 Output: Fetching... After getData() ✅ Done ✅ The await keyword pauses the function execution until the Promise resolves — but doesn’t block the main thread! 💥 5️⃣ Event Loop Priority When both microtasks (Promises) and macrotasks (setTimeout, setInterval) exist: 👉 Microtasks always run first. setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); 🧠 Output: Promise Timeout 🧠 Key Takeaways ✅ JavaScript runs single-threaded but handles async operations efficiently. ✅ The Event Loop enables concurrency via task queues. ✅ Promises and Async/Await simplify async code. ✅ Microtasks (Promises) have higher priority than Macrotasks (Timers). 💬 My Take: Understanding the Event Loop is what turns a JavaScript developer into a JavaScript engineer. 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions,hands-on coding examples, and performance-driven frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #WebDevelopment #AsyncProgramming #Promises #AsyncAwait #EventLoop #Coding #ReactJS #NodeJS #NextJS #WebPerformance #InterviewPrep #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
Types of Errors in JavaScript: * JavaScript is a powerful language, but even a small mistake can lead to unexpected errors. * Understanding these errors helps us debug faster and write cleaner code. Here are the 5 main types of errors in JavaScript: 1. Syntax Error Definition: * Occurs when the code is written incorrectly and JavaScript cannot understand it. * It happens before execution (during parsing). Example: console.log("Hello World" // Missing parenthesis Error Message: * Uncaught SyntaxError: missing ) after argument list Explanation: * JS expected a ) but didn’t find one. These are simple typos that break code instantly. 2. Reference Error Definition: * Occurs when trying to access a variable that doesn’t exist or is out of scope. Example: console.log(name); // name not defined Error Message: * Uncaught ReferenceError: name is not defined Explanation: * This means JS cannot find the variable in memory. * Always declare variables before using them! 3. Type Error Definition: * Occurs when a value is not of the expected type, or a property/method doesn’t exist on that type. Example: let num = 10; num.toUpperCase(); // Not valid on numbers Error Message: * Uncaught TypeError: num.toUpperCase is not a function Explanation: * Only strings can use .toUpperCase(). * TypeErrors often happen due to wrong variable usage. 4. Range Error Definition: Occurs when a number or value is outside its allowed range. Example: let arr = new Array(-5); // Negative length not allowed Error Message: * Uncaught RangeError: Invalid array length Explanation: * Array sizes must be non-negative. * You’ll see this error when loops, recursion, or array sizes go beyond limits. 5. URI Error Definition: * Occurs when using encodeURI() or decodeURI() incorrectly with invalid characters. Example: decodeURI("%"); // Invalid escape sequence Error Message: * Uncaught URIError: URI malformed Explanation: * URI (Uniform Resource Identifier) functions expect valid encoded URLs. * Always validate URLs before decoding! Conclusion * Errors are not your enemies—they’re your best teachers. * By understanding these core JavaScript errors, you’ll spend less time debugging and more time building awesome things. KGiSL MicroCollege #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #LearnToCode #JS #ErrorHandling #CodeNewbie #SoftwareEngineering #WebDesign #Developers #CodeTips #ProgrammingLife #CleanCode #WebApp #DeveloperCommunity #CodeDaily #BugFixing #JSDeveloper #TechCommunity #100DaysOfCode #WomenInTech #FullStackDeveloper #FrontendDeveloper #SoftwareDeveloper #CodingJourney #TechLearning #CodeBetter #TechEducation
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