Day 22/30 – Extend the Array Prototype in JavaScript Challenge 🧩 | Build array.last( ) 💻🚀 🧠 Problem: Enhance all arrays so that you can call: arr.last() Rules: Return the last element of the array If the array is empty → return -1 Assume array comes from JSON.parse() 🧠 Example : [1, 2, 3].last() // 3 [].last() // -1 💡 JavaScript Solution : Array.prototype.last = function() { if (this.length === 0) { return -1; } return this[this.length - 1]; }; 🔎 Why This Works Array.prototype lets us add methods to all arrays this refers to the current array instance this.length - 1 gives the last index Time Complexity: O(1) Space Complexity: O(1) ⚠️ Important Note In real production systems, modifying built-in prototypes is usually discouraged because it can: Cause conflicts Break third-party libraries Create unexpected behavior But for understanding JavaScript internals and interviews — this is GOLD 🔥 #JavaScript #30DaysOfJavaScript #CodingChallenge #Prototype #JSInternals #WebDevelopment #LearnToCode #Programming #DeveloperJourney #TechCommunity Extend Array prototype JavaScript JavaScript array last element JS prototype inheritance JavaScript interview questions Modify built-in objects JS Advanced JavaScript concepts
Extending Array Prototype in JavaScript
More Relevant Posts
-
💻 JavaScript Intermediate – Custom map() Function The map() method is widely used to transform arrays. Here’s how you can implement it manually. 📌 Problem: Apply a function to each element of an array and return a new array. function customMap(arr, callback) { let result = []; for (let i = 0; i < arr.length; i++) { result.push(callback(arr[i])); } return result; } let numbers = [1, 2, 3]; let doubled = customMap(numbers, function(num) { return num * 2; }); console.log(doubled); 📤 Output: [2, 4, 6] 📖 Explanation: • map() creates a new array by applying a function to each element. • Here, we manually implemented the same logic using a loop and callback. 💡 Tip: Understanding this helps you grasp how higher-order functions work in JavaScript. #JavaScript #Coding #WebDevelopment #FrontendDevelopment #LearnToCode #ProgrammingTips
To view or add a comment, sign in
-
-
Day-86 📘 Python Full Stack Journey – JavaScript Events & Dynamic Styling Today I learned how JavaScript events make web pages interactive by responding to user actions in real time. 🔁🖱️ 🎯 What I learned today: ⚡ JavaScript Events onclick — triggers a function when an element is clicked ondblclick — triggers on double-click onmouseover — triggers when the mouse moves over an element Example: onclick="fun()" 🎨 Dynamic Styling with JavaScript Changing styles directly using JavaScript: element.style.color = 'red' element.style.background = 'blue' This helped me understand how JavaScript can instantly modify the UI based on user interactions — a key concept for building responsive and interactive web applications. Really enjoying how JavaScript brings life to static HTML pages! 🚀 #JavaScript #PythonFullStack #WebDevelopment #Frontend #DOM #Events #UIUX #CodingJourney #LearningToCode #Upskilling #ContinuousLearning
To view or add a comment, sign in
-
-
Deep Dive into Strings & Date Today I explored some very important core concepts of JavaScript — Strings and Date objects. Here’s what I learned: 🔹 String Basics Different ways to create strings ("", '', template literals `${}`) String immutability (operations return new strings) length property 🔹 String Methods .toUpperCase() / .toLowerCase() .trim() for cleaning whitespace .split() to convert string → array .replace() & .replaceAll() .slice() and .substring() for extracting parts .indexOf(), .lastIndexOf(), .includes() for searching Understanding that strings are immutable really changed how I think about string manipulation. ⏳ JavaScript Date & Time Then I went deeper into how JavaScript handles time: new Date() .toString() vs .toLocaleString() .getDay(), .getDate(), .getMonth() (0-based indexing ⚠️) Date.now() → milliseconds since 1 Jan 1970 (Unix Epoch) But the most interesting part 👇 💡 How JavaScript Gets Time JavaScript doesn’t generate time itself. It takes time from the Operating System, which gets it from: 🧠 Real-Time Clock (RTC) on the motherboard 🔋 CMOS battery (keeps time even when system is off) ⚡ CPU Clock (high-speed internal counter) Understanding the difference between: Physical CPU Clock Real-Time Clock OS System Clock …gave me clarity on how time actually works inside a computer. The more I learn JavaScript internals, the more I realize how deeply connected software is with hardware. Consistency > Motivation 💪 Still learning. Still building. #JavaScript #WebDevelopment #JSInternals #LearningInPublic #100DaysOfCode #DSA #Frontend CoderArmy
To view or add a comment, sign in
-
-
🚀 Day 86 of My #100DaysOfCode Challenge Today I discovered a lesser-known feature in JavaScript — Symbols. Most developers work with object keys using strings, but JavaScript also provides another unique type called Symbol. A Symbol creates a unique and hidden property key that cannot accidentally conflict with other keys. Example const id = Symbol("id"); const user = { name: "Tejal", [id]: 12345 }; console.log(user.name); // Tejal console.log(user[id]); // 12345 Why Symbols are interesting • Every Symbol is unique • Helps create hidden object properties • Prevents accidental property overwriting • Often used internally in libraries and frameworks Even if two symbols have the same description, they are still different. const a = Symbol("key"); const b = Symbol("key"); console.log(a === b); // false Learning about features like Symbols helps me understand how JavaScript works behind the scenes and how large applications manage object data safely. Exploring deeper concepts every day. 💻✨ #Day86 #100DaysOfCode #JavaScript #WebDevelopment #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
-
🚀 JavaScript Concepts Series – Day 6 / 30 📌 Closures in JavaScript 👀 Let’s Revise the Basics 🧐 A closure is when a function remembers variables from its outer scope even after the outer function has finished execution. 🔹 Key Points • Inner function can access outer variables • Data persists even after function execution • Useful for data privacy and state management 🔹 Example function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 💡 Key Insight Closure → Function + its lexical scope Remembers → Outer variables after execution Closures are widely used in callbacks, event handlers, and React hooks. More JavaScript concepts coming soon. 🚀 #javascript #js #webdevelopment #frontenddeveloper #coding #programming #developers #softwaredeveloper #learnjavascript #javascriptdeveloper #codinglife #devcommunity #webdev #reactjs #mernstack #codingjourney #codeeveryday #developerlife #100daysofcode #techlearning
To view or add a comment, sign in
-
-
🧠 **What will be the output of the following JavaScript code?** ### 🔹 Snippet 1 ```js let x = 1; { let x = 2; } console.log(x); ``` ### 🔹 Snippet 2 ```js var x = 1; { var x = 2; } console.log(x); ``` --- ### ✅ Correct Answer: 👉 **1, 2** --- ### 💡 Why? 🔵 **`let` is block-scoped** In Snippet 1: * `let x = 2` exists only inside the block `{ }` * It does NOT affect the outer `x` * So `console.log(x)` prints → **1** --- 🟠 **`var` is function-scoped** In Snippet 2: * `var x = 2` overrides the same variable * `var` ignores block scope * So `console.log(x)` prints → **2** --- ### 🚀 Key Takeaway: ✔ `let` → Block scoped ✔ `var` → Function scoped ✔ Always prefer `let` and `const` in modern JavaScript --- 🎯 This is one of the most common JavaScript interview traps. Would you have answered it correctly? 👇 #JavaScript #FrontendDevelopment #WebDevelopment #CodingInterview #JSConcepts #Programming #SoftwareEngineering #DeveloperLife #LearnToCode #TechCommunity #FullStackDeveloper #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Arrays are NOT real arrays in JavaScript. That was one of the most interesting things I learned today while studying Arrays in JavaScript. At first, arrays seem simple — just a collection of elements. But under the hood, JavaScript arrays are actually objects with special behavior, not fixed-size contiguous memory structures like in languages such as C++. What I learned about Arrays: • Arrays in JavaScript are mutable • They can store multiple data types • They are dynamic in size Key operations I practiced: • Adding/removing elements → push(), pop(), shift(), unshift() • Looping → classic for loop and modern iteration methods • Searching → indexOf(), lastIndexOf(), includes() • Manipulation → slice(), splice() • Conversion → join() (array → string) • Spread operator → modern and powerful way to copy/merge arrays One important insight: The sort() method can behave unexpectedly with numbers because it sorts values as strings by default. Example: [10, 2, 5].sort() // Output -> [10, 2, 5] To sort numbers correctly, we need a comparison function. To summarize everything, I created a detailed carousel Notes (Notes given by Rohit Negi). Course Instructor: Rohit Negi | Youtube Channel: Coder Army #JavaScript #WebDevelopment #LearningJourney #BuildInPublic #FrontendDevelopment #Fullstackdevelopment #Coding
To view or add a comment, sign in
-
Today I explored one of the most confusing but fascinating concepts in JavaScript — The Event Loop. JavaScript is single-threaded, but it still handles asynchronous tasks like API calls, timers, and promises smoothly. The magic behind this is the Event Loop. Here’s the simple flow: 1️⃣ Call Stack – Executes synchronous code 2️⃣ Web APIs – Handles async tasks (setTimeout, fetch, DOM events) 3️⃣ Callback Queue / Microtask Queue – Stores callbacks waiting to execute 4️⃣ Event Loop – Moves tasks to the call stack when it’s empty 💡 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 🧠 Output: Start End Promise Timeout Why? Because Promises go to the Microtask Queue which runs before the Callback Queue. ✨ Learning this helped me finally understand how JavaScript manages async behavior without multi-threading. Tomorrow I plan to explore another interesting JavaScript concept! Devendra Dhote Ritik Rajput #javascript #webdevelopment #frontenddeveloper #100DaysOfCode #learninginpublic #codingjourney #sheryianscodingschool
To view or add a comment, sign in
-
🚀 **Scope in JavaScript (Every Developer Must Understand This)** Scope determines **where a variable is accessible** in your code. If you don’t understand scope, you’ll eventually face unexpected bugs. Let’s break it down 👇 --- ## 🌍 1️⃣ Global Scope Variables declared outside any function are accessible everywhere. ```js let name = "Abhishek"; function greet() { console.log(name); } ``` ✔ Accessible inside functions ✔ Accessible across the file --- ## 🧠 2️⃣ Function Scope (`var`) `var` is function-scoped. ```js function test() { var message = "Hello"; } console.log(message); // ❌ Error ``` It exists only inside the function. --- ## 📦 3️⃣ Block Scope (`let` / `const`) `let` and `const` are block-scoped. ```js if (true) { let age = 25; } console.log(age); // ❌ Error ``` Accessible only inside `{ }` --- ## ⚠ Common Mistake with `var` ```js if (true) { var age = 25; } console.log(age); // 25 😱 ``` Why? Because `var` ignores block scope and leaks outside the block. --- ## 🎯 Best Practice ✅ Use `const` by default ✅ Use `let` when value needs to change ❌ Avoid `var` in modern JavaScript --- Mastering scope makes you stronger in: ✔ Closures ✔ Event Loop ✔ Asynchronous JavaScript ✔ Interviews --- 💬 What should I explain next? 1️⃣ Closures 2️⃣ Event Loop #JavaScript #FrontendDevelopment #WebDevelopment #Programming #CodingInterview #JSConcepts #SoftwareEngineering #FullStackDeveloper #LearnToCode #DeveloperTips #100DaysOfCode #TechCommunity
To view or add a comment, sign in
-
-
💡 Today I Learned About JavaScript Closures One interesting concept in JavaScript that often appears in interviews is Closures. A closure happens when a function remembers and can access variables from its outer scope, even after the outer function has finished executing. In simple terms: A function “closes over” the variables around it. 🔎 Example: function outerFunction() { let count = 0; function innerFunction() { count++; console.log(count); } return innerFunction; } const counter = outerFunction(); counter(); // 1 counter(); // 2 counter(); // 3 📌 Why does this work? Even though outerFunction() has finished executing, the innerFunction() still remembers the count variable from its lexical scope. This is the power of closures. 🚀 Real-world use cases: ✔ Data privacy and encapsulation ✔ Creating private variables ✔ Function factories ✔ Event handlers and callbacks Closures are a fundamental part of how JavaScript works, and understanding them helps in writing more efficient and maintainable code. Still learning JavaScript deeply as part of my frontend development journey. #JavaScript #FrontendDeveloper #WebDevelopment #LearningInPublic #MERNStack
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