CINXE.COM
javascript - Stack Abuse
<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>javascript - Stack Abuse</title><link rel="canonical" href="https://stackabuse.com/tag/javascript/"/><meta property="og:url" content="https://stackabuse.com/tag/javascript/"/><meta name="twitter:url" content="https://stackabuse.com/tag/javascript/"/><link rel="next" href="https://stackabuse.com/tag/javascript/page/2/"/><meta property="og:site_name" content="Stack Abuse"/><meta property="og:type" content="website"/><meta property="og:title" content="javascript - Stack Abuse"/><meta name="twitter:card" content="summary"/><meta name="twitter:title" content="javascript - Stack Abuse"/><meta name="twitter:site" content="@StackAbuse"/><script type="application/ld+json">{ "@context": "https://schema.org", "@type": "Series", "publisher": { "@type": "Organization", "name": "Stack Abuse", "logo": { "@type": "ImageObject", "url": "https://stackabuse.com/assets/images/favicon.svg" } }, "url": "https://stackabuse.com/tag/javascript/", "name": "javascript", "mainEntityOfPage": { "@type": "WebPage", "@id": "https://stackabuse.com/" } }</script><meta name="next-head-count" content="14"/><link href="//fonts.googleapis.com" rel="preconnect"/><link href="//fonts.gstatic.com" rel="preconnect" crossorigin="true"/><link href="//cdnjs.cloudflare.com" rel="preconnect"/><link href="//s3.stackabuse.com" rel="preconnect"/><link href="//googletagmanager.com" rel="dns-prefetch"/><meta charSet="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="HandheldFriendly" content="True"/><link rel="shortcut icon" sizes="any" href="/assets/images/favicon.ico"/><link rel="shortcut icon" type="image/svg+xml" href="/assets/images/favicon.svg"/><link rel="preload" as="style" href="//fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"/><link rel="preload" as="style" href="//fonts.googleapis.com/css?family=Nunito:400,400i,700,700i&display=swap"/><meta name="referrer" content="no-referrer-when-downgrade"/><link rel="alternate" type="application/rss+xml" title="Stack Abuse" href="https://stackabuse.com/rss/"/><link rel="preload" href="/_next/static/css/eaee8aa5ba78cb00.css" as="style"/><link rel="stylesheet" href="/_next/static/css/eaee8aa5ba78cb00.css" data-n-g=""/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills-c67a75d1b6f99dc8.js"></script><script src="/_next/static/chunks/webpack-1154c37f273c7921.js" defer=""></script><script src="/_next/static/chunks/framework-1dabaad0401a053e.js" defer=""></script><script src="/_next/static/chunks/main-7cc54cdcfbd9bea6.js" defer=""></script><script src="/_next/static/chunks/pages/_app-85dd70c54f224ed0.js" defer=""></script><script src="/_next/static/chunks/c78d26b1-fe043233b220ebfb.js" defer=""></script><script src="/_next/static/chunks/816-dfcc5ef3cff7cadb.js" defer=""></script><script src="/_next/static/chunks/3646-f084444085f451b1.js" defer=""></script><script src="/_next/static/chunks/7329-ea47eb245049fa3f.js" defer=""></script><script src="/_next/static/chunks/2221-aa293f4e0cf5d5c8.js" defer=""></script><script src="/_next/static/chunks/pages/tag/%5B...slug%5D-b520602e3aebd55c.js" defer=""></script><script src="/_next/static/1740324887682/_buildManifest.js" defer=""></script><script src="/_next/static/1740324887682/_ssgManifest.js" defer=""></script></head><body><div id="__next"><div><nav class="bg-white pb-2 border-b shadow"><div class="mx-8 px-2 sm:px-4 lg:px-8"><div class="flex justify-between h-16"><div class="flex items-center px-2 lg:px-0"><a href="/"><div class="flex-shrink-0 flex items-center"><svg class="h-6 w-full" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 494.36 63"><defs><style>.cls-1{fill:#363636}.cls-2{fill:#f29c80}.cls-3{fill:#b34a28}.cls-4{fill:#f16335}</style></defs><title>SA Logotype</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M104.94,27.65q-3.15-1.44-4.65-2.16c-1-.48-2.17-1.12-3.49-1.91A10.35,10.35,0,0,1,94,21.35a3.58,3.58,0,0,1-.82-2.27,4.79,4.79,0,0,1,1.74-3.89,7.6,7.6,0,0,1,5-1.44,16,16,0,0,1,5.61,1.15,27.13,27.13,0,0,1,4.1,1.84c.73.46,1.3.83,1.71,1.12l5.2-10.8-2-1.44A28.63,28.63,0,0,0,108,2.84a29.37,29.37,0,0,0-9-1.4A18.5,18.5,0,0,0,86.2,6.52a16.81,16.81,0,0,0-5.61,13.06,14.64,14.64,0,0,0,2.81,8.61,21.59,21.59,0,0,0,7.93,6.66c.82.43,2.09,1.07,3.8,1.91s2.94,1.46,3.69,1.87a27.75,27.75,0,0,1,2.6,1.65,6.9,6.9,0,0,1,2,2.09,4.57,4.57,0,0,1,.58,2.27q0,5.84-8.14,5.83a14.52,14.52,0,0,1-6.46-1.87,35.41,35.41,0,0,1-5.1-3c-.95-.74-1.71-1.35-2.25-1.83L75.67,55.15l.89.79a19.23,19.23,0,0,0,2.8,2c1.28.77,2.71,1.55,4.31,2.34a26.52,26.52,0,0,0,6,2,33.14,33.14,0,0,0,7.25.79,29.54,29.54,0,0,0,8-1,21.94,21.94,0,0,0,6.74-3.21,14.53,14.53,0,0,0,4.79-6,21.36,21.36,0,0,0,1.74-8.93,13.77,13.77,0,0,0-3.86-9.54A28,28,0,0,0,104.94,27.65Z"></path><path class="cls-1" d="M143.66,50.69a5.8,5.8,0,0,1-1.17.57,3.84,3.84,0,0,1-1.43.29q-2.75,0-2.74-5.11V34.7h7.39V25h-7.39V11.23H126.21V25h-5.06V34.7h5.06V48.89a22.21,22.21,0,0,0,.55,5,16,16,0,0,0,1.81,4.47,9,9,0,0,0,3.73,3.38A12.76,12.76,0,0,0,138.18,63a17.23,17.23,0,0,0,8.9-2.3l-3-10.3Z"></path><path class="cls-1" d="M177.44,28.51A15.41,15.41,0,0,0,166,23.9a15.82,15.82,0,0,0-12.51,5.69,20.47,20.47,0,0,0-4.93,13.9,20.33,20.33,0,0,0,4.93,13.86A15.85,15.85,0,0,0,166,63a14.47,14.47,0,0,0,11.49-5.26h.14v4.18h12V25H177.44Zm-2,21.17a7.68,7.68,0,0,1-5.85,2.45,7.79,7.79,0,0,1-6-2.41,8.74,8.74,0,0,1-2.26-6.23,8.69,8.69,0,0,1,2.36-6.27,8.15,8.15,0,0,1,11.63,0,8.69,8.69,0,0,1,2.36,6.27A8.74,8.74,0,0,1,175.43,49.68Z"></path><path class="cls-1" d="M216.43,34.34a9.4,9.4,0,0,1,5.88,1.73l4.11-8.71-1.16-.86a15,15,0,0,0-4.18-1.73,22.57,22.57,0,0,0-6.43-.87,18.72,18.72,0,0,0-13.57,5.8,18.81,18.81,0,0,0-5.85,13.86,18.52,18.52,0,0,0,5.85,13.72A18.83,18.83,0,0,0,214.65,63a22,22,0,0,0,6.54-.94,20,20,0,0,0,3.89-1.47c.57-.36,1-.66,1.34-.9l-4.11-8.86-.61.43a9.12,9.12,0,0,1-2.16.87,10.87,10.87,0,0,1-3.11.43,7.75,7.75,0,0,1-5.88-2.66,9.22,9.22,0,0,1-2.46-6.48A9.1,9.1,0,0,1,210.55,37,7.72,7.72,0,0,1,216.43,34.34Z"></path><polygon class="cls-1" points="271.43 24.98 255.69 24.98 243.45 37.87 243.45 0 231.34 0 231.34 61.92 243.45 61.92 243.45 47.16 257.47 61.92 273.07 61.92 254.74 42.62 271.43 24.98"></polygon><polygon class="cls-1" points="296.96 2.52 274.18 61.92 288 61.92 302.84 20.88 302.98 20.88 317.82 61.92 331.63 61.92 308.86 2.52 296.96 2.52"></polygon><path class="cls-1" d="M357.42,23.9a15.41,15.41,0,0,0-11.49,4.61V0H333.82V61.92h12V57.74h.14A14.47,14.47,0,0,0,357.42,63a15.88,15.88,0,0,0,12.52-5.65,20.38,20.38,0,0,0,4.92-13.86,20.51,20.51,0,0,0-4.92-13.9A15.86,15.86,0,0,0,357.42,23.9Zm2.33,25.82a7.8,7.8,0,0,1-5.95,2.41A7.65,7.65,0,0,1,348,49.68a8.69,8.69,0,0,1-2.29-6.19A8.64,8.64,0,0,1,348,37.22a7.7,7.7,0,0,1,5.78-2.44,7.78,7.78,0,0,1,5.84,2.44A8.64,8.64,0,0,1,362,43.49,8.78,8.78,0,0,1,359.75,49.72Z"></path><path class="cls-1" d="M405.78,42.55c0,3.65-.53,6.24-1.57,7.78s-2.83,2.3-5.34,2.3-4.29-.77-5.33-2.3S392,46.2,392,42.55V25h-12.1V45.65q0,9.21,4.54,13.28T398.87,63q9.92,0,14.47-4.07t4.55-13.28V25H405.78Z"></path><path class="cls-1" d="M449.11,42.19A20.21,20.21,0,0,0,445.79,40a23.31,23.31,0,0,0-3.69-1.44,8.7,8.7,0,0,1-1-.29c-.44-.14-.74-.25-.93-.32l-.82-.32-.78-.33-.65-.32a2.25,2.25,0,0,1-.58-.4c-.12-.12-.24-.26-.38-.43a1.25,1.25,0,0,1-.27-.54,2.25,2.25,0,0,1-.07-.58,1.82,1.82,0,0,1,.85-1.76,6.53,6.53,0,0,1,2.91-.47,16,16,0,0,1,7.8,2.31l4-8.36-1.43-.72a22.21,22.21,0,0,0-4.38-1.44,24.9,24.9,0,0,0-5.95-.72q-7,0-11.18,3.14a10.32,10.32,0,0,0-4.14,8.74,9.07,9.07,0,0,0,1.91,6,18.12,18.12,0,0,0,5.2,4.06,28.82,28.82,0,0,0,3.59,1.59A14.8,14.8,0,0,1,439,49a2.2,2.2,0,0,1,1,1.9c0,1.78-1.26,2.67-3.76,2.67a9.22,9.22,0,0,1-4-1.19A23.33,23.33,0,0,1,429,50.51c-.6-.46-1.08-.85-1.44-1.19L422.61,58l1.5,1.3A17.63,17.63,0,0,0,429,61.78,21,21,0,0,0,436.15,63q16.62,0,16.62-12.6a11.23,11.23,0,0,0-1-4.75A9.24,9.24,0,0,0,449.11,42.19Z"></path><path class="cls-1" d="M494.36,43.49q0-9.43-5.24-14.51T475.55,23.9a18.46,18.46,0,0,0-13.62,5.76,19,19,0,0,0-5.67,13.83,18.9,18.9,0,0,0,5.67,13.79A18.54,18.54,0,0,0,475.55,63q12.72,0,18.19-9.65L485,48.74a13.63,13.63,0,0,1-3.9,3.28,10.84,10.84,0,0,1-4.65.83,8.3,8.3,0,0,1-5.2-1.87q-2.4-1.87-2.4-5.76h25.45A14.91,14.91,0,0,0,494.36,43.49Zm-25.17-5.33a6,6,0,0,1,1.91-4.32,6.77,6.77,0,0,1,4.79-1.66,6.51,6.51,0,0,1,4.48,1.55,7,7,0,0,1,2.15,4.43Z"></path><polygon class="cls-2" points="66.05 19.08 73.15 1.3 57.25 1.3 50.16 19.08 66.05 19.08"></polygon><polygon class="cls-3" points="40.21 43.99 32.99 62.06 48.88 62.06 56.1 43.99 40.21 43.99"></polygon><polygon class="cls-4" points="57.69 40.01 64.46 23.05 48.57 23.05 41.8 40.01 57.69 40.01"></polygon><polygon class="cls-2" points="33.06 19.08 40.16 1.3 24.27 1.3 17.17 19.08 33.06 19.08"></polygon><polygon class="cls-3" points="7.22 43.99 0 62.06 15.89 62.06 23.11 43.99 7.22 43.99"></polygon><polygon class="cls-4" points="24.7 40.01 31.47 23.05 15.58 23.05 8.81 40.01 24.7 40.01"></polygon></g></g></svg></div></a><div class="hidden lg:block lg:ml-6"><div class="hidden lg:ml-6 lg:flex"><a href="/tools/" class="mr-8 inline-flex items-center px-1 pt-1 border-b-2 border-blue-400 text-sm font-medium leading-10 text-gray-500 hover:text-gray-700 focus:outline-none focus:text-gray-700 transition duration-150 ease-in-out">Tools</a><div class="px-1 pt-1 border-b-2 border-green-400 focus:border-gray-300 transition duration-150 ease-in-out"><div class="relative" data-headlessui-state=""><button class="text-gray-500 group rounded-md inline-flex items-center focus:outline-none text-sm font-medium leading-10 text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700" type="button" aria-expanded="false" data-headlessui-state=""><span>Learn</span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="text-gray-400 ml-2 h-5 w-5 group-hover:text-gray-500"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg></button></div><div hidden="" style="position:fixed;top:1px;left:1px;width:1px;height:0;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0;display:none"></div></div><a href="/about/" class="ml-8 inline-flex items-center px-1 pt-1 border-b-2 border-red-400 text-sm font-medium leading-10 text-gray-500 hover:text-gray-700 focus:outline-none focus:text-gray-700 transition duration-150 ease-in-out">About</a></div></div></div><div class="hidden mt-4 md:flex md:flex-1 md:items-center md:justify-center md:px-2 lg:ml-6 lg:justify-end"><div class="relative w-1/2 text-gray-400 transition duration-200 focus-within:text-gray-600"><div class="absolute inset-y-0 left-0 flex items-center pointer-events-none" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="h-5 w-5 ml-2"><path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path></svg></div><input id="search-field" class="block w-full h-full pl-10 pr-3 py-3 text-sm border-gray-300 text-gray-900 placeholder-gray-500 rounded transition duration-200 focus:outline-none focus:ring-0 focus:border-gray-400" placeholder="Search" type="text"/></div><div class="hidden ml-6 md:flex items-center"><button class="whitespace-nowrap text-base font-medium text-gray-500 hover:text-gray-900">Sign in</button><button class="ml-6 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-orange-500 hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500">Sign up</button></div></div><div class="flex items-center lg:hidden"><button class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out" aria-label="Main menu" aria-expanded="false"><svg class="block h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg><svg class="hidden h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg></button></div></div></div><div class="hidden lg:hidden"><div class="pt-2 pb-3"><a href="/tag/python" class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Python</a><a href="/tag/javascript" class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">JavaScript</a><a href="/tag/java" class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Java</a></div></div></nav><main><div class="flex items-stretch min-h-screen"><div class="mx-auto max-w-none lg:max-w-screen-xl px-4 sm:px-6 pb-6"><div class="grid grid-cols-12 sm:gap-x-2 lg:gap-x-3 pt-6"><div class="col-span-12 lg:col-span-7"><h1 class="my-1 text-3xl tracking-tight leading-10 font-extrabold text-gray-900 sm:leading-none sm:text-6xl lg:text-4xl xl:text-5xl">javascript</h1><div class="">Articles: <!-- -->375</div><div class="my-4"></div></div><div class="lg:col-span-1"></div></div><div class="mt-8 border-t border-gray-200"><h2 class="my-6 text-xl tracking-tight leading-10 font-extrabold text-gray-700 sm:leading-none sm:text-4xl lg:text-2xl xl:text-3xl">Recently published</h2><div class="grid gap-5 lg:grid-cols-3"><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/simplify-regular-expressions-with-regexpbuilderjs/"><img class="h-48 w-full object-cover" src="/assets/images/logo-javascript.png" alt=""/></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Article</p><a class="block hover:no-underline" href="/simplify-regular-expressions-with-regexpbuilderjs/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Simplify Regular Expressions with RegExpBuilderJS</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Regular expressions are on of the most powerful tools in a developer's toolkit. But let's be honest, regex kind of sucks to write. Not only is it hard to write, but it's also hard to read and debug too. So how can we make it easier to use? In its...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><img class="h-10 w-10 rounded-full" src="//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg" alt="Scott Robinson"/></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2024-06-06">Jun 06, 2024</time><span class="mx-1">路</span><span>5<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/get-name-from-an-email-address-with-javascript/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/get-name-from-an-email-address-with-javascript/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Get Name from an Email Address with JavaScript</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Let's talk about extracting names from email addresses using JavaScript. This can be useful when you're dealing with bulk data and need to personalize your communication. For instance, you might want to send out a mass email to your users but address each one by their name. Let's see how...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-12">Oct 12, 2023</time><span class="mx-1">路</span><span>17<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/refreshing-a-web-page-using-javascript-or-jquery/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/refreshing-a-web-page-using-javascript-or-jquery/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Refreshing a Web Page Using JavaScript or jQuery</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Let's explore a fundamental task in web development: refreshing a web page. But we're not talking about the classic F5 or CTRL+R here. We're instead going to be using JavaScript and jQuery to programmatically refresh a page. This is a handy trick for when you need a &quot;hard&...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-11">Oct 11, 2023</time><span class="mx-1">路</span><span>10<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/what-is-export-default-in-javascript/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/what-is-export-default-in-javascript/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">What is "export default" in JavaScript?</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">If you've been working with JavaScript, you've probably come across the term export default and wondered what it is or how it works. This Byte is meant for developers with a basic understanding of JavaScript, who are looking to deepen their knowledge of the language's intricacies. We'll be taking a...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-11">Oct 11, 2023</time><span class="mx-1">路</span><span>15<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/how-to-add-remove-multiple-classes-to-an-element-in-javascript/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/how-to-add-remove-multiple-classes-to-an-element-in-javascript/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">How to Add/Remove Multiple Classes to an Element in JavaScript</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">In this Byte you'll learn a bit about the importance of CSS classes and how to manipulate them using both vanilla JavaScript and jQuery. By the end, you'll be able to dynamically alter the appearance and behavior of your web elements with ease. Let's get started! CSS Classes As you...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-09">Oct 09, 2023</time><span class="mx-1">路</span><span>14<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/how-to-add-remove-an-event-listener-in-react/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/how-to-add-remove-an-event-listener-in-react/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">How to Add/Remove an Event Listener in React</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">If you've been working with React, you would know that it's a powerful JavaScript library for building user interfaces. But sometimes, you need to go beyond the basic click and change events. This is where event listeners come into play. This Byte is ideal for developers who are familiar with...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-07">Oct 07, 2023</time><span class="mx-1">路</span><span>20<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/call-a-function-every-n-seconds-in-typescript/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/call-a-function-every-n-seconds-in-typescript/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Call a Function Every N Seconds in TypeScript</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">When dealing with real-time, interactive, or dynamic applications, you may need to run a function every N seconds in TypeScript. In this Byte, we'll go over exactly how to do that. Why Use Time-Interval Function Calls? There are a lot of different scenarios where you might want to execute a...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-07">Oct 07, 2023</time><span class="mx-1">路</span><span>14<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/reading-environment-variables-in-node-js/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/reading-environment-variables-in-node-js/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Reading Environment Variables in Node.js</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Ever wondered how to manage sensitive data like API keys, database credentials or configuration settings in your Node.js applications? The answer lies with environment variables. This Byte will give a brief intro to environment variables, why they are important, and then we'll explore how to read them in Node....</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-05">Oct 05, 2023</time><span class="mx-1">路</span><span>20<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/how-to-convert-a-date-to-timestamp-in-javascript/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/how-to-convert-a-date-to-timestamp-in-javascript/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">How to Convert a Date to Timestamp in JavaScript</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">In programming, we often need to deal with dates and times, which can be represented in a few different ways, like an object (via Date), a string (i.e. &quot;2023-10-04T00:00:00.000Z&quot;), or a timestamp (i.e. 1696377600000). In this Byte, we'll explore how to convert a...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-10-04">Oct 04, 2023</time><span class="mx-1">路</span><span>15<!-- --> min read</span></div></div></div></div></div></div></div><div class="mt-8 border-t border-gray-200 px-4 flex items-center justify-between sm:px-0"><div class="-mt-px w-0 flex-1 flex justify-end"><a class="border-t-2 border-transparent pt-4 pl-1 inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300" href="/tag/javascript/page/2/">Next<svg class="ml-3 h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg></a></div></div></div></div></div></main><div class="bg-white border-t border-gray-300"><div class="max-w-screen-xl mx-auto pt-12 pb-6 px-4 sm:px-6 md:flex md:items-center md:justify-between lg:px-8"><div class="flex justify-center md:order-2"><a href="https://twitter.com/stackabuse" target="_blank" rel="noreferrer noopener" class="text-gray-500 hover:text-twitter"><span class="sr-only">Twitter</span><svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"><path d="M8.29 20.251c7.547 0 11.675-6.253 11.675-11.675 0-.178 0-.355-.012-.53A8.348 8.348 0 0022 5.92a8.19 8.19 0 01-2.357.646 4.118 4.118 0 001.804-2.27 8.224 8.224 0 01-2.605.996 4.107 4.107 0 00-6.993 3.743 11.65 11.65 0 01-8.457-4.287 4.106 4.106 0 001.27 5.477A4.072 4.072 0 012.8 9.713v.052a4.105 4.105 0 003.292 4.022 4.095 4.095 0 01-1.853.07 4.108 4.108 0 003.834 2.85A8.233 8.233 0 012 18.407a11.616 11.616 0 006.29 1.84"></path></svg></a><a href="https://github.com/stackabuse" target="_blank" rel="noreferrer noopener" class="ml-6 text-gray-500 hover:text-github"><span class="sr-only">GitHub</span><svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clip-rule="evenodd"></path></svg></a><a href="https://www.facebook.com/stackabuse" target="_blank" rel="noreferrer noopener" class="ml-6 text-gray-500 hover:text-facebook"><span class="sr-only">Facebook</span><svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z" clip-rule="evenodd"></path></svg></a></div><div class="mt-8 md:mt-0 md:order-1"><p class="text-center text-base leading-6 text-gray-500">漏 2013-<!-- -->2025<!-- --> Stack Abuse. All rights reserved.</p><div class="text-sm"><a href="/about" class="pr-4 text-gray-500 border-r-2 border-grey-400 hover:no-underline hover:text-gray-600">About</a><a href="/disclosure" class="px-4 text-gray-500 border-r-2 border-grey-400 hover:no-underline hover:text-gray-600">Disclosure</a><a href="/privacy-policy" class="px-4 text-gray-500 border-r-2 border-grey-400 hover:no-underline hover:text-gray-600">Privacy</a><a href="/terms-of-service" class="pl-4 text-gray-500 hover:no-underline hover:text-gray-600">Terms</a><div id="ccpa" style="display:none;cursor:pointer">Do not share my Personal Information.</div></div></div></div></div></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"tag":{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"contents":[{"id":2128,"old_id":null,"uuid":"935ed44a-5598-4a83-9558-8cace0acab47","title":"Simplify Regular Expressions with RegExpBuilderJS","slug":"simplify-regular-expressions-with-regexpbuilderjs","body_md":"Regular expressions are on of the most powerful tools in a developer's toolkit. But let's be honest, regex kind of sucks to write. Not only is it hard to write, but it's also hard to read and debug too. So how can we make it easier to use?\n\nIn its traditional form, regex defines powerful string patterns in a very compact statement. One trade-off we can make is to use a more verbose syntax that is easier to read and write. This is the purpose of a package like `regexpbuilderjs`.\n\n:::note\nThe `regexpbuilderjs` package is actually a port of the popular PHP package, \u003ca rel=\"nofollow noreferrer\" target=\"_blank\" href=\"https://github.com/gherkins/regexpbuilderphp/wiki#eitherfindregexpbuilder\"\u003eregexpbuilderphp\u003c/a\u003e. The `regexpbuilderphp` package itself is a port of an old JS package, `regexpbuilder`, which now seems to be gone. This new package is meant to continue the work of the original `regexpbuilder` package.\n\nAll credit goes to \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://github.com/thebinarysearchtree\"\u003eAndrew Jones\u003c/a\u003e for creating the original JS version and \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://github.com/gherkins\"\u003eMax Girkens\u003c/a\u003e for the PHP port.\n:::\n\n## Installation\n\nTo install the package, you can use npm:\n\n```console\n$ npm install regexpbuilderjs\n```\n\n## Usage\n\nHere's a simple example of how you can use the package:\n\n```javascript\nconst RegExpBuilder = require('regexpbuilderjs');\n\nconst builder = new RegExpBuilder();\nconst regEx = builder\n .startOfLine()\n .exactly(1)\n .of('S')\n .getRegExp();\n```\n\nNow let's break this down a bit. The `RegExpBuilder` class is the main class that you'll be using to build your regular expressions. You can start by creating a new instance of this class and chain methods together to create your regex:\n\n- `startOfLine()`: This method adds the `^` character to the regex, which matches the start of a line.\n- `exactly(1)`: This method adds the `{1}` quantifier to the regex, which matches exactly one occurrence of a given character or group.\n- `of('S')`: This method adds the `S` character to the regex.\n- `getRegExp()`: This method returns the final `RegExp` object that you can use to match strings.\n\nWith this, you can match strings like \"Scott\", \"Soccer\", or \"S418401\".\n\nThis is great and all, but this is probably a regex string you could come up with on your own and not struggle too much to read. So now let's see a more complex example:\n\n```javascript\nconst builder = new RegExpBuilder();\n\nconst regExp = builder\n .startOfInput()\n .exactly(4).digits()\n .then('_')\n .exactly(2).digits()\n .then('_')\n .min(3).max(10).letters()\n .then('.')\n .anyOf(['png', 'jpg', 'gif'])\n .endOfInput()\n .getRegExp();\n```\n\nThis regex is meant to match filenames, which may look like:\n\n- 2020_10_hund.jpg\n- 2030_11_katze.png\n- 4000_99_maus.gif\n\nSome interesting parts of this regex is that we can specify type of strings (i.e. `digits()`), min and max occurrences of a character or group (i.e. `min(3).max(10)`), and a list of possible values (i.e. `anyOf(['png', 'jpg', 'gif'])`).\n\nFor a full list of methods you can use to build your regex, you can check out the \u003ca rel=\"noopener\" target=\"_blank\" href=\"https://github.com/scottwrobinson/regexpbuilderjs?tab=readme-ov-file#documentation\"\u003edocumentation\u003c/a\u003e.\n\nThis is just a small taste of what you can do with `regexpbuilderjs`. The package is very powerful and can help you build complex regular expressions in a more readable and maintainable way.\n\n## Conclusion\n\nComments, questions, and suggestions are always welcome! If you have any feedback on how this could work better, feel free to \u003ca target=\"_blank\" href=\"https://twitter.com/ScottWRobinson\"\u003ereach out on X\u003c/a\u003e. In the meantime, you can check out the repo on \u003ca target=\"_blank\" href=\"https://github.com/scottwrobinson/regexpbuilderjs\"\u003eGitHub\u003c/a\u003e and give it a star while you're at it.","body_html":"\u003cp\u003eRegular expressions are on of the most powerful tools in a developer's toolkit. But let's be honest, regex kind of sucks to write. Not only is it hard to write, but it's also hard to read and debug too. So how can we make it easier to use?\u003c/p\u003e\n\u003cp\u003eIn its traditional form, regex defines powerful string patterns in a very compact statement. One trade-off we can make is to use a more verbose syntax that is easier to read and write. This is the purpose of a package like \u003ccode\u003eregexpbuilderjs\u003c/code\u003e.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003eThe \u003ccode\u003eregexpbuilderjs\u003c/code\u003e package is actually a port of the popular PHP package, \u003ca rel=\"nofollow noreferrer\" target=\"_blank\" href=\"https://github.com/gherkins/regexpbuilderphp/wiki#eitherfindregexpbuilder\"\u003eregexpbuilderphp\u003c/a\u003e. The \u003ccode\u003eregexpbuilderphp\u003c/code\u003e package itself is a port of an old JS package, \u003ccode\u003eregexpbuilder\u003c/code\u003e, which now seems to be gone. This new package is meant to continue the work of the original \u003ccode\u003eregexpbuilder\u003c/code\u003e package.\u003c/p\u003e\n\u003cp\u003eAll credit goes to \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://github.com/thebinarysearchtree\"\u003eAndrew Jones\u003c/a\u003e for creating the original JS version and \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://github.com/gherkins\"\u003eMax Girkens\u003c/a\u003e for the PHP port.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"installation\"\u003eInstallation\u003c/h2\u003e\n\u003cp\u003eTo install the package, you can use npm:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e npm install regexpbuilderjs\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"usage\"\u003eUsage\u003c/h2\u003e\n\u003cp\u003eHere's a simple example of how you can use the package:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e RegExpBuilder = \u003cspan class=\"hljs-built_in\"\u003erequire\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;regexpbuilderjs\u0026#x27;\u003c/span\u003e);\n\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e builder = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e RegExpBuilder();\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e regEx = builder\n .startOfLine()\n .exactly(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e)\n .of(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;S\u0026#x27;\u003c/span\u003e)\n .getRegExp();\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eNow let's break this down a bit. The \u003ccode\u003eRegExpBuilder\u003c/code\u003e class is the main class that you'll be using to build your regular expressions. You can start by creating a new instance of this class and chain methods together to create your regex:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\u003ccode\u003estartOfLine()\u003c/code\u003e: This method adds the \u003ccode\u003e^\u003c/code\u003e character to the regex, which matches the start of a line.\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003eexactly(1)\u003c/code\u003e: This method adds the \u003ccode\u003e{1}\u003c/code\u003e quantifier to the regex, which matches exactly one occurrence of a given character or group.\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003eof('S')\u003c/code\u003e: This method adds the \u003ccode\u003eS\u003c/code\u003e character to the regex.\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003egetRegExp()\u003c/code\u003e: This method returns the final \u003ccode\u003eRegExp\u003c/code\u003e object that you can use to match strings.\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eWith this, you can match strings like \u0026quot;Scott\u0026quot;, \u0026quot;Soccer\u0026quot;, or \u0026quot;S418401\u0026quot;.\u003c/p\u003e\n\u003cp\u003eThis is great and all, but this is probably a regex string you could come up with on your own and not struggle too much to read. So now let's see a more complex example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e builder = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e RegExpBuilder();\n\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e regExp = builder\n .startOfInput()\n .exactly(\u003cspan class=\"hljs-number\"\u003e4\u003c/span\u003e).digits()\n .then(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;_\u0026#x27;\u003c/span\u003e)\n .exactly(\u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e).digits()\n .then(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;_\u0026#x27;\u003c/span\u003e)\n .min(\u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e).max(\u003cspan class=\"hljs-number\"\u003e10\u003c/span\u003e).letters()\n .then(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;.\u0026#x27;\u003c/span\u003e)\n .anyOf([\u003cspan class=\"hljs-string\"\u003e\u0026#x27;png\u0026#x27;\u003c/span\u003e, \u003cspan class=\"hljs-string\"\u003e\u0026#x27;jpg\u0026#x27;\u003c/span\u003e, \u003cspan class=\"hljs-string\"\u003e\u0026#x27;gif\u0026#x27;\u003c/span\u003e])\n .endOfInput()\n .getRegExp();\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis regex is meant to match filenames, which may look like:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e2020_10_hund.jpg\u003c/li\u003e\n\u003cli\u003e2030_11_katze.png\u003c/li\u003e\n\u003cli\u003e4000_99_maus.gif\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eSome interesting parts of this regex is that we can specify type of strings (i.e. \u003ccode\u003edigits()\u003c/code\u003e), min and max occurrences of a character or group (i.e. \u003ccode\u003emin(3).max(10)\u003c/code\u003e), and a list of possible values (i.e. \u003ccode\u003eanyOf(['png', 'jpg', 'gif'])\u003c/code\u003e).\u003c/p\u003e\n\u003cp\u003eFor a full list of methods you can use to build your regex, you can check out the \u003ca rel=\"noopener\" target=\"_blank\" href=\"https://github.com/scottwrobinson/regexpbuilderjs?tab=readme-ov-file#documentation\"\u003edocumentation\u003c/a\u003e.\u003c/p\u003e\n\u003cp\u003eThis is just a small taste of what you can do with \u003ccode\u003eregexpbuilderjs\u003c/code\u003e. The package is very powerful and can help you build complex regular expressions in a more readable and maintainable way.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eComments, questions, and suggestions are always welcome! If you have any feedback on how this could work better, feel free to \u003ca target=\"_blank\" href=\"https://twitter.com/ScottWRobinson\"\u003ereach out on X\u003c/a\u003e. In the meantime, you can check out the repo on \u003ca target=\"_blank\" href=\"https://github.com/scottwrobinson/regexpbuilderjs\"\u003eGitHub\u003c/a\u003e and give it a star while you're at it.\u003c/p\u003e\n","parent_id":null,"type":"article","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":5,"published_by":1,"published_at":1717699045389,"created_by":1,"updated_by":null,"created_at":1717698906805,"updated_at":1717699130504,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2128,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":39,"name":"regex","slug":"regex","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431360680000,"updated_at":1431360680000,"_pivot_content_id":2128,"_pivot_tag_id":39,"_pivot_sort_order":0},{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2128,"_pivot_tag_id":45,"_pivot_sort_order":1},{"id":48,"name":"node","slug":"node","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2128,"_pivot_tag_id":48,"_pivot_sort_order":2}],"_pivot_tag_id":45,"_pivot_content_id":2128},{"id":2120,"old_id":null,"uuid":"6c5ebf4c-cf4c-4b68-85cc-4a892b2eac9d","title":"Get Name from an Email Address with JavaScript","slug":"get-name-from-an-email-address-with-javascript","body_md":"## Introduction\n\nLet's talk about extracting names from email addresses using JavaScript. This can be useful when you're dealing with bulk data and need to personalize your communication. For instance, you might want to send out a mass email to your users but address each one by their name. Let's see how we can do this.\n\n## Email Address Structure\n\nBefore we get into the JavaScript solution, let's first understand the structure of an email address. A basic email address consists of two parts separated by an '@' symbol - the local part and the domain part. The local part is usually the name of the individual or service, while the domain part represents the domain where the email is hosted.\n\nA typical email address looks like this: `name@domain.tld`. However, email addresses can also come in other formats such as `Name \u003cname@domain.tld\u003e`. In this case, the name of the individual is separated from the email address by a pair of angle brackets. \n\n## The JavaScript Approach\n\nJavaScript provides several built-in methods and regular expressions that we can use to extract the name from an email address. We will be exploring two of these methods in this Byte - the `split()` method and regular expressions.\n\n## Using String Split Method\n\nThe \u003ca target=\"_blank\" href=\"https://stackabuse.com/how-to-split-a-string-in-javascript/\"\u003esplit() method\u003c/a\u003e 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.\n\nHere's how we can use the `split()` method to extract the name from an email address:\n\n```javascript\nlet email = \"Scott \u003cscott@gmail.com\u003e\";\nlet name = email.split('\u003c')[0].trim();\nconsole.log(name); // Output: Scott\n```\n\nIn this example, we're splitting the email string at the '\u003c' character, which gives us an array of two elements. The first element is \"Scott \", and the second one is `scott@gmail.com\u003e`. We then use the `trim()` method to remove the trailing space from the first element, which gives us the name \"Scott\".\n\nBut what if the email address doesn't contain angle brackets? In that case, we can split the string at the '@' character:\n\n```javascript\nlet email = \"scott@gmail.com\";\nlet name = email.split('@')[0];\nconsole.log(name); // Output: scott\n```\n\nThis method is simple and works well for most email formats. However, it may not work as expected for some unusual email formats.\n\nOne thing you'll need to account for is first checking what format the email address is in. Since it can take on a few different forms, you'll need to have a robust method for first determining what the format is.\n\n## Using Regular Expressions\n\n\u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-regular-expressions-and-matching-strings-in-javascript/\"\u003eRegular expressions\u003c/a\u003e, or regex, are sequences of characters that define a search pattern. In JavaScript, we can use them to extract the name from an email address. Again we'll consider an email address in the format of `Name \u003cname@domain.tld\u003e`, for example, `Scott \u003cscott@gmail.com\u003e`.\n\nThe regex we'll use is `/.*(?=\u003c)/`. This pattern will match any character until it hits the `\u003c` symbol, which is the delimiter between the name and the email in our format.\n\nHere is a simple function that uses this regex to get the name from the email:\n\n```javascript\nfunction getNameFromEmail(email) {\n const regex = /.*(?=\u003c)/;\n const match = email.match(regex);\n return match ? match[0].trim() : null;\n}\n\nconsole.log(getNameFromEmail(\"Scott \u003cscott@gmail.com\u003e\")); // Output: \"Scott\"\n```\n\nThe `match()` method returns the matched string, or `null` if no match was found. We then use the `trim()` method to remove any leading or trailing spaces.\n\n### Using Third-Party Libraries\n\nIf you're looking to save time and avoid reinventing the wheel (which I'd highly recommend), there are a number of third-party libraries that can help extract names from email addresses. One popular option is the \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://www.npmjs.com/package/email-addresses\"\u003eemail-addresses\u003c/a\u003e library. This library provides a robust set of tools for parsing email addresses, including extracting names.\n\nHere's an example of how you might use it:\n\n```javascript\nconst emailAddress = require('email-addresses');\n\nlet email = 'Scott \u003cscott@gmail.com\u003e';\nlet parsedEmail = emailAddress.parseOneAddress(email);\n\nconsole.log(parsedEmail.name); // Outputs: Scott\n```\n\nIn this example, we're using the `parseOneAddress` function from the `email-addresses` library to parse the email address. Then we simply log the `name` property of the returned object.\n\nFor what it's worth, this is the library I use for the \u003ca href=\"https://blocksender.io\"\u003eBlock Sender\u003c/a\u003e service, and it's served me well for a long time. I'd recommend it for any non-trivial email parsing needs.\n\n## Potential Errors and Their Solutions\n\nWhile the above method works fine for standard email formats, it might not work as expected with unusual or invalid email formats. For example, if the email doesn't contain a `\u003c` symbol, the `match()` method will return `null`, and we'll have no name to return.\n\n### Handling Invalid Email Formats\n\nIf an email address is not in the expected format, our function will return `null`. As we touched on earlier in this Byte, we can add simple checks at the beginning of our function to check its format:\n\n```javascript\nfunction getNameFromEmail(email) {\n if (!email.includes('\u003c')) {\n return null;\n }\n const regex = /.*(?=\u003c)/;\n const match = email.match(regex);\n return match ? match[0].trim() : null;\n}\n\nconsole.log(getNameFromEmail(\"scott@gmail.com\")); // Output: null\n```\n\nNow, if the email doesn't contain a `\u003c` symbol, the function will immediately return `null`.\n\n### Dealing with Unusual Email Formats\n\nSometimes, you might come across unusual email formats. For instance, the name might contain special characters, or the email might use a different delimiter. In such cases, you'll need to modify your regex or write a custom function to handle these cases.\n\nLet's consider an email format where the name is enclosed in square brackets, for example, \"[Scott] scott@gmail.com\". Our previous function won't work here, but we can easily modify the regex to handle this:\n\n```javascript\nfunction getNameFromEmail(email) {\n const regex = /\\[(.*?)\\]/;\n const match = email.match(regex);\n return match ? match[1].trim() : null;\n}\n\nconsole.log(getNameFromEmail(\"[Scott] scott@gmail.com\")); // Output: \"Scott\"\n```\n\nWhile this may not be a standardized address form, you'd be surprised at how many different formats of emails are out there, standardized or not. If you're going to be handling a large number of emails, especially those not from popular and conforming email services like G Suite, you'll need to invest time in catching all edge cases.\n\n## Conclusion\n\nIn this Byte, we've explored various ways to extract a name from an email address using JavaScript. We've looked at built-in JavaScript methods, regular expressions, and even third-party libraries. We've also discussed potential issues with non-standard formats. Hopefully you've found a method that works well for your use-case.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eLet's talk about extracting names from email addresses using JavaScript. This can be useful when you're dealing with bulk data and need to personalize your communication. For instance, you might want to send out a mass email to your users but address each one by their name. Let's see how we can do this.\u003c/p\u003e\n\u003ch2 id=\"emailaddressstructure\"\u003eEmail Address Structure\u003c/h2\u003e\n\u003cp\u003eBefore we get into the JavaScript solution, let's first understand the structure of an email address. A basic email address consists of two parts separated by an '@' symbol - the local part and the domain part. The local part is usually the name of the individual or service, while the domain part represents the domain where the email is hosted.\u003c/p\u003e\n\u003cp\u003eA typical email address looks like this: \u003ccode\u003ename@domain.tld\u003c/code\u003e. However, email addresses can also come in other formats such as \u003ccode\u003eName \u0026lt;name@domain.tld\u0026gt;\u003c/code\u003e. In this case, the name of the individual is separated from the email address by a pair of angle brackets.\u003c/p\u003e\n\u003ch2 id=\"thejavascriptapproach\"\u003eThe JavaScript Approach\u003c/h2\u003e\n\u003cp\u003eJavaScript provides several built-in methods and regular expressions that we can use to extract the name from an email address. We will be exploring two of these methods in this Byte - the \u003ccode\u003esplit()\u003c/code\u003e method and regular expressions.\u003c/p\u003e\n\u003ch2 id=\"usingstringsplitmethod\"\u003eUsing String Split Method\u003c/h2\u003e\n\u003cp\u003eThe \u003ca target=\"_blank\" href=\"https://stackabuse.com/how-to-split-a-string-in-javascript/\"\u003esplit() method\u003c/a\u003e divides a \u003ccode\u003eString\u003c/code\u003e 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.\u003c/p\u003e\n\u003cp\u003eHere's how we can use the \u003ccode\u003esplit()\u003c/code\u003e method to extract the name from an email address:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e email = \u003cspan class=\"hljs-string\"\u003e\u0026quot;Scott \u0026lt;scott@gmail.com\u0026gt;\u0026quot;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e name = email.split(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;\u0026lt;\u0026#x27;\u003c/span\u003e)[\u003cspan class=\"hljs-number\"\u003e0\u003c/span\u003e].trim();\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(name); \u003cspan class=\"hljs-comment\"\u003e// Output: Scott\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this example, we're splitting the email string at the '\u0026lt;' character, which gives us an array of two elements. The first element is \u0026quot;Scott \u0026quot;, and the second one is \u003ccode\u003escott@gmail.com\u0026gt;\u003c/code\u003e. We then use the \u003ccode\u003etrim()\u003c/code\u003e method to remove the trailing space from the first element, which gives us the name \u0026quot;Scott\u0026quot;.\u003c/p\u003e\n\u003cp\u003eBut what if the email address doesn't contain angle brackets? In that case, we can split the string at the '@' character:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e email = \u003cspan class=\"hljs-string\"\u003e\u0026quot;scott@gmail.com\u0026quot;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e name = email.split(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;@\u0026#x27;\u003c/span\u003e)[\u003cspan class=\"hljs-number\"\u003e0\u003c/span\u003e];\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(name); \u003cspan class=\"hljs-comment\"\u003e// Output: scott\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis method is simple and works well for most email formats. However, it may not work as expected for some unusual email formats.\u003c/p\u003e\n\u003cp\u003eOne thing you'll need to account for is first checking what format the email address is in. Since it can take on a few different forms, you'll need to have a robust method for first determining what the format is.\u003c/p\u003e\n\u003ch2 id=\"usingregularexpressions\"\u003eUsing Regular Expressions\u003c/h2\u003e\n\u003cp\u003e\u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-regular-expressions-and-matching-strings-in-javascript/\"\u003eRegular expressions\u003c/a\u003e, or regex, are sequences of characters that define a search pattern. In JavaScript, we can use them to extract the name from an email address. Again we'll consider an email address in the format of \u003ccode\u003eName \u0026lt;name@domain.tld\u0026gt;\u003c/code\u003e, for example, \u003ccode\u003eScott \u0026lt;scott@gmail.com\u0026gt;\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eThe regex we'll use is \u003ccode\u003e/.*(?=\u0026lt;)/\u003c/code\u003e. This pattern will match any character until it hits the \u003ccode\u003e\u0026lt;\u003c/code\u003e symbol, which is the delimiter between the name and the email in our format.\u003c/p\u003e\n\u003cp\u003eHere is a simple function that uses this regex to get the name from the email:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003egetNameFromEmail\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003eemail\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e regex = \u003cspan class=\"hljs-regexp\"\u003e/.*(?=\u0026lt;)/\u003c/span\u003e;\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e match = email.match(regex);\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e match ? match[\u003cspan class=\"hljs-number\"\u003e0\u003c/span\u003e].trim() : \u003cspan class=\"hljs-literal\"\u003enull\u003c/span\u003e;\n}\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(getNameFromEmail(\u003cspan class=\"hljs-string\"\u003e\u0026quot;Scott \u0026lt;scott@gmail.com\u0026gt;\u0026quot;\u003c/span\u003e)); \u003cspan class=\"hljs-comment\"\u003e// Output: \u0026quot;Scott\u0026quot;\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe \u003ccode\u003ematch()\u003c/code\u003e method returns the matched string, or \u003ccode\u003enull\u003c/code\u003e if no match was found. We then use the \u003ccode\u003etrim()\u003c/code\u003e method to remove any leading or trailing spaces.\u003c/p\u003e\n\u003ch3 id=\"usingthirdpartylibraries\"\u003eUsing Third-Party Libraries\u003c/h3\u003e\n\u003cp\u003eIf you're looking to save time and avoid reinventing the wheel (which I'd highly recommend), there are a number of third-party libraries that can help extract names from email addresses. One popular option is the \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://www.npmjs.com/package/email-addresses\"\u003eemail-addresses\u003c/a\u003e library. This library provides a robust set of tools for parsing email addresses, including extracting names.\u003c/p\u003e\n\u003cp\u003eHere's an example of how you might use it:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e emailAddress = \u003cspan class=\"hljs-built_in\"\u003erequire\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;email-addresses\u0026#x27;\u003c/span\u003e);\n\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e email = \u003cspan class=\"hljs-string\"\u003e\u0026#x27;Scott \u0026lt;scott@gmail.com\u0026gt;\u0026#x27;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e parsedEmail = emailAddress.parseOneAddress(email);\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(parsedEmail.name); \u003cspan class=\"hljs-comment\"\u003e// Outputs: Scott\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this example, we're using the \u003ccode\u003eparseOneAddress\u003c/code\u003e function from the \u003ccode\u003eemail-addresses\u003c/code\u003e library to parse the email address. Then we simply log the \u003ccode\u003ename\u003c/code\u003e property of the returned object.\u003c/p\u003e\n\u003cp\u003eFor what it's worth, this is the library I use for the \u003ca href=\"https://blocksender.io\"\u003eBlock Sender\u003c/a\u003e service, and it's served me well for a long time. I'd recommend it for any non-trivial email parsing needs.\u003c/p\u003e\n\u003ch2 id=\"potentialerrorsandtheirsolutions\"\u003ePotential Errors and Their Solutions\u003c/h2\u003e\n\u003cp\u003eWhile the above method works fine for standard email formats, it might not work as expected with unusual or invalid email formats. For example, if the email doesn't contain a \u003ccode\u003e\u0026lt;\u003c/code\u003e symbol, the \u003ccode\u003ematch()\u003c/code\u003e method will return \u003ccode\u003enull\u003c/code\u003e, and we'll have no name to return.\u003c/p\u003e\n\u003ch3 id=\"handlinginvalidemailformats\"\u003eHandling Invalid Email Formats\u003c/h3\u003e\n\u003cp\u003eIf an email address is not in the expected format, our function will return \u003ccode\u003enull\u003c/code\u003e. As we touched on earlier in this Byte, we can add simple checks at the beginning of our function to check its format:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003egetNameFromEmail\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003eemail\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003eif\u003c/span\u003e (!email.includes(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;\u0026lt;\u0026#x27;\u003c/span\u003e)) {\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e \u003cspan class=\"hljs-literal\"\u003enull\u003c/span\u003e;\n }\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e regex = \u003cspan class=\"hljs-regexp\"\u003e/.*(?=\u0026lt;)/\u003c/span\u003e;\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e match = email.match(regex);\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e match ? match[\u003cspan class=\"hljs-number\"\u003e0\u003c/span\u003e].trim() : \u003cspan class=\"hljs-literal\"\u003enull\u003c/span\u003e;\n}\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(getNameFromEmail(\u003cspan class=\"hljs-string\"\u003e\u0026quot;scott@gmail.com\u0026quot;\u003c/span\u003e)); \u003cspan class=\"hljs-comment\"\u003e// Output: null\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eNow, if the email doesn't contain a \u003ccode\u003e\u0026lt;\u003c/code\u003e symbol, the function will immediately return \u003ccode\u003enull\u003c/code\u003e.\u003c/p\u003e\n\u003ch3 id=\"dealingwithunusualemailformats\"\u003eDealing with Unusual Email Formats\u003c/h3\u003e\n\u003cp\u003eSometimes, you might come across unusual email formats. For instance, the name might contain special characters, or the email might use a different delimiter. In such cases, you'll need to modify your regex or write a custom function to handle these cases.\u003c/p\u003e\n\u003cp\u003eLet's consider an email format where the name is enclosed in square brackets, for example, \u0026quot;[Scott] \u003ca href=\"mailto:scott@gmail.com\"\u003escott@gmail.com\u003c/a\u003e\u0026quot;. Our previous function won't work here, but we can easily modify the regex to handle this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003egetNameFromEmail\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003eemail\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e regex = \u003cspan class=\"hljs-regexp\"\u003e/\\[(.*?)\\]/\u003c/span\u003e;\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e match = email.match(regex);\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e match ? match[\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e].trim() : \u003cspan class=\"hljs-literal\"\u003enull\u003c/span\u003e;\n}\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(getNameFromEmail(\u003cspan class=\"hljs-string\"\u003e\u0026quot;[Scott] scott@gmail.com\u0026quot;\u003c/span\u003e)); \u003cspan class=\"hljs-comment\"\u003e// Output: \u0026quot;Scott\u0026quot;\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eWhile this may not be a standardized address form, you'd be surprised at how many different formats of emails are out there, standardized or not. If you're going to be handling a large number of emails, especially those not from popular and conforming email services like G Suite, you'll need to invest time in catching all edge cases.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've explored various ways to extract a name from an email address using JavaScript. We've looked at built-in JavaScript methods, regular expressions, and even third-party libraries. We've also discussed potential issues with non-standard formats. Hopefully you've found a method that works well for your use-case.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":17,"published_by":1,"published_at":1697078452302,"created_by":1,"updated_by":null,"created_at":1697077106603,"updated_at":1697078452315,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2120,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2120,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":48,"name":"node","slug":"node","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2120,"_pivot_tag_id":48,"_pivot_sort_order":1}],"_pivot_tag_id":45,"_pivot_content_id":2120},{"id":2117,"old_id":null,"uuid":"52b20c99-6d05-4c64-aa08-d6d0b3203210","title":"Refreshing a Web Page Using JavaScript or jQuery","slug":"refreshing-a-web-page-using-javascript-or-jquery","body_md":"## Introduction\n\nLet's explore a fundamental task in web development: refreshing a web page. But we're not talking about the classic \u003ckbd\u003eF5\u003c/kbd\u003e or \u003ckbd\u003eCTRL+R\u003c/kbd\u003e here. We're instead going to be using JavaScript and jQuery to programmatically refresh a page. This is a handy trick for when you need a \"hard\" refresh.\n\n## Why Programmatically Refresh a Page?\n\nThere are various times where this could be beneficial. For instance, you might want to automatically reload a page when a certain event occurs, or refresh a page after a specific interval to fetch the latest data from the server. This is particularly useful in dynamic applications where content updates frequently (like a live news feed or a real-time dashboard), but for whatever reason, you don't have asynchronous updates via AJAX.\n\n## Refreshing a Page with Plain JS\n\nLet's start with plain old JavaScript. The simplest way to refresh a page using JavaScript is by using the `location.reload()` method. Which can be used with just this one method call:\n\n```javascript\nlocation.reload();\n```\n\nWhen this code is executed, the current page will be reloaded. It's as simple as that! But remember, this will refresh the entire page which means any unsaved changes in the form inputs will be lost.\n\n:::note\n**Note:** There's a slight twist to the `location.reload()` method. It accepts a Boolean parameter. When set to `true`, it causes a hard reload from the server. When set to `false` or left undefined, it performs a soft reload from the _browser cache_. So, just be aware that `location.reload(true)` and `location.reload()` behave differently!\n:::\n\n## Refreshing a Page with jQuery\n\nNext up, let's see how to refresh a page using jQuery. jQuery doesn't have a built-in method for page refresh, but it's easy to do it by leveraging the JavaScript `location.reload()` method.\n\nWhile jQuery doesn't actually have a built-in method to do a page refresh, we can instead leverage some of its events to know when to refresh. For example:\n\n```javascript\n$(\"#refresh-button\").click(function() {\n location.reload();\n}); \n```\n\nHere we're refreshing the page when the user clicks our \"frefresh button\".\n\n## Common Errors and How to Fix Them\n\nWhen working with JavaScript or jQuery to refresh a web page, several common errors may occur. Let's take a look at a few of them and their solutions.\n\n### Infinite Loop of Page Refreshes\n\nThis happens when the page refresh code is placed in a location where it gets executed every time the page loads. Since the refresh command reloads the page, it gets stuck in an infinite loop of refreshes.\n\n```javascript\n// This will cause an infinite loop of page refreshes\nwindow.onload = function() {\n location.reload();\n}\n```\n\nTo avoid this, ensure you have a condition that can break the loop.\n\n```javascript\n// This will refresh the page only once\nif (!window.location.hash) {\n window.location = window.location + '#loaded';\n window.location.reload();\n}\n```\n\n### Uncaught TypeError: location.reload() is not a function\n\nThis error occurs when you attempt to call the `location.reload()` method on an object that doesn't have it. For instance, if you mistakenly call `location.reload()` on a jQuery object, you'll run into this error. \n\n```javascript\n$('#myDiv').location.reload(); // Uncaught TypeError: $(...).location is not a function\n```\n\nTo fix this, ensure you're calling `location.reload()` on the correct object, which is the `window` or `location` object.\n\n```javascript\nwindow.location.reload(); // Correct usage\n```\n\n## Conclusion\n\nIn this Byte, we've covered how to refresh a page using JavaScript and jQuery. We've also looked at some common errors that may occur when refreshing a page and how to fix them. Just remember, refreshing a page will cause any unsaved changes to be lost, and it's not always a good experience for the user, so use it sparingly.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eLet's explore a fundamental task in web development: refreshing a web page. But we're not talking about the classic \u003ckbd\u003eF5\u003c/kbd\u003e or \u003ckbd\u003eCTRL+R\u003c/kbd\u003e here. We're instead going to be using JavaScript and jQuery to programmatically refresh a page. This is a handy trick for when you need a \u0026quot;hard\u0026quot; refresh.\u003c/p\u003e\n\u003ch2 id=\"whyprogrammaticallyrefreshapage\"\u003eWhy Programmatically Refresh a Page?\u003c/h2\u003e\n\u003cp\u003eThere are various times where this could be beneficial. For instance, you might want to automatically reload a page when a certain event occurs, or refresh a page after a specific interval to fetch the latest data from the server. This is particularly useful in dynamic applications where content updates frequently (like a live news feed or a real-time dashboard), but for whatever reason, you don't have asynchronous updates via AJAX.\u003c/p\u003e\n\u003ch2 id=\"refreshingapagewithplainjs\"\u003eRefreshing a Page with Plain JS\u003c/h2\u003e\n\u003cp\u003eLet's start with plain old JavaScript. The simplest way to refresh a page using JavaScript is by using the \u003ccode\u003elocation.reload()\u003c/code\u003e method. Which can be used with just this one method call:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003elocation.reload();\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eWhen this code is executed, the current page will be reloaded. It's as simple as that! But remember, this will refresh the entire page which means any unsaved changes in the form inputs will be lost.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e There's a slight twist to the \u003ccode\u003elocation.reload()\u003c/code\u003e method. It accepts a Boolean parameter. When set to \u003ccode\u003etrue\u003c/code\u003e, it causes a hard reload from the server. When set to \u003ccode\u003efalse\u003c/code\u003e or left undefined, it performs a soft reload from the \u003cem\u003ebrowser cache\u003c/em\u003e. So, just be aware that \u003ccode\u003elocation.reload(true)\u003c/code\u003e and \u003ccode\u003elocation.reload()\u003c/code\u003e behave differently!\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"refreshingapagewithjquery\"\u003eRefreshing a Page with jQuery\u003c/h2\u003e\n\u003cp\u003eNext up, let's see how to refresh a page using jQuery. jQuery doesn't have a built-in method for page refresh, but it's easy to do it by leveraging the JavaScript \u003ccode\u003elocation.reload()\u003c/code\u003e method.\u003c/p\u003e\n\u003cp\u003eWhile jQuery doesn't actually have a built-in method to do a page refresh, we can instead leverage some of its events to know when to refresh. For example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e$(\u003cspan class=\"hljs-string\"\u003e\u0026quot;#refresh-button\u0026quot;\u003c/span\u003e).click(\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n location.reload();\n}); \n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHere we're refreshing the page when the user clicks our \u0026quot;frefresh button\u0026quot;.\u003c/p\u003e\n\u003ch2 id=\"commonerrorsandhowtofixthem\"\u003eCommon Errors and How to Fix Them\u003c/h2\u003e\n\u003cp\u003eWhen working with JavaScript or jQuery to refresh a web page, several common errors may occur. Let's take a look at a few of them and their solutions.\u003c/p\u003e\n\u003ch3 id=\"infiniteloopofpagerefreshes\"\u003eInfinite Loop of Page Refreshes\u003c/h3\u003e\n\u003cp\u003eThis happens when the page refresh code is placed in a location where it gets executed every time the page loads. Since the refresh command reloads the page, it gets stuck in an infinite loop of refreshes.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// This will cause an infinite loop of page refreshes\u003c/span\u003e\n\u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.onload = \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n location.reload();\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eTo avoid this, ensure you have a condition that can break the loop.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// This will refresh the page only once\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eif\u003c/span\u003e (!\u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.location.hash) {\n \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.location = \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.location + \u003cspan class=\"hljs-string\"\u003e\u0026#x27;#loaded\u0026#x27;\u003c/span\u003e;\n \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.location.reload();\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch3 id=\"uncaughttypeerrorlocationreloadisnotafunction\"\u003eUncaught TypeError: location.reload() is not a function\u003c/h3\u003e\n\u003cp\u003eThis error occurs when you attempt to call the \u003ccode\u003elocation.reload()\u003c/code\u003e method on an object that doesn't have it. For instance, if you mistakenly call \u003ccode\u003elocation.reload()\u003c/code\u003e on a jQuery object, you'll run into this error.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e$(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;#myDiv\u0026#x27;\u003c/span\u003e).location.reload(); \u003cspan class=\"hljs-comment\"\u003e// Uncaught TypeError: $(...).location is not a function\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eTo fix this, ensure you're calling \u003ccode\u003elocation.reload()\u003c/code\u003e on the correct object, which is the \u003ccode\u003ewindow\u003c/code\u003e or \u003ccode\u003elocation\u003c/code\u003e object.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.location.reload(); \u003cspan class=\"hljs-comment\"\u003e// Correct usage\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've covered how to refresh a page using JavaScript and jQuery. We've also looked at some common errors that may occur when refreshing a page and how to fix them. Just remember, refreshing a page will cause any unsaved changes to be lost, and it's not always a good experience for the user, so use it sparingly.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":10,"published_by":1,"published_at":1697049640472,"created_by":1,"updated_by":null,"created_at":1697043487975,"updated_at":1697049644571,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2117,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2117,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":196,"name":"web development","slug":"web-development","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1601641448000,"updated_at":1601641448000,"_pivot_content_id":2117,"_pivot_tag_id":196,"_pivot_sort_order":2},{"id":267,"name":"jquery","slug":"jquery","img_cover":null,"description_md":"","description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":1,"updated_by":null,"created_at":1692997806624,"updated_at":1692997806624,"_pivot_content_id":2117,"_pivot_tag_id":267,"_pivot_sort_order":1}],"_pivot_tag_id":45,"_pivot_content_id":2117},{"id":2116,"old_id":null,"uuid":"394f2443-8779-4e2a-a65f-a69aa7597e95","title":"What is \"export default\" in JavaScript?","slug":"what-is-export-default-in-javascript","body_md":"## Introduction\n\nIf you've been working with JavaScript, you've probably come across the term `export default` and wondered what it is or how it works. This Byte is meant for developers with a basic understanding of JavaScript, who are looking to deepen their knowledge of the language's intricacies. We'll be taking a closer look at JavaScript modules and the concept of `export default`. By the end, you should have a better understanding of how and when to use `export default` in your code.\n\n## Understanding JavaScript Modules\n\nJavaScript modules are self-contained pieces of code that can be exported and imported into other JavaScript files. They help in organizing code, making it more maintainable, and more reusable. JavaScript modules were introduced in ES6 and have since become a core part of modern JavaScript development.\n\nConsider the following example:\n\n```javascript\n// mathFunctions.js\nconst add = (a, b) =\u003e a + b;\nconst subtract = (a, b) =\u003e a - b;\n\nexport { add, subtract };\n```\n\nIn the code above, we have a module named `mathFunctions.js` that exports two functions: `add` and `subtract`.\n\n```javascript\n// app.js\nimport { add, subtract } from './mathFunctions.js';\n\nconsole.log(add(2, 3)); // Output: 5\nconsole.log(subtract(5, 2)); // Output: 3\n```\n\nIn `app.js`, we import the `add` and `subtract` functions from `mathFunctions.js` and use them as needed.\n\n## What is 'export default'?\n\n`export default` is a syntax used in JavaScript modules to export a single entity (be it a function, object, or variable) as the _default_ export from a module.\n\nConsider the following example:\n\n```javascript\n// greeting.js\nconst greeting = 'Hello, StackAbuse readers!';\n\nexport default greeting;\n```\n\nIn the code above, we have a module named `greeting.js` that exports a single string `greeting` as the default export.\n\n```javascript\n// app.js\nimport greeting from './greeting.js';\n\nconsole.log(greeting); // Output: Hello, StackAbuse readers!\n```\n\nIn `app.js`, we import the default export from `greeting.js` and use it as needed. **Notice how we didn't use curly braces `{}` to import the default export.** This is the purpose of the `default` keyword.\n\nThis is similar to how you'd use `exports.greeting = ...` vs `module.exports = ...` in Node.\n\n:::note\n**Note:** A module can have only one default export, but it can have multiple named exports.\n:::\n\n## How and When to Use 'export default'\n\n`export default` is typically used when a module only has one thing to export. This could be a function, a class, an object, or anything else that you want to be the main focus of the module. \n\nConsider a case where you have a module that exports a single function:\n\n```javascript\n// sayHello.js\nconst sayHello = name =\u003e `Hello, ${name}!`;\n\nexport default sayHello;\n```\n\nAnd then you import it in another module:\n\n```javascript\n// app.js\nimport sayHello from './sayHello.js';\n\nconsole.log(sayHello('StackAbuse readers')); // Output: Hello, StackAbuse readers!\n```\n\nIn this case, using 'export default' makes sense because `sayHello` is the only function that the `sayHello.js` module exports, thus we don't want to have to use a destructuring assignment to access the function.\n\nRemember, whether to use `export default` or named exports largely depends on how you want to structure your code. Both have their uses, and understanding when to use each is an important part of mastering JavaScript modules.\n\n## Common Errors with 'export default'\n\nSo what are some common pitfalls/errors that you might run into? Here we'll take a moment to discuss some possible mistakes. Depending on your level of experience with JS, you may run into one or more of the following issues.\n\nOne common mistake is trying to use `export default` more than once within the same module. Remember, `export default` is meant for a single value, be it a function, an object, or a variable. \n\n```javascript\n// Incorrect usage!\nexport default let name = \"John\";\nexport default let age = 25;\n```\n\nAnother common mistake is using curly braces `{}` with 'export default'. This is unnecessary and leads to syntax errors.\n\n```javascript\n// Incorrect usage!\nimport { myFunction } from './myModule.js';\n```\n\n:::note\n**Note:** The above syntax is used for named exports, not default exports.\n:::\n\n## Fixing 'export default' Errors\n\nNow that we've looked at some common pitfalls, let's talk about how to fix them.\n\nIf you're trying to export more than one value from a module using `export default`, consider combining them into an object.\n\n```javascript\n// Correct usage\nlet name = \"John\";\nlet age = 25;\nexport default { name, age };\n```\n\nAs for the second error, remember that `export default` doesn't require curly braces. The correct way to import a default export is as follows:\n\n```javascript\n// Correct usage\nimport myFunction from './myModule.js';\n```\n\n## Named Exports\n\nWhile `export default` is a convenient tool, it isn't the only way to export values from a JavaScript module. Named exports can be a good alternative, especially when you want to export multiple values.\n\nIn contrast to default exporting, named exports allow you to export multiple values, and each of these exports can be imported using the `{}` syntax.\n\n```javascript\n// Named exports\nexport const name = \"John\";\nexport const age = 25;\n```\n\nAnd they can be imported like so:\n\n```javascript\n// Importing named exports\nimport { name, age } from './myModule.js';\n```\n\n:::note\n**Note:** You can use both `export default` and named exports in the same module. However, a module can only have one `default`.\n:::\n\n## Conclusion\n\nIn this Byte, we've dug into the `export default` statement in JavaScript, explored some common errors, and learned how to fix them. We've also discussed named exports, a similar, yet distinct, concept. Hopefully now with a better understanding, you'll run into less exporting/importing issues in your JS code.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eIf you've been working with JavaScript, you've probably come across the term \u003ccode\u003eexport default\u003c/code\u003e and wondered what it is or how it works. This Byte is meant for developers with a basic understanding of JavaScript, who are looking to deepen their knowledge of the language's intricacies. We'll be taking a closer look at JavaScript modules and the concept of \u003ccode\u003eexport default\u003c/code\u003e. By the end, you should have a better understanding of how and when to use \u003ccode\u003eexport default\u003c/code\u003e in your code.\u003c/p\u003e\n\u003ch2 id=\"understandingjavascriptmodules\"\u003eUnderstanding JavaScript Modules\u003c/h2\u003e\n\u003cp\u003eJavaScript modules are self-contained pieces of code that can be exported and imported into other JavaScript files. They help in organizing code, making it more maintainable, and more reusable. JavaScript modules were introduced in ES6 and have since become a core part of modern JavaScript development.\u003c/p\u003e\n\u003cp\u003eConsider the following example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// mathFunctions.js\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e add = \u003cspan class=\"hljs-function\"\u003e(\u003cspan class=\"hljs-params\"\u003ea, b\u003c/span\u003e) =\u0026gt;\u003c/span\u003e a + b;\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e subtract = \u003cspan class=\"hljs-function\"\u003e(\u003cspan class=\"hljs-params\"\u003ea, b\u003c/span\u003e) =\u0026gt;\u003c/span\u003e a - b;\n\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e { add, subtract };\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn the code above, we have a module named \u003ccode\u003emathFunctions.js\u003c/code\u003e that exports two functions: \u003ccode\u003eadd\u003c/code\u003e and \u003ccode\u003esubtract\u003c/code\u003e.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// app.js\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e { add, subtract } \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./mathFunctions.js\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(add(\u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e)); \u003cspan class=\"hljs-comment\"\u003e// Output: 5\u003c/span\u003e\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(subtract(\u003cspan class=\"hljs-number\"\u003e5\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e)); \u003cspan class=\"hljs-comment\"\u003e// Output: 3\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn \u003ccode\u003eapp.js\u003c/code\u003e, we import the \u003ccode\u003eadd\u003c/code\u003e and \u003ccode\u003esubtract\u003c/code\u003e functions from \u003ccode\u003emathFunctions.js\u003c/code\u003e and use them as needed.\u003c/p\u003e\n\u003ch2 id=\"whatisexportdefault\"\u003eWhat is 'export default'?\u003c/h2\u003e\n\u003cp\u003e\u003ccode\u003eexport default\u003c/code\u003e is a syntax used in JavaScript modules to export a single entity (be it a function, object, or variable) as the \u003cem\u003edefault\u003c/em\u003e export from a module.\u003c/p\u003e\n\u003cp\u003eConsider the following example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// greeting.js\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e greeting = \u003cspan class=\"hljs-string\"\u003e\u0026#x27;Hello, StackAbuse readers!\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003edefault\u003c/span\u003e greeting;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn the code above, we have a module named \u003ccode\u003egreeting.js\u003c/code\u003e that exports a single string \u003ccode\u003egreeting\u003c/code\u003e as the default export.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// app.js\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e greeting \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./greeting.js\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(greeting); \u003cspan class=\"hljs-comment\"\u003e// Output: Hello, StackAbuse readers!\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn \u003ccode\u003eapp.js\u003c/code\u003e, we import the default export from \u003ccode\u003egreeting.js\u003c/code\u003e and use it as needed. \u003cstrong\u003eNotice how we didn't use curly braces \u003ccode\u003e{}\u003c/code\u003e to import the default export.\u003c/strong\u003e This is the purpose of the \u003ccode\u003edefault\u003c/code\u003e keyword.\u003c/p\u003e\n\u003cp\u003eThis is similar to how you'd use \u003ccode\u003eexports.greeting = ...\u003c/code\u003e vs \u003ccode\u003emodule.exports = ...\u003c/code\u003e in Node.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e A module can have only one default export, but it can have multiple named exports.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"howandwhentouseexportdefault\"\u003eHow and When to Use 'export default'\u003c/h2\u003e\n\u003cp\u003e\u003ccode\u003eexport default\u003c/code\u003e is typically used when a module only has one thing to export. This could be a function, a class, an object, or anything else that you want to be the main focus of the module.\u003c/p\u003e\n\u003cp\u003eConsider a case where you have a module that exports a single function:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// sayHello.js\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e sayHello = \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-params\"\u003ename\u003c/span\u003e =\u0026gt;\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e`Hello, \u003cspan class=\"hljs-subst\"\u003e${name}\u003c/span\u003e!`\u003c/span\u003e;\n\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003edefault\u003c/span\u003e sayHello;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnd then you import it in another module:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// app.js\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e sayHello \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./sayHello.js\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(sayHello(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;StackAbuse readers\u0026#x27;\u003c/span\u003e)); \u003cspan class=\"hljs-comment\"\u003e// Output: Hello, StackAbuse readers!\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this case, using 'export default' makes sense because \u003ccode\u003esayHello\u003c/code\u003e is the only function that the \u003ccode\u003esayHello.js\u003c/code\u003e module exports, thus we don't want to have to use a destructuring assignment to access the function.\u003c/p\u003e\n\u003cp\u003eRemember, whether to use \u003ccode\u003eexport default\u003c/code\u003e or named exports largely depends on how you want to structure your code. Both have their uses, and understanding when to use each is an important part of mastering JavaScript modules.\u003c/p\u003e\n\u003ch2 id=\"commonerrorswithexportdefault\"\u003eCommon Errors with 'export default'\u003c/h2\u003e\n\u003cp\u003eSo what are some common pitfalls/errors that you might run into? Here we'll take a moment to discuss some possible mistakes. Depending on your level of experience with JS, you may run into one or more of the following issues.\u003c/p\u003e\n\u003cp\u003eOne common mistake is trying to use \u003ccode\u003eexport default\u003c/code\u003e more than once within the same module. Remember, \u003ccode\u003eexport default\u003c/code\u003e is meant for a single value, be it a function, an object, or a variable.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Incorrect usage!\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003edefault\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e name = \u003cspan class=\"hljs-string\"\u003e\u0026quot;John\u0026quot;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003edefault\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e age = \u003cspan class=\"hljs-number\"\u003e25\u003c/span\u003e;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnother common mistake is using curly braces \u003ccode\u003e{}\u003c/code\u003e with 'export default'. This is unnecessary and leads to syntax errors.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Incorrect usage!\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e { myFunction } \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./myModule.js\u0026#x27;\u003c/span\u003e;\n\u003c/code\u003e\u003c/pre\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e The above syntax is used for named exports, not default exports.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"fixingexportdefaulterrors\"\u003eFixing 'export default' Errors\u003c/h2\u003e\n\u003cp\u003eNow that we've looked at some common pitfalls, let's talk about how to fix them.\u003c/p\u003e\n\u003cp\u003eIf you're trying to export more than one value from a module using \u003ccode\u003eexport default\u003c/code\u003e, consider combining them into an object.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Correct usage\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e name = \u003cspan class=\"hljs-string\"\u003e\u0026quot;John\u0026quot;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e age = \u003cspan class=\"hljs-number\"\u003e25\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003edefault\u003c/span\u003e { name, age };\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAs for the second error, remember that \u003ccode\u003eexport default\u003c/code\u003e doesn't require curly braces. The correct way to import a default export is as follows:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Correct usage\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e myFunction \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./myModule.js\u0026#x27;\u003c/span\u003e;\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"namedexports\"\u003eNamed Exports\u003c/h2\u003e\n\u003cp\u003eWhile \u003ccode\u003eexport default\u003c/code\u003e is a convenient tool, it isn't the only way to export values from a JavaScript module. Named exports can be a good alternative, especially when you want to export multiple values.\u003c/p\u003e\n\u003cp\u003eIn contrast to default exporting, named exports allow you to export multiple values, and each of these exports can be imported using the \u003ccode\u003e{}\u003c/code\u003e syntax.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Named exports\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e name = \u003cspan class=\"hljs-string\"\u003e\u0026quot;John\u0026quot;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003eexport\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e age = \u003cspan class=\"hljs-number\"\u003e25\u003c/span\u003e;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnd they can be imported like so:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Importing named exports\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e { name, age } \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./myModule.js\u0026#x27;\u003c/span\u003e;\n\u003c/code\u003e\u003c/pre\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e You can use both \u003ccode\u003eexport default\u003c/code\u003e and named exports in the same module. However, a module can only have one \u003ccode\u003edefault\u003c/code\u003e.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've dug into the \u003ccode\u003eexport default\u003c/code\u003e statement in JavaScript, explored some common errors, and learned how to fix them. We've also discussed named exports, a similar, yet distinct, concept. Hopefully now with a better understanding, you'll run into less exporting/importing issues in your JS code.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":15,"published_by":1,"published_at":1697043314607,"created_by":1,"updated_by":null,"created_at":1697042210916,"updated_at":1697043314609,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2116,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2116,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":48,"name":"node","slug":"node","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2116,"_pivot_tag_id":48,"_pivot_sort_order":1},{"id":50,"name":"es6","slug":"es6","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2116,"_pivot_tag_id":50,"_pivot_sort_order":2}],"_pivot_tag_id":45,"_pivot_content_id":2116},{"id":2114,"old_id":null,"uuid":"6ada1ad5-a445-4059-9218-568fa74358b5","title":"How to Add/Remove Multiple Classes to an Element in JavaScript","slug":"how-to-add-remove-multiple-classes-to-an-element-in-javascript","body_md":"## Introduction\n\nIn this Byte you'll learn a bit about the importance of CSS classes and how to manipulate them using both vanilla JavaScript and jQuery. By the end, you'll be able to dynamically alter the appearance and behavior of your web elements with ease. Let's get started!\n\n## CSS Classes\n\nAs you probably know, CSS classes play an important role in web development. They allow you to define a style once and then apply it to multiple elements across your website, ensuring consistency and reducing repetition. For instance, you might have a `.highlight` class that changes the background color of an element to yellow. To apply this style, you simply add the class to the desired elements in your HTML.\n\n```html\n\u003cdiv class=\"highlight\"\u003eThis is a highlighted text.\u003c/div\u003e\n```\n\nHowever, what if you want to add or remove classes dynamically, based on user interaction or some other condition? That's where we'll be using JavaScript.\n\n## Why Manipulate CSS Classes with JavaScript\n\nWhile CSS is great for static styles, JavaScript allows us to make our web pages dynamic and interactive. By manipulating CSS classes with JavaScript, you can change the look and behavior of elements on-the-fly. This is something that isn't possible without the use of JS.\n\nFor example, you might want to add a `.active` class to a navigation link when it's clicked, or remove a `.hidden` class from a modal when a button is pressed. This dynamic manipulation of classes can greatly enhance the user experience of a website.\n\nIn the next few sections we'll see how to actually do this in JS using a few different methods.\n\n## Vanilla JavaScript\n\nIn vanilla JavaScript, you can add or remove classes using the `classList` property of an element. This property returns a live `DOMTokenList` collection of the class attributes of the element.\n\n### Adding Multiple Classes\n\nTo add multiple classes, you can use the `add` method of `classList`. This method can accept multiple arguments, each one being a class you want to add. If a specified class already exists on the element, it will not be added again.\n\nHere's an example:\n\n```javascript\nlet element = document.querySelector(\"#myElement\");\nelement.classList.add(\"class1\", \"class2\", \"class3\");\n```\n\nAfter running this code, the element with the `id` \"myElement\" will have the classes `class1`, `class2`, and `class3` added to it.\n\n### Removing Multiple Classes\n\nSimilarly, to remove multiple classes, you can use the `remove` method of `classList`. This method also accepts multiple arguments, each one a class to be removed. If a specified class does not exist on the element, it will be ignored. This is a nice feature as it provides some built-in \"safety\" and doesn't throw an error.\n\nHere's how you can do it:\n\n```javascript\nlet element = document.querySelector(\"#myElement\");\nelement.classList.remove(\"class1\", \"class2\", \"class3\");\n```\n\nAfter running this code, the classes `class1`, `class2`, and `class3` will be removed from the element with the `id` \"myElement\".\n\nIn the next sections, we'll cover how to achieve the same results using jQuery.\n\n## jQuery\n\njQuery, a popular JavaScript library, provides its own methods for adding and removing classes. If you're already using jQuery in your project, these methods can provide a more concise syntax for class manipulation.\n\n### Adding Multiple Classes\n\nTo add multiple classes with jQuery, you use the `addClass()` method. Here's how it looks:\n\n```javascript\n$(\"#myElement\").addClass(\"class1 class2 class3\");\n```\n\nThis code adds the classes `class1`, `class2`, and `class3` to the element with the ID `myElement`. Unlike the `classList.add()` method in vanilla JavaScript, the `addClass()` method in jQuery takes a single string argument, with individual class names separated by spaces.\n\n### Removing Multiple Classes\n\nAgain, for jQuery, the process is quite similar as in plain JS. The `removeClass()` method is used, and the class names are passed as a space-separated string:\n\n```javascript\n// Select the element\nlet element = $(\"#myElement\");\n\n// Remove multiple classes\nelement.removeClass(\"class1 class2 class3\");\n```\n\nIn this case, we're using jQuery to select the element with the `id` \"myElement\" and remove \"class1\", \"class2\", and \"class3\" from it. Again, if the classes don't exist, `removeClass()` will just carry on its way and ignore the missing class.\n\n## Use Cases and Applications\n\nManipulating CSS classes with JavaScript has a wide range of applications, some of which we touched on earlier. It's a common technique for adding dynamic behavior to websites. For example, you might have a navigation menu that changes style when the user scrolls down. This can be done by adding or removing classes that control the appearance of the menu.\n\nAnother common use case is form validation. You may have a form where the user has to input a valid email address. If the user inputs an invalid email, you could add a class to the input field that changes its border to red. If the user corrects their mistake, you could remove the class to revert the border color.\n\nIn interactive web applications, you might have elements that change appearance based on user actions or data changes. Like a button could have different styles depending on whether it's enabled or disabled. By adding or removing classes, you can control these styles directly from your JavaScript code.\n\n## Conclusion\n\nIn this Byte, we've learned how to add and remove multiple CSS classes to an element using both vanilla JavaScript and jQuery. We've seen that this can be done using the `classList` property in JavaScript and the `addClass()` and `removeClass()` methods in jQuery. We've also explained some practical applications of these techniques, like dynamic styling and form validation.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eIn this Byte you'll learn a bit about the importance of CSS classes and how to manipulate them using both vanilla JavaScript and jQuery. By the end, you'll be able to dynamically alter the appearance and behavior of your web elements with ease. Let's get started!\u003c/p\u003e\n\u003ch2 id=\"cssclasses\"\u003eCSS Classes\u003c/h2\u003e\n\u003cp\u003eAs you probably know, CSS classes play an important role in web development. They allow you to define a style once and then apply it to multiple elements across your website, ensuring consistency and reducing repetition. For instance, you might have a \u003ccode\u003e.highlight\u003c/code\u003e class that changes the background color of an element to yellow. To apply this style, you simply add the class to the desired elements in your HTML.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ediv\u003c/span\u003e \u003cspan class=\"hljs-attr\"\u003eclass\u003c/span\u003e=\u003cspan class=\"hljs-string\"\u003e\u0026quot;highlight\u0026quot;\u003c/span\u003e\u0026gt;\u003c/span\u003eThis is a highlighted text.\u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ediv\u003c/span\u003e\u0026gt;\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHowever, what if you want to add or remove classes dynamically, based on user interaction or some other condition? That's where we'll be using JavaScript.\u003c/p\u003e\n\u003ch2 id=\"whymanipulatecssclasseswithjavascript\"\u003eWhy Manipulate CSS Classes with JavaScript\u003c/h2\u003e\n\u003cp\u003eWhile CSS is great for static styles, JavaScript allows us to make our web pages dynamic and interactive. By manipulating CSS classes with JavaScript, you can change the look and behavior of elements on-the-fly. This is something that isn't possible without the use of JS.\u003c/p\u003e\n\u003cp\u003eFor example, you might want to add a \u003ccode\u003e.active\u003c/code\u003e class to a navigation link when it's clicked, or remove a \u003ccode\u003e.hidden\u003c/code\u003e class from a modal when a button is pressed. This dynamic manipulation of classes can greatly enhance the user experience of a website.\u003c/p\u003e\n\u003cp\u003eIn the next few sections we'll see how to actually do this in JS using a few different methods.\u003c/p\u003e\n\u003ch2 id=\"vanillajavascript\"\u003eVanilla JavaScript\u003c/h2\u003e\n\u003cp\u003eIn vanilla JavaScript, you can add or remove classes using the \u003ccode\u003eclassList\u003c/code\u003e property of an element. This property returns a live \u003ccode\u003eDOMTokenList\u003c/code\u003e collection of the class attributes of the element.\u003c/p\u003e\n\u003ch3 id=\"addingmultipleclasses\"\u003eAdding Multiple Classes\u003c/h3\u003e\n\u003cp\u003eTo add multiple classes, you can use the \u003ccode\u003eadd\u003c/code\u003e method of \u003ccode\u003eclassList\u003c/code\u003e. This method can accept multiple arguments, each one being a class you want to add. If a specified class already exists on the element, it will not be added again.\u003c/p\u003e\n\u003cp\u003eHere's an example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e element = \u003cspan class=\"hljs-built_in\"\u003edocument\u003c/span\u003e.querySelector(\u003cspan class=\"hljs-string\"\u003e\u0026quot;#myElement\u0026quot;\u003c/span\u003e);\nelement.classList.add(\u003cspan class=\"hljs-string\"\u003e\u0026quot;class1\u0026quot;\u003c/span\u003e, \u003cspan class=\"hljs-string\"\u003e\u0026quot;class2\u0026quot;\u003c/span\u003e, \u003cspan class=\"hljs-string\"\u003e\u0026quot;class3\u0026quot;\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAfter running this code, the element with the \u003ccode\u003eid\u003c/code\u003e \u0026quot;myElement\u0026quot; will have the classes \u003ccode\u003eclass1\u003c/code\u003e, \u003ccode\u003eclass2\u003c/code\u003e, and \u003ccode\u003eclass3\u003c/code\u003e added to it.\u003c/p\u003e\n\u003ch3 id=\"removingmultipleclasses\"\u003eRemoving Multiple Classes\u003c/h3\u003e\n\u003cp\u003eSimilarly, to remove multiple classes, you can use the \u003ccode\u003eremove\u003c/code\u003e method of \u003ccode\u003eclassList\u003c/code\u003e. This method also accepts multiple arguments, each one a class to be removed. If a specified class does not exist on the element, it will be ignored. This is a nice feature as it provides some built-in \u0026quot;safety\u0026quot; and doesn't throw an error.\u003c/p\u003e\n\u003cp\u003eHere's how you can do it:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e element = \u003cspan class=\"hljs-built_in\"\u003edocument\u003c/span\u003e.querySelector(\u003cspan class=\"hljs-string\"\u003e\u0026quot;#myElement\u0026quot;\u003c/span\u003e);\nelement.classList.remove(\u003cspan class=\"hljs-string\"\u003e\u0026quot;class1\u0026quot;\u003c/span\u003e, \u003cspan class=\"hljs-string\"\u003e\u0026quot;class2\u0026quot;\u003c/span\u003e, \u003cspan class=\"hljs-string\"\u003e\u0026quot;class3\u0026quot;\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAfter running this code, the classes \u003ccode\u003eclass1\u003c/code\u003e, \u003ccode\u003eclass2\u003c/code\u003e, and \u003ccode\u003eclass3\u003c/code\u003e will be removed from the element with the \u003ccode\u003eid\u003c/code\u003e \u0026quot;myElement\u0026quot;.\u003c/p\u003e\n\u003cp\u003eIn the next sections, we'll cover how to achieve the same results using jQuery.\u003c/p\u003e\n\u003ch2 id=\"jquery\"\u003ejQuery\u003c/h2\u003e\n\u003cp\u003ejQuery, a popular JavaScript library, provides its own methods for adding and removing classes. If you're already using jQuery in your project, these methods can provide a more concise syntax for class manipulation.\u003c/p\u003e\n\u003ch3 id=\"addingmultipleclasses\"\u003eAdding Multiple Classes\u003c/h3\u003e\n\u003cp\u003eTo add multiple classes with jQuery, you use the \u003ccode\u003eaddClass()\u003c/code\u003e method. Here's how it looks:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e$(\u003cspan class=\"hljs-string\"\u003e\u0026quot;#myElement\u0026quot;\u003c/span\u003e).addClass(\u003cspan class=\"hljs-string\"\u003e\u0026quot;class1 class2 class3\u0026quot;\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis code adds the classes \u003ccode\u003eclass1\u003c/code\u003e, \u003ccode\u003eclass2\u003c/code\u003e, and \u003ccode\u003eclass3\u003c/code\u003e to the element with the ID \u003ccode\u003emyElement\u003c/code\u003e. Unlike the \u003ccode\u003eclassList.add()\u003c/code\u003e method in vanilla JavaScript, the \u003ccode\u003eaddClass()\u003c/code\u003e method in jQuery takes a single string argument, with individual class names separated by spaces.\u003c/p\u003e\n\u003ch3 id=\"removingmultipleclasses\"\u003eRemoving Multiple Classes\u003c/h3\u003e\n\u003cp\u003eAgain, for jQuery, the process is quite similar as in plain JS. The \u003ccode\u003eremoveClass()\u003c/code\u003e method is used, and the class names are passed as a space-separated string:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-comment\"\u003e// Select the element\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e element = $(\u003cspan class=\"hljs-string\"\u003e\u0026quot;#myElement\u0026quot;\u003c/span\u003e);\n\n\u003cspan class=\"hljs-comment\"\u003e// Remove multiple classes\u003c/span\u003e\nelement.removeClass(\u003cspan class=\"hljs-string\"\u003e\u0026quot;class1 class2 class3\u0026quot;\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this case, we're using jQuery to select the element with the \u003ccode\u003eid\u003c/code\u003e \u0026quot;myElement\u0026quot; and remove \u0026quot;class1\u0026quot;, \u0026quot;class2\u0026quot;, and \u0026quot;class3\u0026quot; from it. Again, if the classes don't exist, \u003ccode\u003eremoveClass()\u003c/code\u003e will just carry on its way and ignore the missing class.\u003c/p\u003e\n\u003ch2 id=\"usecasesandapplications\"\u003eUse Cases and Applications\u003c/h2\u003e\n\u003cp\u003eManipulating CSS classes with JavaScript has a wide range of applications, some of which we touched on earlier. It's a common technique for adding dynamic behavior to websites. For example, you might have a navigation menu that changes style when the user scrolls down. This can be done by adding or removing classes that control the appearance of the menu.\u003c/p\u003e\n\u003cp\u003eAnother common use case is form validation. You may have a form where the user has to input a valid email address. If the user inputs an invalid email, you could add a class to the input field that changes its border to red. If the user corrects their mistake, you could remove the class to revert the border color.\u003c/p\u003e\n\u003cp\u003eIn interactive web applications, you might have elements that change appearance based on user actions or data changes. Like a button could have different styles depending on whether it's enabled or disabled. By adding or removing classes, you can control these styles directly from your JavaScript code.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've learned how to add and remove multiple CSS classes to an element using both vanilla JavaScript and jQuery. We've seen that this can be done using the \u003ccode\u003eclassList\u003c/code\u003e property in JavaScript and the \u003ccode\u003eaddClass()\u003c/code\u003e and \u003ccode\u003eremoveClass()\u003c/code\u003e methods in jQuery. We've also explained some practical applications of these techniques, like dynamic styling and form validation.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":14,"published_by":1,"published_at":1696886590386,"created_by":1,"updated_by":null,"created_at":1696879326438,"updated_at":1696886590388,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2114,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2114,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":196,"name":"web development","slug":"web-development","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1601641448000,"updated_at":1601641448000,"_pivot_content_id":2114,"_pivot_tag_id":196,"_pivot_sort_order":2},{"id":267,"name":"jquery","slug":"jquery","img_cover":null,"description_md":"","description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":1,"updated_by":null,"created_at":1692997806624,"updated_at":1692997806624,"_pivot_content_id":2114,"_pivot_tag_id":267,"_pivot_sort_order":1}],"_pivot_tag_id":45,"_pivot_content_id":2114},{"id":2113,"old_id":null,"uuid":"bf211aba-03e9-4c96-8736-8ab9bdcc1a30","title":"How to Add/Remove an Event Listener in React","slug":"how-to-add-remove-an-event-listener-in-react","body_md":"## Introduction\n\nIf you've been working with React, you would know that it's a powerful JavaScript library for building user interfaces. But sometimes, you need to go beyond the basic click and change events. This is where event listeners come into play. This Byte is ideal for developers who are familiar with React and want to dive deeper into how event listeners work and how to manage them effectively.\n\n## Event Listeners in React\n\nBefore we get going, it's important to understand what event listeners are. In JavaScript, event listeners are functions that are called when a specified event occurs. These events could be anything from clicking a button, pressing a key, to resizing a window.\n\nReact, being a JavaScript library, also uses event listeners to handle user interactions. However, unlike vanilla JavaScript, React wraps the native event into a `SyntheticEvent`. This provides a cross-browser interface to the native event, ensuring that the event behaves consistently across all browsers.\n\nHere's a simple example of an event listener in React:\n\n```jsx\nconst MyComponent = () =\u003e {\n const handleClick = () =\u003e {\n console.log('Button clicked!');\n };\n\n return (\n \u003cbutton onClick={handleClick}\u003e\n Click Me\n \u003c/button\u003e\n );\n};\n```\n\nIn this example, `handleClick` is an event listener that logs \"Button clicked!\" to the console when the button is clicked. This is, effectively, an event listener on the `\u003cbutton\u003e` component.\n\n## Why Add/Remove an Event Listener?\n\nSo why can't we just leave the event listener attached?\n\nWell, the reason is twofold. First, adding and removing event listeners as needed can significantly improve the performance of your application. Event listeners can be quite expensive in terms of memory and processing power, especially if you have a lot of them.\n\nSecond, removing event listeners when they're no longer needed can help prevent memory leaks. A memory leak can happen when an application continues to use memory that it no longer needs. Over time, these leaks can cause your application to slow down or even crash. \n\n## How to Add/Remove an Event Listener\n\nNow that we have a bit of background on managing event listeners, let's see how to add and remove them in React.\n\n### Adding an Event Listener\n\nTo add an event listener, you simply need to specify the event and the function to call when the event occurs. This is typically done in the `render` method of your component, like this:\n\n```jsx\nconst MyForm = () =\u003e {\n handleSubmit = () =\u003e {\n console.log('Form submitted!');\n }\n\n render() {\n return (\n \u003cform onSubmit={handleSubmit}\u003e\n \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n \u003c/form\u003e\n );\n }\n}\n```\n\nHere, we're adding an event listener for the `submit` event. The `handleSubmit` function will be called whenever the button is clicked.\n\n### Removing an Event Listener\n\nIn this section we'll be adding/removing event listeners a bit differently in order to better illustrate the point and other ways to do this.\n\nIn this component, we add an event listener with `addEventListener` when it's mounted using `useEffect`. As the lifecycle of the component progresses and it is being unmounted, we can then remove the event listener by returning a function from `useEffect` that handles the removal with `removeEventListener`.\n\n```jsx\nimport React, { useEffect } from 'react';\n\nconst MyComponent = () =\u003e {\n const handleClick = () =\u003e {\n console.log('Button clicked!');\n };\n\n useEffect(() =\u003e {\n // Equivalent to componentDidMount\n document.addEventListener('click', handleClick);\n\n // Equivalent to componentWillUnmount\n return () =\u003e {\n document.removeEventListener('click', handleClick);\n };\n }, []);\n\n return (\n \u003cbutton\u003e\n Click Me\n \u003c/button\u003e\n );\n};\n```\n\nWhile this isn't necessarily the recommended way to add click handlers to a component, it does show a bit more of how the lifecycle works for a component and how we'd use that lifecycle to add or remove our listeners.\n\n:::note\n**Note:** It's important to ensure that the function passed to `removeEventListener` is the same function that was passed to `addEventListener`. If you pass a different function, the event listener will not be removed.\n:::\n\n## Potential Issues and Their Solutions\n\nWhile working with event listeners in React, you might encounter some common issues. Let's go over a few and discuss how to solve them.\n\n**1. `this` is undefined:** This issue is due to JavaScript's rules around `this`. In JavaScript, `this` inside an event handler refers to the target of the event, not the instance of the class, which trips up a lot of developers. To fix this, you need to bind `this` to the event handler. This can be done in the constructor:\n\n```jsx\nclass MyButton extends React.Component {\n constructor(props) {\n super(props);\n this.handleClick = this.handleClick.bind(this);\n }\n\n handleClick() {\n alert('Button has been clicked!');\n }\n\n render() {\n return (\n \u003cbutton onClick={this.handleClick}\u003e\n Click me!\n \u003c/button\u003e\n );\n }\n}\n```\n\n**2. Event listener not removed:** If you forget to remove an event listener, it can lead to memory leaks and errors. Always remember to remove global event listeners in the `useEffect` lifecycle method, or `componentWillUnmount` for old-style components.\n\n**3. Event listener added multiple times:** If an event listener is added every time a component updates, it can lead to unexpected behavior. To prevent this, add event listeners in the `useEffect` method with no state variables, or in `componentDidMount` for old components. These are only called once, when the component is first added to the DOM.\n\n## Using useEffect Hook for Event Listener Management\n\nLet's take another quick look at the `useEffect` hook, which is a powerful tool that allows us to manage side effects in our components. Side effects can be anything that interacts with the outside of the component, like fetching data, timers, and of course, event listeners.\n\nTo add an event listener using `useEffect`, we first declare the function that will be called when the event occurs. Then, inside `useEffect`, we add the event listener, and return a cleanup function that removes the event listener. This is how it looks in code:\n\n```jsx\nimport React, { useEffect } from 'react';\n\nfunction MyComponent() {\n useEffect(() =\u003e {\n function handleResize() {\n console.log(window.innerWidth);\n }\n\n window.addEventListener('resize', handleResize);\n\n return () =\u003e {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return \u003cdiv\u003eResize the window and check the console!\u003c/div\u003e;\n}\n```\n\nIn this code, `handleResize` logs the window's inner width whenever the window is resized. The event listener is added when the component mounts, and removed when it unmounts, thanks to `useEffect`'s cleanup function.\n\n## Use Cases for Adding/Removing Event Listeners\n\nThere are tons of scenarios where you might need to add or remove event listeners in a React application. For example, you might want to add a \"click\" event listener to a button to trigger a specific action when the user interacts with it. Or, you might want to listen to the \"resize\" event on the window object to dynamically adjust the layout of your application based on the viewport size.\n\nAnother common use case is listening to keyboard events. For example, you might want to capture the \"keydown\" event to implement keyboard shortcuts in your application. Here's a simple example along those lines:\n\n```jsx\nimport React, { useEffect } from 'react';\n\nfunction MyComponent() {\n useEffect(() =\u003e {\n function handleKeyDown(event) {\n if (event.key === 'Enter') {\n console.log('Enter key pressed!');\n }\n }\n\n window.addEventListener('keydown', handleKeyDown);\n\n return () =\u003e {\n window.removeEventListener('keydown', handleKeyDown);\n };\n }, []);\n\n return \u003cdiv\u003ePress the Enter key and check the console!\u003c/div\u003e;\n}\n```\n\nHere we've added an event listener for the \"keydown\" event. When the user presses the \u003ckbd\u003eEnter\u003c/kbd\u003e key, a message is logged to the console.\n\n## Conclusion\n\nIn this Byte, we've explored how to add and remove event listeners in a React application. We've learned that React's `useEffect` hook is a powerful tool for managing event listeners, allowing us to add them when a component mounts and remove them when it unmounts. We've also looked at some common use cases for adding and removing event listeners, such as responding to user interaction or changes in the viewport size.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eIf you've been working with React, you would know that it's a powerful JavaScript library for building user interfaces. But sometimes, you need to go beyond the basic click and change events. This is where event listeners come into play. This Byte is ideal for developers who are familiar with React and want to dive deeper into how event listeners work and how to manage them effectively.\u003c/p\u003e\n\u003ch2 id=\"eventlistenersinreact\"\u003eEvent Listeners in React\u003c/h2\u003e\n\u003cp\u003eBefore we get going, it's important to understand what event listeners are. In JavaScript, event listeners are functions that are called when a specified event occurs. These events could be anything from clicking a button, pressing a key, to resizing a window.\u003c/p\u003e\n\u003cp\u003eReact, being a JavaScript library, also uses event listeners to handle user interactions. However, unlike vanilla JavaScript, React wraps the native event into a \u003ccode\u003eSyntheticEvent\u003c/code\u003e. This provides a cross-browser interface to the native event, ensuring that the event behaves consistently across all browsers.\u003c/p\u003e\n\u003cp\u003eHere's a simple example of an event listener in React:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e MyComponent = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e handleClick = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Button clicked!\u0026#x27;\u003c/span\u003e);\n };\n\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e (\n \u003cspan class=\"xml\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e \u003cspan class=\"hljs-attr\"\u003eonClick\u003c/span\u003e=\u003cspan class=\"hljs-string\"\u003e{handleClick}\u003c/span\u003e\u0026gt;\u003c/span\u003e\n Click Me\n \u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e\u0026gt;\u003c/span\u003e\u003c/span\u003e\n );\n};\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this example, \u003ccode\u003ehandleClick\u003c/code\u003e is an event listener that logs \u0026quot;Button clicked!\u0026quot; to the console when the button is clicked. This is, effectively, an event listener on the \u003ccode\u003e\u0026lt;button\u0026gt;\u003c/code\u003e component.\u003c/p\u003e\n\u003ch2 id=\"whyaddremoveaneventlistener\"\u003eWhy Add/Remove an Event Listener?\u003c/h2\u003e\n\u003cp\u003eSo why can't we just leave the event listener attached?\u003c/p\u003e\n\u003cp\u003eWell, the reason is twofold. First, adding and removing event listeners as needed can significantly improve the performance of your application. Event listeners can be quite expensive in terms of memory and processing power, especially if you have a lot of them.\u003c/p\u003e\n\u003cp\u003eSecond, removing event listeners when they're no longer needed can help prevent memory leaks. A memory leak can happen when an application continues to use memory that it no longer needs. Over time, these leaks can cause your application to slow down or even crash.\u003c/p\u003e\n\u003ch2 id=\"howtoaddremoveaneventlistener\"\u003eHow to Add/Remove an Event Listener\u003c/h2\u003e\n\u003cp\u003eNow that we have a bit of background on managing event listeners, let's see how to add and remove them in React.\u003c/p\u003e\n\u003ch3 id=\"addinganeventlistener\"\u003eAdding an Event Listener\u003c/h3\u003e\n\u003cp\u003eTo add an event listener, you simply need to specify the event and the function to call when the event occurs. This is typically done in the \u003ccode\u003erender\u003c/code\u003e method of your component, like this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e MyForm = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n handleSubmit = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Form submitted!\u0026#x27;\u003c/span\u003e);\n }\n\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-title\"\u003erender\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e)\u003c/span\u003e {\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e (\n \u003cspan class=\"xml\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003eform\u003c/span\u003e \u003cspan class=\"hljs-attr\"\u003eonSubmit\u003c/span\u003e=\u003cspan class=\"hljs-string\"\u003e{handleSubmit}\u003c/span\u003e\u0026gt;\u003c/span\u003e\n \u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e \u003cspan class=\"hljs-attr\"\u003etype\u003c/span\u003e=\u003cspan class=\"hljs-string\"\u003e\u0026quot;submit\u0026quot;\u003c/span\u003e\u0026gt;\u003c/span\u003eSubmit\u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e\u0026gt;\u003c/span\u003e\n \u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003eform\u003c/span\u003e\u0026gt;\u003c/span\u003e\u003c/span\u003e\n );\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHere, we're adding an event listener for the \u003ccode\u003esubmit\u003c/code\u003e event. The \u003ccode\u003ehandleSubmit\u003c/code\u003e function will be called whenever the button is clicked.\u003c/p\u003e\n\u003ch3 id=\"removinganeventlistener\"\u003eRemoving an Event Listener\u003c/h3\u003e\n\u003cp\u003eIn this section we'll be adding/removing event listeners a bit differently in order to better illustrate the point and other ways to do this.\u003c/p\u003e\n\u003cp\u003eIn this component, we add an event listener with \u003ccode\u003eaddEventListener\u003c/code\u003e when it's mounted using \u003ccode\u003euseEffect\u003c/code\u003e. As the lifecycle of the component progresses and it is being unmounted, we can then remove the event listener by returning a function from \u003ccode\u003euseEffect\u003c/code\u003e that handles the removal with \u003ccode\u003eremoveEventListener\u003c/code\u003e.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e React, { useEffect } \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;react\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e MyComponent = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-keyword\"\u003econst\u003c/span\u003e handleClick = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Button clicked!\u0026#x27;\u003c/span\u003e);\n };\n\n useEffect(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-comment\"\u003e// Equivalent to componentDidMount\u003c/span\u003e\n \u003cspan class=\"hljs-built_in\"\u003edocument\u003c/span\u003e.addEventListener(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;click\u0026#x27;\u003c/span\u003e, handleClick);\n\n \u003cspan class=\"hljs-comment\"\u003e// Equivalent to componentWillUnmount\u003c/span\u003e\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003edocument\u003c/span\u003e.removeEventListener(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;click\u0026#x27;\u003c/span\u003e, handleClick);\n };\n }, []);\n\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e (\n \u003cspan class=\"xml\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e\u0026gt;\u003c/span\u003e\n Click Me\n \u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e\u0026gt;\u003c/span\u003e\u003c/span\u003e\n );\n};\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eWhile this isn't necessarily the recommended way to add click handlers to a component, it does show a bit more of how the lifecycle works for a component and how we'd use that lifecycle to add or remove our listeners.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e It's important to ensure that the function passed to \u003ccode\u003eremoveEventListener\u003c/code\u003e is the same function that was passed to \u003ccode\u003eaddEventListener\u003c/code\u003e. If you pass a different function, the event listener will not be removed.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"potentialissuesandtheirsolutions\"\u003ePotential Issues and Their Solutions\u003c/h2\u003e\n\u003cp\u003eWhile working with event listeners in React, you might encounter some common issues. Let's go over a few and discuss how to solve them.\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003e1. \u003ccode\u003ethis\u003c/code\u003e is undefined:\u003c/strong\u003e This issue is due to JavaScript's rules around \u003ccode\u003ethis\u003c/code\u003e. In JavaScript, \u003ccode\u003ethis\u003c/code\u003e inside an event handler refers to the target of the event, not the instance of the class, which trips up a lot of developers. To fix this, you need to bind \u003ccode\u003ethis\u003c/code\u003e to the event handler. This can be done in the constructor:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eMyButton\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003eextends\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eReact\u003c/span\u003e.\u003cspan class=\"hljs-title\"\u003eComponent\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-title\"\u003econstructor\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003eprops\u003c/span\u003e)\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003esuper\u003c/span\u003e(props);\n \u003cspan class=\"hljs-built_in\"\u003ethis\u003c/span\u003e.handleClick = \u003cspan class=\"hljs-built_in\"\u003ethis\u003c/span\u003e.handleClick.bind(\u003cspan class=\"hljs-built_in\"\u003ethis\u003c/span\u003e);\n }\n\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-title\"\u003ehandleClick\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e)\u003c/span\u003e {\n alert(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Button has been clicked!\u0026#x27;\u003c/span\u003e);\n }\n\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-title\"\u003erender\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e)\u003c/span\u003e {\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e (\n \u003cspan class=\"xml\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e \u003cspan class=\"hljs-attr\"\u003eonClick\u003c/span\u003e=\u003cspan class=\"hljs-string\"\u003e{this.handleClick}\u003c/span\u003e\u0026gt;\u003c/span\u003e\n Click me!\n \u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ebutton\u003c/span\u003e\u0026gt;\u003c/span\u003e\u003c/span\u003e\n );\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003e\u003cstrong\u003e2. Event listener not removed:\u003c/strong\u003e If you forget to remove an event listener, it can lead to memory leaks and errors. Always remember to remove global event listeners in the \u003ccode\u003euseEffect\u003c/code\u003e lifecycle method, or \u003ccode\u003ecomponentWillUnmount\u003c/code\u003e for old-style components.\u003c/p\u003e\n\u003cp\u003e\u003cstrong\u003e3. Event listener added multiple times:\u003c/strong\u003e If an event listener is added every time a component updates, it can lead to unexpected behavior. To prevent this, add event listeners in the \u003ccode\u003euseEffect\u003c/code\u003e method with no state variables, or in \u003ccode\u003ecomponentDidMount\u003c/code\u003e for old components. These are only called once, when the component is first added to the DOM.\u003c/p\u003e\n\u003ch2 id=\"usinguseeffecthookforeventlistenermanagement\"\u003eUsing useEffect Hook for Event Listener Management\u003c/h2\u003e\n\u003cp\u003eLet's take another quick look at the \u003ccode\u003euseEffect\u003c/code\u003e hook, which is a powerful tool that allows us to manage side effects in our components. Side effects can be anything that interacts with the outside of the component, like fetching data, timers, and of course, event listeners.\u003c/p\u003e\n\u003cp\u003eTo add an event listener using \u003ccode\u003euseEffect\u003c/code\u003e, we first declare the function that will be called when the event occurs. Then, inside \u003ccode\u003euseEffect\u003c/code\u003e, we add the event listener, and return a cleanup function that removes the event listener. This is how it looks in code:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e React, { useEffect } \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;react\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eMyComponent\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n useEffect(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003ehandleResize\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.innerWidth);\n }\n\n \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.addEventListener(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;resize\u0026#x27;\u003c/span\u003e, handleResize);\n\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.removeEventListener(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;resize\u0026#x27;\u003c/span\u003e, handleResize);\n };\n }, []);\n\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e \u003cspan class=\"xml\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ediv\u003c/span\u003e\u0026gt;\u003c/span\u003eResize the window and check the console!\u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ediv\u003c/span\u003e\u0026gt;\u003c/span\u003e\u003c/span\u003e;\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this code, \u003ccode\u003ehandleResize\u003c/code\u003e logs the window's inner width whenever the window is resized. The event listener is added when the component mounts, and removed when it unmounts, thanks to \u003ccode\u003euseEffect\u003c/code\u003e's cleanup function.\u003c/p\u003e\n\u003ch2 id=\"usecasesforaddingremovingeventlisteners\"\u003eUse Cases for Adding/Removing Event Listeners\u003c/h2\u003e\n\u003cp\u003eThere are tons of scenarios where you might need to add or remove event listeners in a React application. For example, you might want to add a \u0026quot;click\u0026quot; event listener to a button to trigger a specific action when the user interacts with it. Or, you might want to listen to the \u0026quot;resize\u0026quot; event on the window object to dynamically adjust the layout of your application based on the viewport size.\u003c/p\u003e\n\u003cp\u003eAnother common use case is listening to keyboard events. For example, you might want to capture the \u0026quot;keydown\u0026quot; event to implement keyboard shortcuts in your application. Here's a simple example along those lines:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e React, { useEffect } \u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e \u003cspan class=\"hljs-string\"\u003e\u0026#x27;react\u0026#x27;\u003c/span\u003e;\n\n\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eMyComponent\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n useEffect(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003ehandleKeyDown\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003eevent\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003eif\u003c/span\u003e (event.key === \u003cspan class=\"hljs-string\"\u003e\u0026#x27;Enter\u0026#x27;\u003c/span\u003e) {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Enter key pressed!\u0026#x27;\u003c/span\u003e);\n }\n }\n\n \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.addEventListener(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;keydown\u0026#x27;\u003c/span\u003e, handleKeyDown);\n\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003ewindow\u003c/span\u003e.removeEventListener(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;keydown\u0026#x27;\u003c/span\u003e, handleKeyDown);\n };\n }, []);\n\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e \u003cspan class=\"xml\"\u003e\u003cspan class=\"hljs-tag\"\u003e\u0026lt;\u003cspan class=\"hljs-name\"\u003ediv\u003c/span\u003e\u0026gt;\u003c/span\u003ePress the Enter key and check the console!\u003cspan class=\"hljs-tag\"\u003e\u0026lt;/\u003cspan class=\"hljs-name\"\u003ediv\u003c/span\u003e\u0026gt;\u003c/span\u003e\u003c/span\u003e;\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHere we've added an event listener for the \u0026quot;keydown\u0026quot; event. When the user presses the \u003ckbd\u003eEnter\u003c/kbd\u003e key, a message is logged to the console.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've explored how to add and remove event listeners in a React application. We've learned that React's \u003ccode\u003euseEffect\u003c/code\u003e hook is a powerful tool for managing event listeners, allowing us to add them when a component mounts and remove them when it unmounts. We've also looked at some common use cases for adding and removing event listeners, such as responding to user interaction or changes in the viewport size.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":20,"published_by":1,"published_at":1696653249438,"created_by":1,"updated_by":null,"created_at":1696604494157,"updated_at":1696653254013,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2113,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2113,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":171,"name":"React","slug":"react","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1588171280000,"updated_at":1588171280000,"_pivot_content_id":2113,"_pivot_tag_id":171,"_pivot_sort_order":1},{"id":196,"name":"web development","slug":"web-development","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1601641448000,"updated_at":1601641448000,"_pivot_content_id":2113,"_pivot_tag_id":196,"_pivot_sort_order":2}],"_pivot_tag_id":45,"_pivot_content_id":2113},{"id":2112,"old_id":null,"uuid":"7310bff5-e098-42d1-87ab-7795ba108f28","title":"Call a Function Every N Seconds in TypeScript","slug":"call-a-function-every-n-seconds-in-typescript","body_md":"## Introduction\n\nWhen dealing with real-time, interactive, or dynamic applications, you may need to run a function every N seconds in TypeScript. In this Byte, we'll go over exactly how to do that.\n\n## Why Use Time-Interval Function Calls?\n\nThere are a lot of different scenarios where you might want to execute a function at regular intervals. Consider a live dashboard that needs to refresh data every few seconds, a digital clock updating the time, or a game where certain actions need to be performed repeatedly. All these use cases require some kind of mechanism to call functions at a specified time interval. This is where JavaScript's (and thus TypeScript's) time-interval function calls can help you out.\n\n## What is the _setInterval_ Function?\n\nLet's first understand one of the key functions that makes all of this possible: `setInterval`. This function is well-known Web API function and is supported by all modern browsers. It's used to repeatedly execute code after a designated amount of milliseconds.\n\nHere's how it works:\n\n```typescript\nsetInterval(() =\u003e {\n console.log(\"Hello, StackAbuse readers!\");\n}, 3000);\n```\n\nIn this snippet, \"Hello, StackAbuse readers!\" will be printed to the console every 3000 milliseconds (or 3 seconds). The first argument to `setInterval` is the function to be executed, and the second argument is the delay in milliseconds. Here the first argument is just a simple arrow function that executes `console.log`.\n\n:::note\n**Note:** `setInterval` executes the function repeatedly at regular intervals. If you need to execute a function only once, you'll need to use another function: `setTimeout`.\n:::\n\n## Call a Function Every N Seconds\n\nNow, let's see how we can actually use `setInterval` to call a function every N seconds. The `setInterval` function works similarly to `setTimeout`, but instead of executing the function once after the delay, it executes it repeatedly at the specified interval.\n\nHere's how you can use it:\n\n```typescript\nsetInterval(() =\u003e {\n console.log(\"This message will display every 2 seconds\");\n}, 2000);\n```\n\nIn this example, \"This message will display every 2 seconds\" will be printed to the console every 2 seconds. The first argument to `setInterval` is the function to be executed, and the second argument is the interval in milliseconds.\n\nRemember, the interval you specify is the time *between* the function calls, not the time from the start of one call to the start of the next. This means that if your function takes a long time to execute, the intervals may end up being longer than you specified.\n\n:::note\n**Note:** To stop the function from being called, you can use the `clearInterval` function. This function takes the identifier returned by `setInterval` as an argument.\n:::\n\nHere's an example:\n\n```typescript\nlet intervalId: NodeJS.Timeout = setInterval(() =\u003e {\n console.log(\"This message will display every 2 seconds\");\n}, 2000);\n\n// Stop the interval after 10 seconds\nsetTimeout(() =\u003e {\n clearInterval(intervalId);\n}, 10000);\n```\n\nIn this snippet, the message will be printed every 2 seconds, but will stop after 10 seconds. We've used `setTimeout` to call `clearInterval` after 10 seconds, stopping the interval.\n\nIn true TypeScript fashion, we've also declared the type for `setInterval`'s return value, which is formally `NodeJS.Timeout`.\n\n:::reference\n**Link:** For a more in-depth explanation of timers in JavaScript, check out our guide:\n\n\u003ca href=\"https://stackabuse.com/how-to-use-timers-and-events-in-node-js/\"\u003eHow to use Timers and Events in Node.js\u003c/a\u003e\n:::\n\n## Common Errors and How to Fix Them\n\nWhile using `setTimeout` or `setInterval` in TypeScript, a few common errors may arise. Let's take a look at some of these and how we can address them.\n\nOne common error is `Uncaught ReferenceError: function is not defined`. This error can happen when the function you're trying to call with `setTimeout` is not in the same scope. To fix this, just make sure that the function is accessible in the scope where `setTimeout`/`setInterval` is called.\n\n```typescript\nfunction printMessage() {\n console.log('Hello, StackAbuse!');\n}\n\nsetTimeout(printMessage, 2000); // This will work\n```\n\nAnother possible error is `Uncaught TypeError: this.method is not a function`. This error can happen when `this` inside the callback function doesn't refer to what you expect it to. JavaScript's `this` can be a bit confusing, especially when dealing with callbacks. One way to fix this is by using an arrow function, which lexically binds `this`.\n\n```typescript\nclass Printer {\n message: string = 'Hello, StackAbuse!';\n\n printMessage = () =\u003e {\n console.log(this.message);\n }\n}\n\nlet printer = new Printer();\nsetTimeout(printer.printMessage, 2000); // This will work\n```\n\n## Alternatives to setTimeout\n\nAlthough `setTimeout` is a powerful function, there are other ways to schedule tasks in TypeScript. One such alternative is `setInterval`.\n\n`setInterval` works similarly to `setTimeout`, but instead of executing the function once after a delay, it executes the function repeatedly at the specified interval.\n\n```typescript\nsetInterval(() =\u003e {\n console.log('This message will repeat every 2 seconds');\n}, 2000);\n```\n\nAnother alternative is the `requestAnimationFrame` function. This is particularly useful for animations, as it calls a function before the next repaint, allowing for smoother animations.\n\n```typescript\nfunction animate() {\n console.log('Animating...');\n requestAnimationFrame(animate);\n}\n\nrequestAnimationFrame(animate);\n```\n\nThis one is specific to rendering use-cases, so it's usefulness is limited to that.\n\n## Conclusion\n\nAnd there you have it, a Byte-sized guide to calling a function every N seconds in TypeScript. We've covered how to perform this function, some common errors you might encounter and their fixes, and looked at alternatives to `setTimeout`.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eWhen dealing with real-time, interactive, or dynamic applications, you may need to run a function every N seconds in TypeScript. In this Byte, we'll go over exactly how to do that.\u003c/p\u003e\n\u003ch2 id=\"whyusetimeintervalfunctioncalls\"\u003eWhy Use Time-Interval Function Calls?\u003c/h2\u003e\n\u003cp\u003eThere are a lot of different scenarios where you might want to execute a function at regular intervals. Consider a live dashboard that needs to refresh data every few seconds, a digital clock updating the time, or a game where certain actions need to be performed repeatedly. All these use cases require some kind of mechanism to call functions at a specified time interval. This is where JavaScript's (and thus TypeScript's) time-interval function calls can help you out.\u003c/p\u003e\n\u003ch2 id=\"whatisthesetintervalfunction\"\u003eWhat is the \u003cem\u003esetInterval\u003c/em\u003e Function?\u003c/h2\u003e\n\u003cp\u003eLet's first understand one of the key functions that makes all of this possible: \u003ccode\u003esetInterval\u003c/code\u003e. This function is well-known Web API function and is supported by all modern browsers. It's used to repeatedly execute code after a designated amount of milliseconds.\u003c/p\u003e\n\u003cp\u003eHere's how it works:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003esetInterval\u003c/span\u003e(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026quot;Hello, StackAbuse readers!\u0026quot;\u003c/span\u003e);\n}, \u003cspan class=\"hljs-number\"\u003e3000\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this snippet, \u0026quot;Hello, StackAbuse readers!\u0026quot; will be printed to the console every 3000 milliseconds (or 3 seconds). The first argument to \u003ccode\u003esetInterval\u003c/code\u003e is the function to be executed, and the second argument is the delay in milliseconds. Here the first argument is just a simple arrow function that executes \u003ccode\u003econsole.log\u003c/code\u003e.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e \u003ccode\u003esetInterval\u003c/code\u003e executes the function repeatedly at regular intervals. If you need to execute a function only once, you'll need to use another function: \u003ccode\u003esetTimeout\u003c/code\u003e.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"callafunctioneverynseconds\"\u003eCall a Function Every N Seconds\u003c/h2\u003e\n\u003cp\u003eNow, let's see how we can actually use \u003ccode\u003esetInterval\u003c/code\u003e to call a function every N seconds. The \u003ccode\u003esetInterval\u003c/code\u003e function works similarly to \u003ccode\u003esetTimeout\u003c/code\u003e, but instead of executing the function once after the delay, it executes it repeatedly at the specified interval.\u003c/p\u003e\n\u003cp\u003eHere's how you can use it:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003esetInterval\u003c/span\u003e(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026quot;This message will display every 2 seconds\u0026quot;\u003c/span\u003e);\n}, \u003cspan class=\"hljs-number\"\u003e2000\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this example, \u0026quot;This message will display every 2 seconds\u0026quot; will be printed to the console every 2 seconds. The first argument to \u003ccode\u003esetInterval\u003c/code\u003e is the function to be executed, and the second argument is the interval in milliseconds.\u003c/p\u003e\n\u003cp\u003eRemember, the interval you specify is the time \u003cem\u003ebetween\u003c/em\u003e the function calls, not the time from the start of one call to the start of the next. This means that if your function takes a long time to execute, the intervals may end up being longer than you specified.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e To stop the function from being called, you can use the \u003ccode\u003eclearInterval\u003c/code\u003e function. This function takes the identifier returned by \u003ccode\u003esetInterval\u003c/code\u003e as an argument.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003cp\u003eHere's an example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e intervalId: NodeJS.Timeout = \u003cspan class=\"hljs-built_in\"\u003esetInterval\u003c/span\u003e(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026quot;This message will display every 2 seconds\u0026quot;\u003c/span\u003e);\n}, \u003cspan class=\"hljs-number\"\u003e2000\u003c/span\u003e);\n\n\u003cspan class=\"hljs-comment\"\u003e// Stop the interval after 10 seconds\u003c/span\u003e\n\u003cspan class=\"hljs-built_in\"\u003esetTimeout\u003c/span\u003e(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003eclearInterval\u003c/span\u003e(intervalId);\n}, \u003cspan class=\"hljs-number\"\u003e10000\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this snippet, the message will be printed every 2 seconds, but will stop after 10 seconds. We've used \u003ccode\u003esetTimeout\u003c/code\u003e to call \u003ccode\u003eclearInterval\u003c/code\u003e after 10 seconds, stopping the interval.\u003c/p\u003e\n\u003cp\u003eIn true TypeScript fashion, we've also declared the type for \u003ccode\u003esetInterval\u003c/code\u003e's return value, which is formally \u003ccode\u003eNodeJS.Timeout\u003c/code\u003e.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-reference\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-link-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eLink:\u003c/strong\u003e For a more in-depth explanation of timers in JavaScript, check out our guide:\u003c/p\u003e\n\u003cp\u003e\u003ca href=\"https://stackabuse.com/how-to-use-timers-and-events-in-node-js/\"\u003eHow to use Timers and Events in Node.js\u003c/a\u003e\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"commonerrorsandhowtofixthem\"\u003eCommon Errors and How to Fix Them\u003c/h2\u003e\n\u003cp\u003eWhile using \u003ccode\u003esetTimeout\u003c/code\u003e or \u003ccode\u003esetInterval\u003c/code\u003e in TypeScript, a few common errors may arise. Let's take a look at some of these and how we can address them.\u003c/p\u003e\n\u003cp\u003eOne common error is \u003ccode\u003eUncaught ReferenceError: function is not defined\u003c/code\u003e. This error can happen when the function you're trying to call with \u003ccode\u003esetTimeout\u003c/code\u003e is not in the same scope. To fix this, just make sure that the function is accessible in the scope where \u003ccode\u003esetTimeout\u003c/code\u003e/\u003ccode\u003esetInterval\u003c/code\u003e is called.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eprintMessage\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Hello, StackAbuse!\u0026#x27;\u003c/span\u003e);\n}\n\n\u003cspan class=\"hljs-built_in\"\u003esetTimeout\u003c/span\u003e(printMessage, \u003cspan class=\"hljs-number\"\u003e2000\u003c/span\u003e); \u003cspan class=\"hljs-comment\"\u003e// This will work\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnother possible error is \u003ccode\u003eUncaught TypeError: this.method is not a function\u003c/code\u003e. This error can happen when \u003ccode\u003ethis\u003c/code\u003e inside the callback function doesn't refer to what you expect it to. JavaScript's \u003ccode\u003ethis\u003c/code\u003e can be a bit confusing, especially when dealing with callbacks. One way to fix this is by using an arrow function, which lexically binds \u003ccode\u003ethis\u003c/code\u003e.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003ePrinter\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-attr\"\u003emessage\u003c/span\u003e: \u003cspan class=\"hljs-built_in\"\u003estring\u003c/span\u003e = \u003cspan class=\"hljs-string\"\u003e\u0026#x27;Hello, StackAbuse!\u0026#x27;\u003c/span\u003e;\n\n printMessage = \u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-built_in\"\u003ethis\u003c/span\u003e.message);\n }\n}\n\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e printer = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Printer();\n\u003cspan class=\"hljs-built_in\"\u003esetTimeout\u003c/span\u003e(printer.printMessage, \u003cspan class=\"hljs-number\"\u003e2000\u003c/span\u003e); \u003cspan class=\"hljs-comment\"\u003e// This will work\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"alternativestosettimeout\"\u003eAlternatives to setTimeout\u003c/h2\u003e\n\u003cp\u003eAlthough \u003ccode\u003esetTimeout\u003c/code\u003e is a powerful function, there are other ways to schedule tasks in TypeScript. One such alternative is \u003ccode\u003esetInterval\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003e\u003ccode\u003esetInterval\u003c/code\u003e works similarly to \u003ccode\u003esetTimeout\u003c/code\u003e, but instead of executing the function once after a delay, it executes the function repeatedly at the specified interval.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003esetInterval\u003c/span\u003e(\u003cspan class=\"hljs-function\"\u003e() =\u0026gt;\u003c/span\u003e {\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;This message will repeat every 2 seconds\u0026#x27;\u003c/span\u003e);\n}, \u003cspan class=\"hljs-number\"\u003e2000\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnother alternative is the \u003ccode\u003erequestAnimationFrame\u003c/code\u003e function. This is particularly useful for animations, as it calls a function before the next repaint, allowing for smoother animations.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003efunction\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eanimate\u003c/span\u003e(\u003cspan class=\"hljs-params\"\u003e\u003c/span\u003e) \u003c/span\u003e{\n \u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;Animating...\u0026#x27;\u003c/span\u003e);\n requestAnimationFrame(animate);\n}\n\nrequestAnimationFrame(animate);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis one is specific to rendering use-cases, so it's usefulness is limited to that.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eAnd there you have it, a Byte-sized guide to calling a function every N seconds in TypeScript. We've covered how to perform this function, some common errors you might encounter and their fixes, and looked at alternatives to \u003ccode\u003esetTimeout\u003c/code\u003e.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":14,"published_by":1,"published_at":1696650624162,"created_by":1,"updated_by":null,"created_at":1696564182040,"updated_at":1696650624204,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2112,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2112,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":48,"name":"node","slug":"node","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2112,"_pivot_tag_id":48,"_pivot_sort_order":1},{"id":92,"name":"typescript","slug":"typescript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1525361463000,"updated_at":1525361463000,"_pivot_content_id":2112,"_pivot_tag_id":92,"_pivot_sort_order":2}],"_pivot_tag_id":45,"_pivot_content_id":2112},{"id":2110,"old_id":null,"uuid":"9b12f0a8-da37-4102-aaf8-9f372647adb4","title":"Reading Environment Variables in Node.js","slug":"reading-environment-variables-in-node-js","body_md":"## Introduction\n\nEver wondered how to manage sensitive data like API keys, database credentials or configuration settings in your Node.js applications? The answer lies with environment variables. This Byte will give a brief intro to environment variables, why they are important, and then we'll explore how to read them in Node.js using different methods.\n\n### What are Environment Variables\n\nEnvironment variables are name-value pairs that can affect the way running processes behave on a computer. They exist in every operating system, and are used to make certain information globally available to all running processes. In the context of Node.js, environment variables are primarily used to set process-level variables that are global to the application.\n\n```javascript\nconsole.log(process.env);\n```\n\nRunning the above code in Node.js will output an object containing your environment variables. It might look something like this:\n\n```plaintext\n{\n TERM: 'xterm-256color',\n SHELL: '/usr/local/bin/bash',\n USER: 'username',\n PATH: '...',\n PWD: '/',\n EDITOR: 'vim',\n SHLVL: '1',\n HOME: '/home/username',\n LOGNAME: 'username',\n _: '/usr/local/bin/node'\n}\n```\n\nWe'll look at `process.env` more later in this Byte.\n\n### Why Use Environment Variables\n\nBut why should you use environment variables in your Node.js applications? Well, there are several reasons:\n\n- **Security**: Environment variables allow you to hide or separate sensitive data from your application code. This is particularly useful when you're dealing with passwords, API keys, or any other sensitive data that you don't want to expose in your code. Keeping these keys separate from your code means it won't get checked into a Git repo and then shared with everyone.\n\n:::warn\n**Safeguard your keys!** Accidentally checking in AWS access keys into public Git repos is so common that there are bots that watch for these keys. When found, the bots will set up crypto mining software in your AWS account, potentially costing you thousands of dollars in compute costs.\n:::\n\n- **Portability**: With environment variables, you can configure your application to work in different environments. This is useful when you need to switch between different settings for development, testing, and production environments - or even between operating systems!\n\n- **Ease of use**: Environment variables are easy to use and can be accessed from anywhere in your application. They provide a simple way to store and retrieve configuration settings and commonly used throughout all types of software.\n\n## How to Read Environment Variables in Node.js\n\nThere are two main ways to read environment variables in Node.js: using the `process.env` global object, and using the `dotenv` module.\n\n### Using _process.env_\n\nThe `process.env` global object is a simple way to access your environment variables. It's available globally in your application, and you don't need to import any additional modules to use it.\n\nHere's an example of how you can read an environment variable using `process.env`:\n\n```javascript\nconsole.log(process.env.USER);\n```\n\nRunning this code will output the value of the `USER` environment variable:\n\n```plaintext\n'username'\n```\n\nHowever, while `process.env` is simple and easy to use, it has its limitations. For instance, it doesn't provide a way to load variables from a file, which you'd then have to set by specifying them on the command that launches your app. But what if you have lots of variables to set? This is where the `dotenv` module comes in handy.\n\n:::note\n**Note:** It's a good practice to prefix your custom environment variables with a specific keyword related to your app or company. This helps avoid potential conflicts with system-level environment variables.\n:::\n\n### Using _dotenv_ Module\n\nThe \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://www.npmjs.com/package/dotenv\"\u003edotenv\u003c/a\u003e module is a third-party module that allows you to load environment variables from a `.env` file into `process.env`. This is particularly useful when you have a large number of environment variables, or when you want to easily switch between different environments (i.e. dev, staging, prod, etc).\n\nHere's how you can use `dotenv` to read environment variables:\n\nFirst, install the `dotenv` module using npm:\n\n```console\n$ npm install dotenv\n```\n\nNext, create a `.env` file in the root of your project and add some variables:\n\n```env\nDB_HOST=localhost\nDB_USER=root\nDB_PASS=s1mpl3\n```\n\nFinally, you can load the variables from the `.env` file into `process.env` using `dotenv`:\n\n```javascript\nrequire('dotenv').config();\n\nconsole.log(process.env.DB_HOST);\nconsole.log(process.env.DB_USER);\nconsole.log(process.env.DB_PASS);\n```\n\nRunning this code will output the values of the `DB_HOST`, `DB_USER`, and `DB_PASS` environment variables:\n\n```plaintext\n'localhost'\n'root'\n's1mpl3'\n```\n\nAnd there you have it! You now know how to read environment variables in Node.js using both `process.env` and the `dotenv` module.\n\n## Common Errors and How to Fix Them\n\nWhile reading environment variables in Node.js is generally pretty easy, and thus fairly error-free, you might encounter a few hiccups along the way. Here are a couple of common issues to look out for:\n\n- **`undefined` values:** If `process.env.YOUR_VARIABLE` returns `undefined`, it means the environment variable `YOUR_VARIABLE` wasn't set before the process started. Make sure the variable is set and exported in your environment, or loaded from the `.env` file. An `undefined` value could be an indicator of another problem.\n\n- **Dotenv doesn't load variables:** If you're using `dotenv` and your variables aren't loaded, make sure the `.env` file is in your project root and that you're calling `dotenv.config()` before trying to access the variables.\n\n If your env file is not being loaded because it has a different name, you can either rename it to the standard `.env` name or use the `path` setting to specify a different name:\n\n ```javascript\n require('dotenv').config({ path: './.env-dev' })\n ```\n\n:::note\n**Note:** When using dotenv, remember that it doesn't overwrite existing environment variables. So if you have an environment variable set in your environment and a different value for the same variable in your `.env` file, `process.env` will contain the value from your environment.\n:::\n\n## Use Cases\n\nEnvironment variables are used in tons of software projects and have lots of use-cases, a few of which we'll touch on here.\n\n### Storing Sensitive Information\n\nConsider a scenario: You're working on a project that interacts with a database. Naturally, you'll need to store the database credentials. But, is it a good idea to hardcode these values into your Node.js application? Nope!\n\nStoring sensitive information such as database credentials, API keys, or any other secret data directly in your code can lead to serious security issues. This data can be easily exposed if your codebase is publicly accessible, say, on a GitHub repository.\n\nThis is where environment variables come in handy. By storing sensitive information in environment variables, you're ensuring that this data isn't exposed in your codebase.\n\n:::note\n**Note:** Always remember to add your `.env` file to your `.gitignore` file to prevent it from being tracked by Git and exposed on platforms like GitHub.\n:::\n\n### Configuration Management\n\nEver wondered how you can manage different configurations for development, testing, and production environments in your Node.js application? Environment variables to the rescue, again!\n\nManaging configurations with environment variables is a common practice. It allows you to define different values for your variables depending on the environment your application is running in.\n\nFor instance, you might want to use a different database for development and production. You can manage this by setting an environment variable, say `DB_HOST`. In your development environment, `DB_HOST` can be set to the URL of your development database. Similarly, in production, `DB_HOST` can point to your production database.\n\nThis way, you can easily switch between different configurations without changing any code in your application.\n\n## Conclusion\n\nIn this Byte, we've explored the importance of environment variables in Node.js applications. We've seen how they can help secure sensitive data and manage different configurations for various environments. \n\nBut, there's more to environment variables than just storing secrets and managing configurations. They can also be used for feature flagging, setting application-level constants, and more. ","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eEver wondered how to manage sensitive data like API keys, database credentials or configuration settings in your Node.js applications? The answer lies with environment variables. This Byte will give a brief intro to environment variables, why they are important, and then we'll explore how to read them in Node.js using different methods.\u003c/p\u003e\n\u003ch3 id=\"whatareenvironmentvariables\"\u003eWhat are Environment Variables\u003c/h3\u003e\n\u003cp\u003eEnvironment variables are name-value pairs that can affect the way running processes behave on a computer. They exist in every operating system, and are used to make certain information globally available to all running processes. In the context of Node.js, environment variables are primarily used to set process-level variables that are global to the application.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(process.env);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eRunning the above code in Node.js will output an object containing your environment variables. It might look something like this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e{\n TERM: \u0026#x27;xterm-256color\u0026#x27;,\n SHELL: \u0026#x27;/usr/local/bin/bash\u0026#x27;,\n USER: \u0026#x27;username\u0026#x27;,\n PATH: \u0026#x27;...\u0026#x27;,\n PWD: \u0026#x27;/\u0026#x27;,\n EDITOR: \u0026#x27;vim\u0026#x27;,\n SHLVL: \u0026#x27;1\u0026#x27;,\n HOME: \u0026#x27;/home/username\u0026#x27;,\n LOGNAME: \u0026#x27;username\u0026#x27;,\n _: \u0026#x27;/usr/local/bin/node\u0026#x27;\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eWe'll look at \u003ccode\u003eprocess.env\u003c/code\u003e more later in this Byte.\u003c/p\u003e\n\u003ch3 id=\"whyuseenvironmentvariables\"\u003eWhy Use Environment Variables\u003c/h3\u003e\n\u003cp\u003eBut why should you use environment variables in your Node.js applications? Well, there are several reasons:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\u003cstrong\u003eSecurity\u003c/strong\u003e: Environment variables allow you to hide or separate sensitive data from your application code. This is particularly useful when you're dealing with passwords, API keys, or any other sensitive data that you don't want to expose in your code. Keeping these keys separate from your code means it won't get checked into a Git repo and then shared with everyone.\u003c/li\u003e\n\u003c/ul\u003e\n\n \u003cdiv class=\"alert alert-warn\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-exclamation-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eSafeguard your keys!\u003c/strong\u003e Accidentally checking in AWS access keys into public Git repos is so common that there are bots that watch for these keys. When found, the bots will set up crypto mining software in your AWS account, potentially costing you thousands of dollars in compute costs.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003cul\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003ePortability\u003c/strong\u003e: With environment variables, you can configure your application to work in different environments. This is useful when you need to switch between different settings for development, testing, and production environments - or even between operating systems!\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003eEase of use\u003c/strong\u003e: Environment variables are easy to use and can be accessed from anywhere in your application. They provide a simple way to store and retrieve configuration settings and commonly used throughout all types of software.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"howtoreadenvironmentvariablesinnodejs\"\u003eHow to Read Environment Variables in Node.js\u003c/h2\u003e\n\u003cp\u003eThere are two main ways to read environment variables in Node.js: using the \u003ccode\u003eprocess.env\u003c/code\u003e global object, and using the \u003ccode\u003edotenv\u003c/code\u003e module.\u003c/p\u003e\n\u003ch3 id=\"usingprocessenv\"\u003eUsing \u003cem\u003eprocess.env\u003c/em\u003e\u003c/h3\u003e\n\u003cp\u003eThe \u003ccode\u003eprocess.env\u003c/code\u003e global object is a simple way to access your environment variables. It's available globally in your application, and you don't need to import any additional modules to use it.\u003c/p\u003e\n\u003cp\u003eHere's an example of how you can read an environment variable using \u003ccode\u003eprocess.env\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(process.env.USER);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eRunning this code will output the value of the \u003ccode\u003eUSER\u003c/code\u003e environment variable:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u0026#x27;username\u0026#x27;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHowever, while \u003ccode\u003eprocess.env\u003c/code\u003e is simple and easy to use, it has its limitations. For instance, it doesn't provide a way to load variables from a file, which you'd then have to set by specifying them on the command that launches your app. But what if you have lots of variables to set? This is where the \u003ccode\u003edotenv\u003c/code\u003e module comes in handy.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e It's a good practice to prefix your custom environment variables with a specific keyword related to your app or company. This helps avoid potential conflicts with system-level environment variables.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"usingdotenvmodule\"\u003eUsing \u003cem\u003edotenv\u003c/em\u003e Module\u003c/h3\u003e\n\u003cp\u003eThe \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://www.npmjs.com/package/dotenv\"\u003edotenv\u003c/a\u003e module is a third-party module that allows you to load environment variables from a \u003ccode\u003e.env\u003c/code\u003e file into \u003ccode\u003eprocess.env\u003c/code\u003e. This is particularly useful when you have a large number of environment variables, or when you want to easily switch between different environments (i.e. dev, staging, prod, etc).\u003c/p\u003e\n\u003cp\u003eHere's how you can use \u003ccode\u003edotenv\u003c/code\u003e to read environment variables:\u003c/p\u003e\n\u003cp\u003eFirst, install the \u003ccode\u003edotenv\u003c/code\u003e module using npm:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e npm install dotenv\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eNext, create a \u003ccode\u003e.env\u003c/code\u003e file in the root of your project and add some variables:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003eDB_HOST=localhost\nDB_USER=root\nDB_PASS=s1mpl3\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eFinally, you can load the variables from the \u003ccode\u003e.env\u003c/code\u003e file into \u003ccode\u003eprocess.env\u003c/code\u003e using \u003ccode\u003edotenv\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003erequire\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;dotenv\u0026#x27;\u003c/span\u003e).config();\n\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(process.env.DB_HOST);\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(process.env.DB_USER);\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(process.env.DB_PASS);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eRunning this code will output the values of the \u003ccode\u003eDB_HOST\u003c/code\u003e, \u003ccode\u003eDB_USER\u003c/code\u003e, and \u003ccode\u003eDB_PASS\u003c/code\u003e environment variables:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u0026#x27;localhost\u0026#x27;\n\u0026#x27;root\u0026#x27;\n\u0026#x27;s1mpl3\u0026#x27;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnd there you have it! You now know how to read environment variables in Node.js using both \u003ccode\u003eprocess.env\u003c/code\u003e and the \u003ccode\u003edotenv\u003c/code\u003e module.\u003c/p\u003e\n\u003ch2 id=\"commonerrorsandhowtofixthem\"\u003eCommon Errors and How to Fix Them\u003c/h2\u003e\n\u003cp\u003eWhile reading environment variables in Node.js is generally pretty easy, and thus fairly error-free, you might encounter a few hiccups along the way. Here are a couple of common issues to look out for:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003e\u003ccode\u003eundefined\u003c/code\u003e values:\u003c/strong\u003e If \u003ccode\u003eprocess.env.YOUR_VARIABLE\u003c/code\u003e returns \u003ccode\u003eundefined\u003c/code\u003e, it means the environment variable \u003ccode\u003eYOUR_VARIABLE\u003c/code\u003e wasn't set before the process started. Make sure the variable is set and exported in your environment, or loaded from the \u003ccode\u003e.env\u003c/code\u003e file. An \u003ccode\u003eundefined\u003c/code\u003e value could be an indicator of another problem.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003eDotenv doesn't load variables:\u003c/strong\u003e If you're using \u003ccode\u003edotenv\u003c/code\u003e and your variables aren't loaded, make sure the \u003ccode\u003e.env\u003c/code\u003e file is in your project root and that you're calling \u003ccode\u003edotenv.config()\u003c/code\u003e before trying to access the variables.\u003c/p\u003e\n\u003cp\u003eIf your env file is not being loaded because it has a different name, you can either rename it to the standard \u003ccode\u003e.env\u003c/code\u003e name or use the \u003ccode\u003epath\u003c/code\u003e setting to specify a different name:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-built_in\"\u003erequire\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;dotenv\u0026#x27;\u003c/span\u003e).config({ \u003cspan class=\"hljs-attr\"\u003epath\u003c/span\u003e: \u003cspan class=\"hljs-string\"\u003e\u0026#x27;./.env-dev\u0026#x27;\u003c/span\u003e })\n\u003c/code\u003e\u003c/pre\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e When using dotenv, remember that it doesn't overwrite existing environment variables. So if you have an environment variable set in your environment and a different value for the same variable in your \u003ccode\u003e.env\u003c/code\u003e file, \u003ccode\u003eprocess.env\u003c/code\u003e will contain the value from your environment.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"usecases\"\u003eUse Cases\u003c/h2\u003e\n\u003cp\u003eEnvironment variables are used in tons of software projects and have lots of use-cases, a few of which we'll touch on here.\u003c/p\u003e\n\u003ch3 id=\"storingsensitiveinformation\"\u003eStoring Sensitive Information\u003c/h3\u003e\n\u003cp\u003eConsider a scenario: You're working on a project that interacts with a database. Naturally, you'll need to store the database credentials. But, is it a good idea to hardcode these values into your Node.js application? Nope!\u003c/p\u003e\n\u003cp\u003eStoring sensitive information such as database credentials, API keys, or any other secret data directly in your code can lead to serious security issues. This data can be easily exposed if your codebase is publicly accessible, say, on a GitHub repository.\u003c/p\u003e\n\u003cp\u003eThis is where environment variables come in handy. By storing sensitive information in environment variables, you're ensuring that this data isn't exposed in your codebase.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e Always remember to add your \u003ccode\u003e.env\u003c/code\u003e file to your \u003ccode\u003e.gitignore\u003c/code\u003e file to prevent it from being tracked by Git and exposed on platforms like GitHub.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"configurationmanagement\"\u003eConfiguration Management\u003c/h3\u003e\n\u003cp\u003eEver wondered how you can manage different configurations for development, testing, and production environments in your Node.js application? Environment variables to the rescue, again!\u003c/p\u003e\n\u003cp\u003eManaging configurations with environment variables is a common practice. It allows you to define different values for your variables depending on the environment your application is running in.\u003c/p\u003e\n\u003cp\u003eFor instance, you might want to use a different database for development and production. You can manage this by setting an environment variable, say \u003ccode\u003eDB_HOST\u003c/code\u003e. In your development environment, \u003ccode\u003eDB_HOST\u003c/code\u003e can be set to the URL of your development database. Similarly, in production, \u003ccode\u003eDB_HOST\u003c/code\u003e can point to your production database.\u003c/p\u003e\n\u003cp\u003eThis way, you can easily switch between different configurations without changing any code in your application.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've explored the importance of environment variables in Node.js applications. We've seen how they can help secure sensitive data and manage different configurations for various environments.\u003c/p\u003e\n\u003cp\u003eBut, there's more to environment variables than just storing secrets and managing configurations. They can also be used for feature flagging, setting application-level constants, and more.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":20,"published_by":null,"published_at":1696513200000,"created_by":1,"updated_by":null,"created_at":1696473129117,"updated_at":1696475384908,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2110,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2110,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":48,"name":"node","slug":"node","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2110,"_pivot_tag_id":48,"_pivot_sort_order":1}],"_pivot_tag_id":45,"_pivot_content_id":2110},{"id":2109,"old_id":null,"uuid":"99bfee44-b8d9-4bb9-b54d-a343ffaec5da","title":"How to Convert a Date to Timestamp in JavaScript","slug":"how-to-convert-a-date-to-timestamp-in-javascript","body_md":"## Introduction\n\nIn programming, we often need to deal with dates and times, which can be represented in a few different ways, like an object (via `Date`), a string (i.e. \"2023-10-04T00:00:00.000Z\"), or a timestamp (i.e. 1696377600000). In this Byte, we'll explore how to convert a date or date string to a timestamp in JavaScript.\n\n## Why Convert Date or Date String to Timestamp\n\nBut why do we need to convert a date or date string to a timestamp in the first place? Timestamps are a more universal way of storing date and time information. They represent the number of seconds (or milliseconds) since the Unix Epoch (January 1, 1970), making them a simple way to store date and time data. They're also timezone-agnostic, which can simplify things when dealing with data from different time zones.\n\n## Dates and Timestamps in JavaScript\n\nBefore we get into converting our dates, let's take a moment to understand what we're dealing with. In JavaScript, a `Date` object represents a moment in time. You can create a new Date object with the `new Date()` constructor. \n\nOn the other hand, a timestamp is a numeric representation of a date, as described earlier. \n\n```javascript\nlet currentDate = new Date();\nconsole.log(currentDate); // Outputs: 2023-10-04T13:20:23.670Z\n```\n\n## How to Convert a Date to Timestamp\n\nConverting a Date object to a timestamp in JavaScript is pretty straightforward. You can use the `getTime()` method, which returns the number of milliseconds since the Unix Epoch. \n\n```javascript\nlet currentDate = new Date();\nlet timestamp = currentDate.getTime();\nconsole.log(timestamp); // Outputs: 1696425660603\n```\n\n:::note\n**Note:** The `getTime()` method returns the timestamp in _milliseconds_. If you need the timestamp in _seconds_, you can divide the result by 1000.\n:::\n\n## How to Convert a Date String to Timestamp\n\nSo what if we have a date in string format? It'll be a similar process as before, but with the extra step of converting the string to a `Date` object and then the timestamp.\n\nJust make sure your date string is in a format that the `Date` constructor can understand. According to \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format\"\u003eMDN\u003c/a\u003e:\n\n\u003e The JavaScript specification only specifies one format to be universally supported: the \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-time-string-format\"\u003edate time string format\u003c/a\u003e, a simplification of the ISO 8601 calendar date extended format. The format is as follows:\n\u003e \u0026nbsp;\n\u003e `YYYY-MM-DDTHH:mm:ss.sssZ`\n\nApparently other formats do work, but are implementation-dependent and may not work across all browsers.\n\n```javascript\nlet dateString = \"2023-10-04\";\nlet dateObject = new Date(dateString);\nlet timestamp = dateObject.getTime();\nconsole.log(timestamp); // Outputs: 1696377600000\n```\n\nSo the date string should be in a format recognized by the `Date.parse()` method (used internally by the `Date` constructor). While the above format is formally specified, you can also use more shorthand dates like \"YYYY-MM-DD\".\n\n## Other Solutions\n\nWhile we've focused on the `Date` object and its `getTime()` method for converting a date to a timestamp in JavaScript, there are other ways to achieve the same thing. For instance, the `valueOf()` method returns the primitive value of a `Date` object as a number data type, which is the timestamp.\n\nHere's an example:\n\n```javascript\nlet date = new Date();\nconsole.log(date.valueOf()); // Output: 1696428432208\n```\n\nThe `+` operator can also be used to convert a `Date` object to a timestamp. This works because the `+` operator triggers the `valueOf()` method behind the scenes in order to do any mathematical operation on the date.\n\n```javascript\nlet date = new Date();\nconsole.log(+date); // Output: 1696428432208\n```\n\n:::note\n**Note:** While these methods achieve the same result, it's important to understand how they work and when to use them. The `+` operator, for example, might be less clear to someone reading your code than the explicit `getTime()` or `valueOf()` methods.\n:::\n\n## Common Errors and How to Avoid Them\n\nA common mistake when working with dates and timestamps in JavaScript is not accounting for time zones. JavaScript's `Date` object is **based on the user's local time zone, but timestamps are always UTC**. This can lead to unexpected results if not handled correctly.\n\nFor example, let's say you create a `Date` object for midnight on a specific date:\n\n```javascript\nlet date = new Date('2023-10-04T00:00:00');\nconsole.log(date.getTime()); // Output: 1696428432208\n```\n\nDepending on your local time zone, the timestamp might not represent midnight UTC, but some other time. To avoid this, always create `Date` objects in UTC when you plan to convert them to timestamps.\n\nAnother common mistake is using the `Date.parse()` method to convert a date string to a timestamp. While this can work, it's not recommended because `Date.parse()` has inconsistent behavior across different browsers and can lead to some very hard-to-find bugs!\n\n## Use-Cases of Date/Timestamp Conversion\n\nConverting dates to timestamps is useful in many situations. For example, timestamps are often used in APIs and databases to record when an event occurred. By storing the time as a timestamp, you can easily compare times and calculate durations鈥攕omething that's much harder, or more error-prone, with date strings.\n\nTimestamps are also handy for performance testing. By taking a timestamp at the start and end of a process, you can calculate how long it took. This is a common technique in JavaScript and other programming languages. You'd do this by creating new `Date` objects at the start/end of the process, but then you'd need to convert to timestamp to be able to find the difference between the two.\n\n## Conclusion\n\nIn this Byte, we've learned how to convert a date to a timestamp in JavaScript using the `Date` object's `getTime()` method. We've also looked at alternative methods, common errors to avoid, and some use-cases for date and timestamp conversion.","body_html":"\u003ch2 id=\"introduction\"\u003eIntroduction\u003c/h2\u003e\n\u003cp\u003eIn programming, we often need to deal with dates and times, which can be represented in a few different ways, like an object (via \u003ccode\u003eDate\u003c/code\u003e), a string (i.e. \u0026quot;2023-10-04T00:00:00.000Z\u0026quot;), or a timestamp (i.e. 1696377600000). In this Byte, we'll explore how to convert a date or date string to a timestamp in JavaScript.\u003c/p\u003e\n\u003ch2 id=\"whyconvertdateordatestringtotimestamp\"\u003eWhy Convert Date or Date String to Timestamp\u003c/h2\u003e\n\u003cp\u003eBut why do we need to convert a date or date string to a timestamp in the first place? Timestamps are a more universal way of storing date and time information. They represent the number of seconds (or milliseconds) since the Unix Epoch (January 1, 1970), making them a simple way to store date and time data. They're also timezone-agnostic, which can simplify things when dealing with data from different time zones.\u003c/p\u003e\n\u003ch2 id=\"datesandtimestampsinjavascript\"\u003eDates and Timestamps in JavaScript\u003c/h2\u003e\n\u003cp\u003eBefore we get into converting our dates, let's take a moment to understand what we're dealing with. In JavaScript, a \u003ccode\u003eDate\u003c/code\u003e object represents a moment in time. You can create a new Date object with the \u003ccode\u003enew Date()\u003c/code\u003e constructor.\u003c/p\u003e\n\u003cp\u003eOn the other hand, a timestamp is a numeric representation of a date, as described earlier.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e currentDate = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e \u003cspan class=\"hljs-built_in\"\u003eDate\u003c/span\u003e();\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(currentDate); \u003cspan class=\"hljs-comment\"\u003e// Outputs: 2023-10-04T13:20:23.670Z\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"howtoconvertadatetotimestamp\"\u003eHow to Convert a Date to Timestamp\u003c/h2\u003e\n\u003cp\u003eConverting a Date object to a timestamp in JavaScript is pretty straightforward. You can use the \u003ccode\u003egetTime()\u003c/code\u003e method, which returns the number of milliseconds since the Unix Epoch.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e currentDate = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e \u003cspan class=\"hljs-built_in\"\u003eDate\u003c/span\u003e();\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e timestamp = currentDate.getTime();\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(timestamp); \u003cspan class=\"hljs-comment\"\u003e// Outputs: 1696425660603\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e The \u003ccode\u003egetTime()\u003c/code\u003e method returns the timestamp in \u003cem\u003emilliseconds\u003c/em\u003e. If you need the timestamp in \u003cem\u003eseconds\u003c/em\u003e, you can divide the result by 1000.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"howtoconvertadatestringtotimestamp\"\u003eHow to Convert a Date String to Timestamp\u003c/h2\u003e\n\u003cp\u003eSo what if we have a date in string format? It'll be a similar process as before, but with the extra step of converting the string to a \u003ccode\u003eDate\u003c/code\u003e object and then the timestamp.\u003c/p\u003e\n\u003cp\u003eJust make sure your date string is in a format that the \u003ccode\u003eDate\u003c/code\u003e constructor can understand. According to \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format\"\u003eMDN\u003c/a\u003e:\u003c/p\u003e\n\u003cblockquote\u003e\n\u003cp\u003eThe JavaScript specification only specifies one format to be universally supported: the \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-time-string-format\"\u003edate time string format\u003c/a\u003e, a simplification of the ISO 8601 calendar date extended format. The format is as follows:\u003cbr\u003e\n聽\u003cbr\u003e\n\u003ccode\u003eYYYY-MM-DDTHH:mm:ss.sssZ\u003c/code\u003e\u003c/p\u003e\n\u003c/blockquote\u003e\n\u003cp\u003eApparently other formats do work, but are implementation-dependent and may not work across all browsers.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e dateString = \u003cspan class=\"hljs-string\"\u003e\u0026quot;2023-10-04\u0026quot;\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e dateObject = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e \u003cspan class=\"hljs-built_in\"\u003eDate\u003c/span\u003e(dateString);\n\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e timestamp = dateObject.getTime();\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(timestamp); \u003cspan class=\"hljs-comment\"\u003e// Outputs: 1696377600000\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eSo the date string should be in a format recognized by the \u003ccode\u003eDate.parse()\u003c/code\u003e method (used internally by the \u003ccode\u003eDate\u003c/code\u003e constructor). While the above format is formally specified, you can also use more shorthand dates like \u0026quot;YYYY-MM-DD\u0026quot;.\u003c/p\u003e\n\u003ch2 id=\"othersolutions\"\u003eOther Solutions\u003c/h2\u003e\n\u003cp\u003eWhile we've focused on the \u003ccode\u003eDate\u003c/code\u003e object and its \u003ccode\u003egetTime()\u003c/code\u003e method for converting a date to a timestamp in JavaScript, there are other ways to achieve the same thing. For instance, the \u003ccode\u003evalueOf()\u003c/code\u003e method returns the primitive value of a \u003ccode\u003eDate\u003c/code\u003e object as a number data type, which is the timestamp.\u003c/p\u003e\n\u003cp\u003eHere's an example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e date = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e \u003cspan class=\"hljs-built_in\"\u003eDate\u003c/span\u003e();\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(date.valueOf()); \u003cspan class=\"hljs-comment\"\u003e// Output: 1696428432208\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe \u003ccode\u003e+\u003c/code\u003e operator can also be used to convert a \u003ccode\u003eDate\u003c/code\u003e object to a timestamp. This works because the \u003ccode\u003e+\u003c/code\u003e operator triggers the \u003ccode\u003evalueOf()\u003c/code\u003e method behind the scenes in order to do any mathematical operation on the date.\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e date = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e \u003cspan class=\"hljs-built_in\"\u003eDate\u003c/span\u003e();\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(+date); \u003cspan class=\"hljs-comment\"\u003e// Output: 1696428432208\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e While these methods achieve the same result, it's important to understand how they work and when to use them. The \u003ccode\u003e+\u003c/code\u003e operator, for example, might be less clear to someone reading your code than the explicit \u003ccode\u003egetTime()\u003c/code\u003e or \u003ccode\u003evalueOf()\u003c/code\u003e methods.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch2 id=\"commonerrorsandhowtoavoidthem\"\u003eCommon Errors and How to Avoid Them\u003c/h2\u003e\n\u003cp\u003eA common mistake when working with dates and timestamps in JavaScript is not accounting for time zones. JavaScript's \u003ccode\u003eDate\u003c/code\u003e object is \u003cstrong\u003ebased on the user's local time zone, but timestamps are always UTC\u003c/strong\u003e. This can lead to unexpected results if not handled correctly.\u003c/p\u003e\n\u003cp\u003eFor example, let's say you create a \u003ccode\u003eDate\u003c/code\u003e object for midnight on a specific date:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003elet\u003c/span\u003e date = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e \u003cspan class=\"hljs-built_in\"\u003eDate\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026#x27;2023-10-04T00:00:00\u0026#x27;\u003c/span\u003e);\n\u003cspan class=\"hljs-built_in\"\u003econsole\u003c/span\u003e.log(date.getTime()); \u003cspan class=\"hljs-comment\"\u003e// Output: 1696428432208\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eDepending on your local time zone, the timestamp might not represent midnight UTC, but some other time. To avoid this, always create \u003ccode\u003eDate\u003c/code\u003e objects in UTC when you plan to convert them to timestamps.\u003c/p\u003e\n\u003cp\u003eAnother common mistake is using the \u003ccode\u003eDate.parse()\u003c/code\u003e method to convert a date string to a timestamp. While this can work, it's not recommended because \u003ccode\u003eDate.parse()\u003c/code\u003e has inconsistent behavior across different browsers and can lead to some very hard-to-find bugs!\u003c/p\u003e\n\u003ch2 id=\"usecasesofdatetimestampconversion\"\u003eUse-Cases of Date/Timestamp Conversion\u003c/h2\u003e\n\u003cp\u003eConverting dates to timestamps is useful in many situations. For example, timestamps are often used in APIs and databases to record when an event occurred. By storing the time as a timestamp, you can easily compare times and calculate durations鈥攕omething that's much harder, or more error-prone, with date strings.\u003c/p\u003e\n\u003cp\u003eTimestamps are also handy for performance testing. By taking a timestamp at the start and end of a process, you can calculate how long it took. This is a common technique in JavaScript and other programming languages. You'd do this by creating new \u003ccode\u003eDate\u003c/code\u003e objects at the start/end of the process, but then you'd need to convert to timestamp to be able to find the difference between the two.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this Byte, we've learned how to convert a date to a timestamp in JavaScript using the \u003ccode\u003eDate\u003c/code\u003e object's \u003ccode\u003egetTime()\u003c/code\u003e method. We've also looked at alternative methods, common errors to avoid, and some use-cases for date and timestamp conversion.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":15,"published_by":null,"published_at":1696431660000,"created_by":1,"updated_by":null,"created_at":1696425119379,"updated_at":1696428781843,"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":2109,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"tags":[{"id":45,"name":"javascript","slug":"javascript","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1432589001000,"updated_at":1432589001000,"_pivot_content_id":2109,"_pivot_tag_id":45,"_pivot_sort_order":0},{"id":48,"name":"node","slug":"node","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1437348872000,"updated_at":1437348872000,"_pivot_content_id":2109,"_pivot_tag_id":48,"_pivot_sort_order":1}],"_pivot_tag_id":45,"_pivot_content_id":2109}],"content_count":"375"},"page":1,"error":null},"__N_SSP":true},"page":"/tag/[...slug]","query":{"slug":["javascript"]},"buildId":"1740324887682","isFallback":false,"isExperimentalCompile":false,"gssp":true,"scriptLoader":[]}</script></body></html>