Some browsers cache aggressively. ✅ Fix fetch(url, { method: ‘POST’, cache: ‘no-store’ }); Especially important for forms authentication dynamic APIs
Category: JavaScript
JS Memory Leaks — Forgotten Event Listeners
Single-page apps suffer badly from this. ❌ window.addEventListener(‘resize’, handler); ✅ window.removeEventListener(‘resize’, handler); Always clean up listeners on unmount or destroy.
AJAX Requests Fail Randomly? CSRF Token Missing
POST requests fail silently without CSRF token. ✅ Fix headers: { ‘X-CSRF-TOKEN’: token } Common victims Laravel Django ASP.NET MVC
JS “await” Inside forEach Is a Bug
This does NOT work: items.forEach(async item => { await process(item); }); ✅ Correct Patterns for (const item of items) { await process(item); } or parallel: await Promise.all(items.map(process));
JS “Object Mutation Side Effects” — The Hidden Reference Bug
const a = { x: 5 }; const b = a; b.x = 999; Now a.x is also 999.This breaks apps everywhere. ✔ Fix: Clone before modifying const b = structuredClone(a); or: const b = { …a };
AJAX “POST Works Locally but Not in Production” — HTTPS Mixed Content
Local: HTTPProd: HTTPSBrowser blocks insecure AJAX calls with no error. ✔ Fix Always use relative URLs: $.post(‘/api/users’, data); Avoid: $.post(‘http://localhost/api/users’, data); // ❌
JS “setInterval Drift” — Why Your Timers Run Slower Over Time
setInterval accumulates drift because execution time is included. ✔ Fix: Self-adjusting timer const start = Date.now(); let count = 0; function tick() { count++; const next = start + count * 1000; setTimeout(tick, next – Date.now()); } tick(); Accurate to the millisecond.
AJAX “POST Suddenly Fails” — The Missing Content-Type Header
Many backends reject requests silently. ✔ Fix: $.ajax({ method: “POST”, url: “/api/data”, contentType: “application/json”, data: JSON.stringify({ id: 1 }) }); Missing contentType = backend can’t parse payload.
JS “Undefined Errors in Loops” — The Closure Trap
Typical bug: for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), 100); } Output: 5 5 5 5 5 Because var is function-scoped. ✔ Fix for (let i = 0; i < 5; i++) { setTimeout(() => console.log(i), 100); } Or: setTimeout(((x)=>()=>console.log(x))(i), 100);
AJAX “Stale Data” — Browser Caching GET Requests Deeply
Even server changes don’t update responses. ✔ Fix $.ajax({ url: “/api/data”, cache: false }); or fetch: fetch(“/api/data”, { cache: “no-store” }); Instantly fixes “old response stuck” issue.
JS “Unexpected NaN” — The Invisible Type Coercion Trap
Common bug: “5” – “2” // works => 3 “5” + “2” // ’52’ “5” * “hi” // NaN JS coerces AND behaves inconsistently. ✔ Life-Saving Fix Always convert: Number(value) or parseInt(value, 10) 💡 Bonus Trap parseInt(“08”) returns 8 but “08” == 8 is true → chaos.
AJAX Cache Nightmare — Why Your GET Requests Don’t Update
Browsers cache GET requests aggressively. ✔ Life-Saving Fix $.ajax({ url: ‘/api/data’, cache: false }); Under the hood, jQuery adds:?_={timestamp} → bypasses cache. 💡 If using fetch: fetch(‘/api/data’, { cache: ‘no-store’ });
JS “Debounce vs Throttle” — Why Your Search Bar Lags
Real problem:Search inputs trigger too many backend calls. ✔ Debounce (use for search) function debounce(fn, delay){ let timeout; return (…args)=>{ clearTimeout(timeout); timeout = setTimeout(()=>fn(…args), delay); }; } ✔ Throttle (use for scroll/resize) function throttle(fn, delay){ let last = 0; return (…args)=>{ const now = Date.now(); if(now – last >= delay){ last = now; fn(…args); } […]
JavaScript Event Loop Misconceptions — Why setTimeout(fn, 0) Is NOT Instant
Many devs think: setTimeout(() => console.log(“hi”), 0); runs immediately. It does NOT. 🔍 Why? It is put into the task queue, which only runs after: microtasks (Promise callbacks) current call stack render steps Example Promise.resolve().then(() => console.log(“promise”)); setTimeout(() => console.log(“timeout”), 0); // Output: // promise // timeout 💡 Why This Matters Debugging race conditions Handling […]
Service Workers — Offline-First Apps Made Easy
Service Workers let your site work offline, cache assets, and load instantly. navigator.serviceWorker.register(‘/service-worker.js’); ✨ What You Get ⚡ Near-instant load time 📦 Cached static assets 📡 Offline browsing 🔋 Reduced server load 💡 Combine with “cache-first” strategies for ultimate speed.
Debounce vs Throttle — The UI Performance Problem Everyone Gets Wrong
🎯 Debounce Trigger after user stops typing. Great for: Search boxes Auto-suggest Validation 🌀 Throttle Trigger every X ms, no matter what. Great for: Scroll events Resize events Mouse move Quick Example const debounced = debounce(fn, 300); const throttled = throttle(fn, 200); 💡 Using the wrong one leads to janky UI & wasted CPU.
JavaScript Web Workers — Real Multithreading for Heavy Tasks
Web Workers allow JS to run CPU-heavy tasks off the main thread. const worker = new Worker(“worker.js”); worker.postMessage({ action: “process” }); 💥 Why Use Them 🧵 Prevent UI blocking 🚀 Faster data processing 📸 Smooth animations 🧩 Perfect for image, crypto & data tasks
How to format date in Javascript
function formatDate(date) { var d = new Date(date), month = ” + (d.getMonth() + 1), day = ” + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = ‘0’ + month; if (day.length < 2) day = ‘0’ + day; return [day, month, year].join(‘.’); } OUTPUT: 19.05.2024 NOTE: If you make the return like […]
How to change star rating color on mouseover/out, mouseenter/leave with Javascript
function onMouseEnter(index){ var star = document.getElementsByClassName(“starClass”); var j; for(j = 0; j < fa.length; j++){ if(j < index){ star[j].style.color = “orange”; } else{ star[j].style.color = “#ccc”; } } } function onMouseOut(){ var star = document.getElementsByClassName(“starClass”); var k; for(k = 0; k < fa.length; k++){ star[k].style.color = “#ccc”; } }
How to disable ASP.Net button after click to prevent double clicking
Let’s say you have 2 buttons on your web page. <form id=”form1″ runat=”server”> <asp:Button ID=”Button1″ runat=”server” Text=”Button1″ OnClick=”Button1_Clicked” /> <asp:Button ID=”Button2″ runat=”server” Text=”Button2″ /> </form> Scenario 1: Disabling the specific button <script type=”text/javascript”> function DisableButton() { document.getElementById(“<%=Button1.ClientID %>”).disabled = true; } window.onbeforeunload = DisableButton; </script> The DisableButton JavaScript function is used for disabling specific Button when Clicked. […]
How to use client-side function on checkbox or any asp.net component
Here is the Asp part: <label for=”chkCondition”> <asp:CheckBox ID=”chkCondition” Text=”Should i show the div?” runat=”server” onclick=”ShowHideDiv(this)” /> </label> <hr /> <div id=”divToShowOrHide” style=”display: none”> this div will be shown regarding the checkbox checked status. <asp:TextBox ID=”myTextBox” runat=”server” /> </div> And here is the Javascript part: <script type=”text/javascript”> function ShowHideDiv(chkCondition) { var divToShowOrHide = document.getElementById(“divToShowOrHide”); divToShowOrHide.style.display […]
How to remove searching, filtering, ordering and info from Asp.NET MVC Datatable
var table = $(“#datatable”).DataTable({ “paging”: false, “ordering”: false, “searching”: false, “info”: false });
How to get session value in Javascript
<script> let mySession = ‘<%= Session[“SessionName”].ToString() %>’; //use your session … console.log(mySession); alert(mySession); </script>
Search text through Divs in Javascript
<table align=”center” width=”20%”> <tr> <td style=”padding-right: 10px”> <input type=”text” id=”Search” onkeyup=”myFunction()” placeholder=”Please enter a search term..” title=”Type in a name”> </td> </tr> </table> <br> <div class=”target”> This is my DIV element. </div> <div class=”target”> This is another Div element. </div> <div class=”target”> Can you find me? </div> <script> function myFunction() { var input = document.getElementById(“Search”); […]
How replace characters with asterisks (*) except first characters
const theName = “Vincent van Gogh”; function hideWord(word) { if (word.length < 2) return word; return word.substring(0, 1) + ‘*’.repeat(word.length-1); } console.log(theName.split(” “).map(hideWord).join(” “)); OUTPUT: V****** v** G*** You could also wrap the whole lot in a function if you wanted to be able to call it from multiple places and avoid redefining it. function […]
Smart way to truncate long strings in Javascript
Let’s say we want to truncate long strings (length > 250): short = long.replace(/(.{250})..+/, “$1…”); or short = long.replace(/(.{250})..+/, “$1…”);
Populating Javascript array with Model in ASP.Net MVC Razor
We just need to loop through the razor collection to populate the Javascript array as below: @foreach (var item in Model) { @:$(function () { @:$(“#map”).googleMap(); @:$(“#map”).addMarker({ @:coords:[@item.Latitude], @:title: `@item.City, @item.District`, @:text: `@item.Address` @:}); @:}); }
Pass model from Razor view to JavaScript
Let’s say you send a model called “MyModel” from controller to view. In Controller: … var result = new MyModel() { Id = 1, Name = “Ercan”, FavoriteTeam = “Galatasaray”, FavoriteGame = “Half Life Series” } return View(result); … and now we will send this model which comes with result to Javascript via setName function: […]
Add and Remove classes from element in Javascript
classList is pretty smart and the most modern system of manipulating CSS class names in elements via JavaScript. Adding class name: const element = document.getElementById(‘txtMyText’); element.classList.add(‘myClass’); Removing class name: const element = document.getElementById(‘txtMyText’); element.classList.remove(‘myClass’); Removing multiple class names: const element = document.getElementById(‘txtMyText’); element.classList.remove(‘myClass1’, ‘myClass2’) Thanks to clubmate.fi
Split and Join in Javascript
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method’s call. Syntax split() split(separator) split(separator, limit) Return value An Array of strings, split at each point where the separator occurs […]


