Stop over-complicating small file uploads! I recently worked on a feature where I needed to handle image uploads in a React + Formik environment. Instead of setting up a complex form-data flow for a simple product image, I went with Base64 encoding. Why Base64? It converts your image file into a string, making it super easy to send as a standard JSON field to your backend. No extra headers, no complex file handling—just a clean string! The Technical Snippet: Using the FileReader API, I created a simple utility to convert the File object into a Base64 string during the form submission. JavaScript const base64 = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); What I implemented: Instant Previews: Used URL.createObjectURL for lightning-fast UI feedback. Formik Integration: Seamlessly synced the file state with Formik's validation schema. Clean API Payloads: Sent the image as part of a single JSON object. It’s not always the best solution for large files (due to the ~33% size increase), but for small assets and quick MVPs, it’s a total game-changer for developer productivity! SourceCode:https://lnkd.in/g6uDcSiM #ReactJS #WebDevelopment #Frontend #Formik #TypeScript #CodingTips #JavaScript #NextJS
More Relevant Posts
-
A tale of two JavaScript patterns and the bugs that catch you out 🐛 I've been revisiting the two main ways to create custom objects in JavaScript. Both achieve the same goal. Both have traps. Here's what I found: ES6 Class class Character { constructor(name) { this.name = name this.powers = [] } addPowers(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Methods live outside the constructor, inside the class body. They land on the prototype automatically so every instance shares one copy rather than each carrying its own. Constructor Function function Character(name) { this.name = name this.powers = [] this.addPowers = function(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Easy gotcha: write function addPowers() instead of this.addPowers = and the method becomes a private inner function completely invisible outside the constructor. Your code won't error on creation, it'll just silently fail when you try to call it. The class syntax is cleaner and harder to get wrong. But understanding constructor functions teaches you what's actually happening under the hood and makes legacy codebases far less scary. Worth noting: there is a third way Object.create() but I've not covered it here. It gives you very fine-grained control over the prototype chain, but it's significantly more verbose and rarely the first tool you'd reach for. Both patterns. Both worth knowing. Have you been caught out by either of these? Let me know below 👇 #JavaScript #WebDevelopment #CodingTips #OOP #LearnToCode #JSDevs #SoftwareEngineering
To view or add a comment, sign in
-
Stop copying arrays manually just to sort them. 🛑 For years, we’ve used the spread syntax hack [...items].sort() because the original .sort() mutates the source array. In 2026, this feels like an anachronism. THE EVOLUTION OF IMMUTABILITY: 📍 The 2020 way (Boilerplate): const sorted = [...users].sort((a, b) => a.name.localeCompare(b.name)); const reversed = [...sorted].reverse(); 📍 The 2026 way (Clean & Declarative): const sorted = users.toSorted((a, b) => a.name.localeCompare(b.name)); const reversed = sorted.toReversed(); WHY IT MATTERS: 🔹 No Side Effects: You no longer risk accidentally mutating state in Angular, Vue, React, or any other framework. 🔹 Method Chaining: You can now chain .toSorted().toReversed().filter() without worrying about data integrity at each step. 🔹 Readability: The method name immediately signals your intent: "I am creating a new array, not modifying the original one." Small refactorings like switching to .toSorted() are the quickest way to make a codebase feel modern and resilient. If the platform gives you a specialized tool for immutability, it's time to retire the spread hacks. Have toSorted and toReversed become your new standard, or do you still write [...spread] out of habit? Let’s discuss! 👇 #JavaScript #WebDevelopment #CleanCode #TypeScript #Frontend #CodingTips #ECMAScript #SoftwareEngineering
To view or add a comment, sign in
-
-
Yesterday I broke down V8 and libuv, the first two pillars of Node.js.If you missed it, go read that first. Today we close the loop with the third pillar and a benchmark that makes everything click. Still with me? Good. Let us open the black box. PILLAR 3: C++ Bindings — The Bridge Between Your JS and the Machine When you write const fs = require('fs'), you are not loading a JavaScript file. You are loading a JavaScript interface wired directly into C++ code.Here is the full journey of a single fs.readFile() call: Your JS calls readFile Node's core module drops into C++ via the bindings C++ prepares the request and hands it to libuv. libuv sends it to a worker thread in the thread pool Your JavaScript keeps running. Zero waiting. The worker thread reads the file from disk It notifies libuv when done libuv queues the result for the event loop On the next loop tick your callback fires with the data That entire chain happens in milliseconds. And while it is running your server has already started handling new incoming requests. Now here is the number that makes all three pillars make sense together. Two servers. 10 concurrent requests. Each takes 2 seconds to complete. Blocking server: handles them one by one. Total time: 20 seconds. Node.js server: accepts all 10 instantly, finishes all 10 together. Total time: 2 seconds. Same hardware. Same workload. 10x faster. One thread. That is V8 compiling your code fast, libuv handling the async work, and C++ bindings connecting the two. All three working together. And this is exactly why the golden rule of Node.js exists. Never block the event loop. The moment your main thread gets stuck on heavy synchronous work, that 2 second result becomes 20 seconds again. Every advantage disappears instantly. Now you understand the architecture. Tomorrow I will show you what happens when you trust that architecture too blindly, and the day 11 lines of code broke the entire JavaScript ecosystem. Follow so you do not miss it. #NodeJS #JavaScript #WebDevelopment #Backend #SoftwareEngineering #Programming #TechEducation
To view or add a comment, sign in
-
💡 JavaScript Tip: || vs ?? Many developers use || to set default values in JavaScript. But this can silently introduce bugs. Example: console.log(false || "temp"); // "temp" console.log(null || "temp"); // "temp" console.log(undefined || "temp"); // "temp" Why? Because || treats ANY falsy value as missing: false, 0, "", null, undefined, NaN Now look at the Nullish Coalescing operator (??): console.log(null ?? "temp"); // "temp" console.log(undefined ?? "temp"); // "temp" console.log(false ?? "temp"); // false ?? only replaces: null and undefined. Real example: let count = 0; console.log(count || 10); // 10 ❌ console.log(count ?? 10); // 0 ✅ ✔ Use || when you want to replace all falsy values ✔ Use ?? when you only want to replace null or undefined Small operator — but it can prevent real bugs in production. Do you usually use || or ?? for defaults? 🤔 #JavaScript #WebDevelopment #Frontend #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
Method: Array.from() In JavaScript, Array.from() is one of the most underrated yet powerful methods that can make code cleaner, smarter, and more efficient. What is Array.from()? In simple words, Array.from() is a built-in JavaScript method that creates a new array from: ✅ Arrays ✅Array-like objects (like arguments or NodeList) ✅ Iterable objects like Maps and Sets Basic Syntax: Array.from(arrayLike, mapFunction) Example 1: const str = 'Hello' const array = Array.from(str) console.log(array); output: ['H', 'e', 'l', 'l', 'o '] Example 2: const numbers = [1, 2, 3, 4] const result = Array.from(numbers, number => number * 2) console.log(result); output: [2, 4, 6, 8] Example 2: const nums = Array.from({ length:10 },(value, i )=> i + 1) console.log(nums); output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #120DaysOfCode #JavaScript #WebDevelopment #Networking #API #JSON #AsyncAwait #FullStackDeveloper #MERNStackDeveloper #ReactDeveloper #BackendEngineer
To view or add a comment, sign in
-
-
🔥 I ran 1,000,000 JavaScript lookups to finally settle: Object vs Map. The result shocked me. Every JavaScript dev uses {} by default. It's natural. It's everywhere. Nobody questions it. So I built a benchmark. Real browser. No shortcuts. JIT-warmed for fairness. Here are the actual numbers 👇 📊 Dataset: 10,000 keys | 1M lookups | 5 runs averaged Plain Object → 16.86ms → ~59,311,981 ops/sec Map → 14.28ms → ~70,028,011 ops/sec ✅ WINNER Map was 18.1% faster. Consistently. Every single run. 🤯 Map handles 10.7 MILLION more lookups per second. That's not a rounding error. That's a real-world performance gap. Here's WHY most devs never knew this 👇 → Map uses a dedicated hash table built for frequent lookups → Plain Object must deal with prototype chain overhead on every access → With 10K+ unique random keys, V8 can't build stable Hidden Classes for Object → V8 falls Object into slow "dictionary mode" — Map stays consistently fast → Map also wins on memory for large, dynamic key sets But here's the NUANCE nobody talks about: ✅ Object can still win on tiny, stable, predictable key sets (<100 keys) ✅ Map wins the moment your data is dynamic, large, or frequently mutated ✅ Map is ALWAYS safer — no prototype key collision risk (no accidental toString / constructor keys) The real takeaway? If you're building caches, frequency tables, lookup maps, or any dynamic key-value store in JavaScript — stop defaulting to Object. Use Map. The 18.1% speed boost is just the beginning. 💬 Drop a comment: Are you using Map in production yet? ♻️ Repost if this would help someone on your team write faster JS. 🔔 Follow me for weekly JavaScript performance deep-dives. #JavaScript #WebDevelopment #FrontendDevelopment #JavaScriptTips #SoftwareEngineering #NodeJS #Programming #WebPerformance #100DaysOfCode #CodeNewbie #TechCommunity #CleanCode #Developer #Coding #JSPerformance #V8Engine #DataStructures #OpenSource #FullStackDevelopment #TechTwitter #codewithramkumar
To view or add a comment, sign in
-
-
Day 62 of me reading random and basic but important dev topicsss..... Today I read about the Resource Loading in JavaScript...... In our day-to-day work building interfaces with React or other modern frameworks, it's easy to take module bundlers for granted. But what happens when we need to dynamically inject a third-party script......like an analytics tracker, a payment SDK, or a support widget.....on the fly? Understanding the vanilla DOM events onload and onerror is a must for any robust front-end architecture. 1. The Dynamic Injection Adding a script dynamically is straightforward: let script = document.createElement('script'); script.src = "third-party.js"; document.head.append(script); But we can't just invoke its functions immediately. The browser needs time to fetch and execute it. 2. script.onload (The Success Path) This event triggers after the script has successfully loaded and executed. This is our green light to safely use the newly available variables or functions. 3. script.onerror (The Failure Path) If the script 404s or the server is down, onerror catches it. However, keep in mind: we won't get HTTP status codes (like 404 or 500) here, just a notification that the network request failed. Loading vs. Execution Here is where we get tripped up: onload and onerror only track the network loading phase. If a script downloads successfully but contains a syntax or runtime error during execution, onload will still fire! To catch those internal execution bugs, we need a different tool entirely: the window.onerror global handler. Keep Learning!!!!! #JavaScript #WebDevelopment #FrontendDev #React #SoftwareEngineering
To view or add a comment, sign in
-
-
📊 Day 13 – Poll Answer & Explanation ```javascript const a = [1, 2, 3]; const b = a; b.push(4); console.log(a); console.log(b); ``` ### ❓ What will be the output? ## ✅ Correct Answer: **B** ``` [1,2,3,4] [1,2,3,4] ``` --- ## 📌 Step-by-Step Explanation **1️⃣ Arrays are Reference Types** In **JavaScript**, arrays are **objects**. Objects are stored in **memory by reference**, not by value. --- **2️⃣ Assigning `b = a`** ```javascript const b = a; ``` This **does NOT create a new array**. Instead, **both `a` and `b` point to the same array in memory**. ``` a ──► [1,2,3] b ──► ``` --- **3️⃣ Modifying the Array** ```javascript b.push(4); ``` Since **`b` references the same array**, the original array is modified. ``` a ──► [1,2,3,4] b ──► ``` --- **4️⃣ Final Output** ```javascript console.log(a); // [1,2,3,4] console.log(b); // [1,2,3,4] ``` Both variables print the **same updated array**. --- ## 💡 Key Takeaway 👉 **Arrays and objects in JavaScript are stored by reference.** 👉 If multiple variables reference the **same object**, modifying one **affects all of them**. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode
To view or add a comment, sign in
-
🚀 **JavaScript: var vs let vs const (Every Developer Should Know This)** Understanding the difference between `var`, `let`, and `const` is one of the most important fundamentals in JavaScript. Let’s simplify it 👇 --- 🔴 **var** • Function scoped • Can be **reassigned** • Can be **redeclared** • Hoisted and initialized as `undefined` ```javascript var x = 10; x = 20; // ✅ allowed var x = 30; // ✅ allowed ``` ⚠️ Old JavaScript way. Avoid using `var` in modern code. --- 🟢 **let** • Block scoped `{ }` • Can be **reassigned** • ❌ Cannot be redeclared in the same scope • Hoisted but in **Temporal Dead Zone (TDZ)** ```javascript let y = 10; y = 20; // ✅ allowed let y = 30; // ❌ Error ``` ✔ Best for variables that will change. --- 🟣 **const** • Block scoped • ❌ Cannot be reassigned • ❌ Cannot be redeclared • Hoisted with **Temporal Dead Zone** ```javascript const z = 10; z = 20; // ❌ Error ``` ✔ Best for constants. --- 🎯 **Best Practice** ✔ Use **const by default** ✔ Use **let when value changes** ❌ Avoid **var** This makes your code **cleaner, safer, and predictable.** --- 💬 Interview Question: What is **Temporal Dead Zone (TDZ)** in JavaScript? Comment your answer 👇 --- #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #SoftwareEngineering #LearnToCode #DeveloperTips #JS #TechCommunity
To view or add a comment, sign in
-
-
But I can still change const even though it is immutable, Const a = [] a.push(7) Above code is completely valid. Can anyone explain that .. comment below 👇
Immediate Joiner - Software Developer | Full Stack Web Developer | NODE JS | REACT JS | PHP | JS | GITHUB | PYTHON | DJANGO | REST API | MYSQL | MONGO DB | FLASK | WORDPRESS
🚀 **JavaScript: var vs let vs const (Every Developer Should Know This)** Understanding the difference between `var`, `let`, and `const` is one of the most important fundamentals in JavaScript. Let’s simplify it 👇 --- 🔴 **var** • Function scoped • Can be **reassigned** • Can be **redeclared** • Hoisted and initialized as `undefined` ```javascript var x = 10; x = 20; // ✅ allowed var x = 30; // ✅ allowed ``` ⚠️ Old JavaScript way. Avoid using `var` in modern code. --- 🟢 **let** • Block scoped `{ }` • Can be **reassigned** • ❌ Cannot be redeclared in the same scope • Hoisted but in **Temporal Dead Zone (TDZ)** ```javascript let y = 10; y = 20; // ✅ allowed let y = 30; // ❌ Error ``` ✔ Best for variables that will change. --- 🟣 **const** • Block scoped • ❌ Cannot be reassigned • ❌ Cannot be redeclared • Hoisted with **Temporal Dead Zone** ```javascript const z = 10; z = 20; // ❌ Error ``` ✔ Best for constants. --- 🎯 **Best Practice** ✔ Use **const by default** ✔ Use **let when value changes** ❌ Avoid **var** This makes your code **cleaner, safer, and predictable.** --- 💬 Interview Question: What is **Temporal Dead Zone (TDZ)** in JavaScript? Comment your answer 👇 --- #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #SoftwareEngineering #LearnToCode #DeveloperTips #JS #TechCommunity
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
How do you usually handle image uploads in your React apps? Are you Team Base64 or Team Multipart? Let’s discuss!