<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amitav Mishra on Medium]]></title>
        <description><![CDATA[Stories by Amitav Mishra on Medium]]></description>
        <link>https://medium.com/@amitavmishra99?source=rss-ce60062d05dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5Onf6sQjtrribeMZUIIceA.jpeg</url>
            <title>Stories by Amitav Mishra on Medium</title>
            <link>https://medium.com/@amitavmishra99?source=rss-ce60062d05dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:44:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitavmishra99/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Play Audio with HTMLAudioElement API in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/play-audio-with-htmlaudioelement-api-in-javascript-6f3f2530d58e?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3f2530d58e</guid>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Sat, 15 Jul 2023 15:49:52 GMT</pubDate>
            <atom:updated>2023-07-16T17:51:11.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*caYyQ79eKCeSpXxm" /><figcaption>Photo by <a href="https://unsplash.com/fr/@fhavlik?utm_source=medium&amp;utm_medium=referral">Filip</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The HTMLAudioElement API has access to all the properties and methods of the HTML &lt;audio&gt; element. This API allows us to play audio without even creating the &lt;audio&gt; elements. The Audio() constructor creates and returns a new HTMLAudioElement object.</p><pre>const audio = new Audio(&#39;nature.wav&#39;);</pre><p>This API inherits properties and methods from the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">HTMLMediaElement</a> API that are needed to use the media capabilities like play, pause, mute, etc. Let’s discuss some of them.</p><h3>Methods</h3><h4>The play() method</h4><p>This method is used to play the audio. It returns a <a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript">Promise</a> which resolves when the audio successfully starts and rejects if any error occurs in starting the audio.</p><pre>const audio = new Audio(&#39;nature.wav&#39;);<br>audio.play();</pre><h4>The pause() method</h4><p>This method pauses the audio.</p><pre>audio.pause();</pre><h4>The load() method</h4><p>This method loads or resets the audio. If we call this method, the audio will start from the beginning when we play it next time.</p><pre>audio.load();</pre><p><strong>Use case 1 — Load:</strong></p><p>When we create a new HTMLAudioElement object and call the play() method for the first time, it takes some time to load and play the audio. So, for a scenario where we instantly want to play the audio on a button click or something, we see a delay.</p><p>To fix this delay, we can use the load() method to load the audio beforehand and keep it ready, so that the next time we call play(), it will start playing without any delay.</p><pre>const audio = new Audio(&#39;nature.wav&#39;);<br>audio.load();<br><br>// now play the audio whenever you want<br>audio.play();</pre><p><strong>Use case 2 — Reset:</strong></p><p>If we want to stop the ongoing audio, and we want it to play from the beginning the next time we play it, then we can use the load() method to reset the audio after we pause it.</p><pre>audio.pause();<br>audio.load();</pre><h3>Properties</h3><h4>duration</h4><p>It returns the total duration of the audio in seconds.</p><pre>console.log(audio.duration);</pre><h4>currentTime</h4><p>It is used to set or get the current playback time in seconds. If we change its value, it seeks the audio to the new provided time. If we set a time higher than the audio duration, it gets set to the audio duration.</p><pre>console.log(audio.currentTime);<br>audio.currentTime = 30;</pre><h4>loop</h4><p>It is used to set or get the loop value that indicates whether the audio should play repeatedly.</p><pre>const audio = new Audio(&#39;nature.wav&#39;);<br>console.log(audio.loop); // false<br>audio.loop = true;<br>console.log(audio.loop); // true</pre><h4>muted</h4><p>It is used to set or get the mute value of the audio.</p><pre>const audio = new Audio(&#39;nature.wav&#39;);<br>console.log(audio.muted); // false<br>audio.muted = true;<br>console.log(audio.muted); // true</pre><h4>volume</h4><p>It is used to set or get the volume of the audio. Its value ranges from 0.0 to 1.0. If we set any value higher than 1, it throws an error.</p><pre>const audio = new Audio(&#39;nature.wav&#39;);<br>console.log(audio.volume); // 1<br>audio.volume = 0.1;</pre><h3>You may also like</h3><ul><li><a href="https://jscurious.com/the-notification-api-in-javascript/">Send push notifications with the Notification API in JavaScript</a></li><li><a href="https://jscurious.com/currency-formatting-in-javascript/">How to add currency symbol and formatting to a number in JavaScript</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/the-urlsearchparams-api/">The URLSearchParams API in JavaScript</a></li><li><a href="https://jscurious.com/map-in-javascript-and-how-it-is-better-than-object/">Map in JavaScript and when its a better choice than Object</a></li><li><a href="https://jscurious.com/different-ways-to-check-if-a-key-exists-in-an-object/">Different ways to check if a key exists in an object in JavaScript</a></li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">A brief guide to Promises in JavaScript</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tips and tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3f2530d58e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/play-audio-with-htmlaudioelement-api-in-javascript-6f3f2530d58e">Play Audio with HTMLAudioElement API in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Generator functions — a complete guide]]></title>
            <link>https://javascript.plainenglish.io/javascript-generator-functions-a-complete-guide-52c2ead5af23?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c2ead5af23</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 14:35:09 GMT</pubDate>
            <atom:updated>2022-12-02T00:53:30.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Generator Functions — a Complete Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oq7OgkziWMSmaxJs" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript Generators are a special type of function which lets you suspend the function execution and then come back later and resume the execution.</p><p>We can define a generator function with the function keyword followed by an asterisk (function*). Currently, there is no such option available for arrow functions to create generator functions.</p><p>The generator function provides a powerful keyword called yield which pauses the function execution and returns the yield expression value.</p><pre>function* generatorFn() {<br>    console.log(&#39;start&#39;);<br>    yield 1;<br>    console.log(&#39;After yield 1&#39;);<br>    yield 2;<br>    console.log(&#39;end&#39;);<br>}</pre><p>The generator function doesn’t execute right away when we invoke it. Instead, it returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">Generator</a> object which contains three utility methods.</p><ul><li>next()</li><li>return()</li><li>throw()</li></ul><h3>The next() method</h3><p>When we call the next() method, the Generator function executes until the next yield expression. This method returns an object containing a value property that holds the yielded value and a done property that holds a boolean value that indicates if the function has finished its execution or not.</p><pre>function* generatorFn() {<br>    console.log(&#39;start&#39;);<br>    yield 10;<br>    console.log(&#39;After yield 10&#39;);<br>    console.log(&#39;X&#39;, yield 20);<br>    console.log(&#39;end&#39;);<br>}<br><br>const gen = generatorFn();<br>console.log(gen.next());<br>console.log(gen.next());<br>console.log(gen.next());</pre><p>Output:</p><pre>start<br>{ value: 10, done: false }<br>After yield 10<br>{ value: 20, done: false }<br>X undefined<br>end<br>{ value: undefined, done: true }</pre><p><strong>Code explanation:<br></strong>First next() call – function will execute till first yield expression yield 10. Therefore, “start” will be printed and an object will be returned by yield 10 containing properties value as “10” and done as false.</p><p>Second next() call – function will start the execution from the second line (without yield expression) till the next yield expression yield 20. Remember when execution pauses on a line, it only executes the yield expression and the rest of the statement will execute in the next next() call. So, here on the second next() call, only yield 20 will execute and pause, and the rest console statement will execute in the next iteration.</p><p>Third next() call – function will start its execution from the fourth line, executing the console statement and replacing yield 20 with undefined (as we passed no argument in next(). we’ll learn more about it later). As there are no more yield expression left, execution will continue till the end and return the object containing value as undefined and done as true.</p><p>Once the execution is finished, call to next() will always return the object with properties value as undefined and done as true.</p><h4>Placing a return statement inside the generator function</h4><p>If we have a return statement inside the generator function, then the return statement will finish the execution and the returned object will have value as the returned value and done as true.</p><pre>function* generator() {<br>    yield 1;<br>    return 5;<br>}<br><br>const gen = generator();<br>console.log(gen.next());<br>// { value: 1, done: false }<br>console.log(gen.next());<br>// { value: 5, done: true }</pre><p>If we place the return statement before any yield expression, the return statement will finish the execution and the yield expression will be ignored.</p><pre>function* generator() {<br>    yield 1;<br>    return 5;<br>    yield 10;<br>}<br><br>const gen = generator();<br>console.log(gen.next()); <br>// { value: 1, done: false }<br>console.log(gen.next()); <br>// { value: 5, done: true }<br>console.log(gen.next()); <br>// { value: undefined, done: true }</pre><h4>Passing value in next() method</h4><p>We can call the next() method with an argument, which will replace the last executed yield expression where the execution was paused with the argument value.</p><pre>function* generator() {<br>    yield 10;<br>    const third = yield 20;<br>    yield third;<br>}<br><br>const gen = generator();<br>console.log(gen.next()); <br>// { value: 10, done: false }<br>console.log(gen.next(55)); <br>// { value: 20, done: false }<br>console.log(gen.next(99)); <br>// { value: 99, done: false }<br>console.log(gen.next()); <br>// { value: undefined, done: true }</pre><p>Here, when the first next() is called, yield 10 executed and execution was paused there.</p><p>When next(55) is called, it replaced the last yield expression i.e. yield 10 with “55” (We are not using this value here so we won’t see a difference), then executed yield 20 and execution paused there.</p><p>When next(99) is called, it replaced the last yield expression i.e. yield 20 with “99” and assigned value “99” to variable “third”. Then yield third executed and returned object with properties value as “99” and paused execution there.</p><p>Finally, when the last next() is called, code after the last yield executed, here there was no code available after the last yield so it simply finished the execution and returned the object with done as true.</p><h3>The return() method</h3><p>When we call the return() method, it will finish the function execution there itself where the execution was paused. It will return an object with properties value as undefined and done as true. We can also pass a value in the return() method which will replace the value property in the returned object.</p><pre>function* generator() {<br>  console.log(&quot;start&quot;);<br>  yield 10;<br>  console.log(&quot;after yield 10&quot;);<br>  yield 20;<br>  console.log(&quot;end&quot;);<br>}<br><br>const gen = generator();<br>console.log(gen.next());<br>console.log(gen.return(55));<br>console.log(gen.next());</pre><p>Output:</p><pre>start<br>{ value: 10, done: false }<br>{ value: 55, done: true }<br>{ value: undefined, done: true }</pre><h3>The throw() method</h3><p>This method basically stops the execution there itself and throws an exception. This method won’t return any object like next() and return() does. We can pass any error information to this method for debugging purposes.</p><pre>function* generator() {<br>  console.log(&quot;start&quot;);<br>  yield 10;<br>  console.log(&quot;after yield 10&quot;);<br>  yield 20;<br>  console.log(&quot;end&quot;);<br>}<br><br>const gen = generator();<br>console.log(gen.next());<br>console.log(gen.throw(new Error(&#39;Some error occured&#39;)));<br>console.log(gen.next());</pre><p>Output:</p><pre>start<br>{ value: 10, done: false }<br>Uncaught Error: Some error occured</pre><h3>Generator object as an iterator</h3><p>The generator object is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol">iterable</a>, so we can easily loop through it and use the values returned by each yield expression.</p><pre>function* generator() {<br>  yield 25;<br>  yield 45;<br>  yield 65;<br>}<br><br>// using for...of loop<br>for (let value of generator()) {<br>  console.log(value);<br>}<br>// 25<br>// 45<br>// 65<br><br>// Array.from()<br>console.log(Array.from(generator())); <br>// [25, 45, 65]<br><br>// spread operator<br>console.log([...generator()]); <br>// [25, 45, 65]</pre><h3>Using the yield* keyword with iterables</h3><p>The yield* keyword iterates over the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol">iterable</a> operand and yields each value returned by it. This keyword must be used with iterables only, else it will throw an error.</p><p>Some of the built-in iterables are Array, Map, String, Generators, etc.</p><h4>Example with string and array</h4><pre>function* generator() {<br>  yield 10;<br>  yield [20, 30];<br>  yield* [40, 50];<br>  yield &#39;html&#39;;<br>  yield* &#39;js&#39;;<br>}<br><br>const gen = generator();<br><br>console.log(gen.next().value); // 10<br>console.log(gen.next().value); // [20, 30]<br>console.log(gen.next().value); // 40<br>console.log(gen.next().value); // 50<br>console.log(gen.next().value); // html<br>console.log(gen.next().value); // j<br>console.log(gen.next().value); // s</pre><h4>Example with generator</h4><pre>// print a series of numbers like 1223334444...n(n times)<br><br>function* repeat(n) {<br>  let count = 1;<br>  while (count &lt;= n) {<br>    yield n;<br>    count++;<br>  }<br>}<br><br>function* generateSequence(n) {<br>  let count = 1;<br>  while (count &lt;= n) {<br>    yield* repeat(count);<br>    count++;<br>  }<br>}<br><br>const gen = generateSequence(3);<br>console.log(gen.next().value); // 1<br>console.log(gen.next().value); // 2<br>console.log(gen.next().value); // 2<br>console.log(gen.next().value); // 3<br>console.log(gen.next().value); // 3<br>console.log(gen.next().value); // 3<br>console.log(gen.next().value); // undefined</pre><h3>Multiple instances of a generator function</h3><p>We can create multiple instances of generators and they don’t interfere with each other’s execution and work independently. Let’s see one example.</p><pre>function* generator() {<br>  yield 10;<br>  yield 20;<br>}<br><br>const gen1 = generator();<br>const gen2 = generator();<br><br>console.log(gen1.next()); <br>// { value: 10, done: false }<br>console.log(gen1.next()); <br>// { value: 20, done: false }<br>console.log(gen2.next());<br>// { value: 10, done: false }<br>console.log(gen1.next()); <br>// { value: undefined, done: true }<br>console.log(gen2.next()); <br>// { value: 20, done: false }<br>console.log(gen2.next()); <br>// { value: undefined, done: true }</pre><h3>You may also like</h3><ul><li><a href="https://jscurious.com/the-notification-api-in-javascript/">Send push notifications with the Notification API in JavaScript</a></li><li><a href="https://jscurious.com/play-audio-with-htmlaudioelement-api-in-javascript/">Play audio with HTMLAudioElement API in JavaScript</a></li><li><a href="https://jscurious.com/map-in-javascript-and-how-it-is-better-than-object/">Map in JavaScript and when its a better choice than Object</a></li><li><a href="https://jscurious.com/different-ways-to-check-if-a-key-exists-in-an-object/">Different ways to check if a key exists in an object in JavaScript</a></li><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">A brief guide to Promises in JavaScript</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript/">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/javascript-object-is-method/">JavaScript Object.is() method to check equality of two values</a></li><li><a href="https://jscurious.com/the-css-is-and-where-pseudo-classes/">The CSS :is() and :where() pseudo-classes</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tips and tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c2ead5af23" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-generator-functions-a-complete-guide-52c2ead5af23">JavaScript Generator functions — a complete guide</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The URLSearchParams API in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-urlsearchparams-api-in-javascript-19748ef513d5?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/19748ef513d5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 17:20:21 GMT</pubDate>
            <atom:updated>2022-10-21T15:19:19.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ET4DLWGsZHUaDhOC" /><figcaption>Photo by <a href="https://unsplash.com/@nublson?utm_source=medium&amp;utm_medium=referral">Nubelson Fernandes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The URLSearchParams API provides utility methods to parse data from the query string of an <a href="https://developer.mozilla.org/en-US/docs/Glossary/URL">URL</a>. The URLSearchParams() constructor creates a new URLSearchParams object from the query string and returns it. It ignores the leading question mark ? in the query string, so we can pass the query string without a leading ? also.</p><pre>// URL: <a href="https://myshop.com/mobiles?color=black&amp;sort=price_asc">https://myshop.com/mobiles?color=black&amp;sort=price_asc</a><br>const search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&#39;);</pre><p>The URLSearchParams() constructor can’t parse data correctly if we provide the full URL instead of the query string. If we have a full URL, we can use the <a href="https://jscurious.com/the-url-api-in-javascript/">URL API</a> to parse the query string out of it and pass it to the URLSearchParams() constructor.</p><pre>// Wrong way<br>const search = new URLSearchParams(&#39;<a href="https://myshop.com/mobiles?color=black&amp;sort=price&#39;">https://myshop.com/mobiles?color=black&amp;sort=price&#39;</a>);</pre><pre>// Correct way<br>const url = new URL(&#39;<a href="https://myshop.com/mobiles?color=black&amp;sort=price&#39;">https://myshop.com/mobiles?color=black&amp;sort=price&#39;</a>);<br>const search = new URLSearchParams(url.search);<br>// OR pass the query string directly <br>const search = new URLSearchParams(&#39;color=black&amp;sort=price&#39;);</pre><h3>Utility methods</h3><p>The URLSearchParams utility methods let us easily access the query parameters and also let us add new or modify any existing parameter. Let’s explore them all.</p><h4>The get() method</h4><p>This method takes the query parameter name and returns the value of the first match. If no match is found, it returns null.</p><pre>const search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&amp;color=red&#39;);<br>console.log(search.get(&#39;color&#39;)); // &#39;black&#39;<br>console.log(search.get(&#39;brand&#39;)); // null</pre><h4>The getAll() method</h4><p>This method takes the query parameter name and returns all the associated values as an array. If no match is found, it returns an empty array.</p><pre>const search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&amp;color=red&#39;);<br>console.log(search.getAll(&#39;color&#39;)); // [&#39;black&#39;, &#39;red&#39;]<br>console.log(search.getAll(&#39;sort&#39;)); // [&#39;price_asc&#39;]<br>console.log(search.getAll(&#39;brand&#39;)); // []</pre><h4>The has() method</h4><p>This method checks whether the provided parameter is present in the query string or not. If the parameter exists, it returns true otherwise returns false.</p><pre>const search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&#39;);<br>console.log(search.has(&#39;sort&#39;)); // true<br>console.log(search.has(&#39;brand&#39;)); // false</pre><h4>The forEach() method</h4><p>This method lets us iterate through all the query parameter values.</p><pre>const search = new URLSearchParams(&quot;color=black&amp;sort=price_asc&quot;);<br>search.forEach((value, key) =&gt; console.log(key, value));<br>// color black<br>// sort price_asc</pre><h4>The keys() method</h4><p>This method returns an Iterator object containing all the query parameter names. We can either use the for…of loop to iterate over this Iterator object or convert it to an array using the spread operator or Array.from() method.</p><pre>const search = new URLSearchParams(&quot;color=black&amp;sort=price_asc&quot;);<br>for (const key of search.keys()) {<br>  console.log(key);<br>}<br>/* -output-<br>    color<br>    sort<br>*/</pre><pre>// convert to Array<br>console.log([...search.keys()]); // [&#39;color&#39;, &#39;sort&#39;]<br>// OR<br>console.log(Array.from(search.keys())); // [&#39;color&#39;, &#39;sort&#39;]</pre><h4>The values() method</h4><p>This method returns an Iterator object containing all the query parameter values.</p><pre>const search = new URLSearchParams(&quot;color=black&amp;sort=price_asc&quot;);<br>console.log([...search.values()]); // [&#39;black&#39;, &#39;price_asc&#39;]</pre><h4>The entries() method</h4><p>This method returns an Iterator object containing all the key-value pairs of query parameter and their values.</p><pre>const search = new URLSearchParams(&quot;color=black&amp;sort=price_asc&quot;);<br>console.log([...search.entries()]); <br>// [[&#39;color&#39;, &#39;black&#39;], [&#39;sort&#39;, &#39;price_asc&#39;]]</pre><h4>The append() method</h4><p>This method appends a new query parameter with value to the existing query string.</p><pre>const search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&#39;);<br>search.append(&#39;brand&#39;, &#39;apple&#39;);<br>console.log(search.toString()); <br>// &#39;color=black&amp;sort=price_asc&amp;brand=apple&#39;</pre><h4>The set() method</h4><p>This method replaces any existing query parameter value with the provided one, and if the provided parameter doesn’t exist, it appends it. If multiple occurrences are present for the provided parameter, it removes them and replaces only the first one’s value.</p><pre>const search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&amp;color=red&#39;);<br>search.set(&#39;sort&#39;, &#39;popularity&#39;);<br>search.set(&#39;color&#39;, &#39;green&#39;);<br>search.set(&#39;brand&#39;, &#39;apple&#39;);<br>console.log(search.toString()); <br>// &#39;color=green&amp;sort=popularity&amp;brand=apple&#39;</pre><h4>The delete() method</h4><p>This method deletes all the entries associated with the provided query parameter key.</p><pre>search = new URLSearchParams(&#39;color=black&amp;sort=price_asc&amp;color=red&#39;);<br>search.delete(&#39;color&#39;);<br>search.delete(&#39;brand&#39;);<br>console.log(search.toString()); // &#39;sort=price_asc&#39;</pre><h4>The sort() method</h4><p>This method sorts the query string by the keys, and if multiple keys with the same name are present, then their relative order will be preserved.</p><pre>const search = new URLSearchParams(&#39;sort=price&amp;ram=8gb&amp;color=red&amp;ram=4gb&#39;);<br>search.sort();<br>console.log(search.toString()); <br>// color=red&amp;ram=8gb&amp;ram=4gb&amp;sort=price</pre><h3>You may also like</h3><ul><li><a href="https://jscurious.com/the-url-api-in-javascript/">The URL API in JavaScript</a></li><li><a href="https://jscurious.com/the-notification-api-in-javascript/">Send push notifications with the Notification API in JavaScript</a></li><li><a href="https://jscurious.com/play-audio-with-htmlaudioelement-api-in-javascript/">Play audio with HTMLAudioElement API in JavaScript</a></li><li><a href="https://jscurious.com/map-in-javascript-and-how-it-is-better-than-object/">Map in JavaScript and when its a better choice than Object</a></li><li><a href="https://jscurious.com/different-ways-to-check-if-a-key-exists-in-an-object/">Different ways to check if a key exists in an object in JavaScript</a></li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">A brief guide to Promises in JavaScript</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript/">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tips and tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>, and</em></strong><em> </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19748ef513d5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-urlsearchparams-api-in-javascript-19748ef513d5">The URLSearchParams API in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Set Object — to Store Unique Values]]></title>
            <link>https://javascript.plainenglish.io/javascript-set-object-to-store-unique-values-e330ab7a886c?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e330ab7a886c</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 14:33:34 GMT</pubDate>
            <atom:updated>2022-12-01T15:44:02.638Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Set Object — to Store Unique Values</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a-tXr1ntckOqUkYL" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Set in JavaScript is a special type of object which lets us store unique values. It works for values of both primitive and non-primitive data types.</p><p>When it comes to storing a bunch of data, we can always go for Arrays. But if we want to store unique values, Set is a better option when compared to the Array. Though in the Array, we can manually filter out all the duplicate values, or we can check if the value already exists beforehand while adding to the collection.</p><pre>const set = new Set();</pre><p>The Set() constructor creates a new Set object. This constructor also accepts an optional argument that must be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol">iterable</a>. If we pass any argument, it will filter out all the non-duplicate values and add them to the new Set. But if we don’t pass one, the Set will be empty.</p><p>Some examples of built-in iterables are Array, Map, String, Generators, etc.</p><pre>const set1 = new Set();<br>console.log(set1); // Set(0) {size: 0}<br><br>const set2 = new Set([2, &#39;x&#39;, 5, true, 2, &#39;x&#39;, true, 6]);<br>console.log(set2); // Set(5) {2, &#39;x&#39;, 5, true, 6}<br><br>// checking for String<br>const set3 = new Set(&#39;world&#39;);<br>console.log(set3); // Set(5) {&#39;w&#39;, &#39;o&#39;, &#39;r&#39;, &#39;l&#39;, &#39;d&#39;}<br><br>// String with duplicate characters<br>const set4 = new Set(&#39;madam&#39;);<br>console.log(set4); // Set(3) {&#39;m&#39;, &#39;a&#39;, &#39;d&#39;}</pre><h3>Utility methods and property</h3><p>The Set object provides a couple of helper methods that we can use to add/delete values or check if any value exists and many more. Let’s find them all.</p><h4>The add() method</h4><p>This method adds value to the end of the Set object. If the value is already present in the Set, it won’t add it. This method returns the updated Set object.</p><pre>const set = new Set();<br>set.add(10); // Set(1) {10}<br>set.add(&#39;Hello&#39;); // Set(2) {10, &#39;Hello&#39;}<br>set.add(10); // Set(2) {10, &#39;Hello&#39;}<br>set.add(20); // Set(3) {10, &#39;Hello&#39;, 20}<br>set.add(&#39;Hello&#39;); // Set(3) {10, &#39;Hello&#39;, 20}</pre><p>When we add non-primitive values, Set tests their uniqueness by their references and not by their values. Let’s see one example.</p><pre>const ob1 = { x: 2 };<br>const ob2 = ob1;<br>const ob3 = { x: 2 };<br><br>const set = new Set();<br>set.add(ob1); // Set(1) {{...}}<br>set.add(ob2); // Set(1) {{...}}<br>set.add(ob3); // Set(2) {{...}, {...}}</pre><p>Here ob1 and ob2 are referencing the same object, so Set treated ob2 as duplicate and didn’t add it. On the other hand, ob3 has the same value as ob1 and ob2, but it is referencing a different object, so Set treated it as unique and added it.</p><blockquote><strong>Note:</strong> The Set considers all NaN values as same, though NaN !== NaN.</blockquote><p>The add() method is chainable.</p><pre>const set = new Set();<br>set.add(8).add(null).add(&quot;Hello&quot;).add(NaN).add();<br>// Set(5) {8, null, &#39;Hello&#39;, NaN, undefined}<br><br>set.add(NaN).add(undefined).add(null).add(false);<br>// Set(6) {8, null, &#39;Hello&#39;, NaN, undefined, false}</pre><h4>The delete() method</h4><p>This method removes the value from the Set. It takes the value as the argument that we want to remove from Set. If the passed value is present in the Set, delete() removes it and returns true otherwise, it returns false.</p><pre>const set = new Set();<br>set.add(8); // Set(1) {8}<br>set.add(&#39;Hello&#39;); // Set(2) {8, &#39;Hello&#39;}<br>set.delete(8); // true<br>set.delete(&#39;world&#39;); // false<br>console.log(set); // Set(1) {&#39;Hello&#39;}</pre><h4>The has() method</h4><p>This method checks whether a value is present in the Set or not. If the value exists, it returns true otherwise returns false.</p><pre>const set = new Set();<br>set.add(&#39;Hello&#39;); // Set(1) {&#39;Hello&#39;}<br>set.add(8); // Set(2) {&#39;Hello&#39;, 8}<br>set.delete(&#39;Hello&#39;); // Set(1) {8}<br>console.log(set.has(8)); // true<br>console.log(set.has(&#39;Hello&#39;)); // false</pre><h4>The clear() method</h4><p>This method removes all the values present in the Set object.</p><pre>const set = new Set([2, &quot;x&quot;, true, 10]);<br>set.clear();<br>console.log(set); // Set(0) {size: 0}</pre><h4>The size property</h4><p>This property returns the number of values present in the Set object.</p><pre>const set = new Set([2, &quot;x&quot;, 2, 5]);<br>console.log(set.size); // 3</pre><h4>The forEach() method()</h4><p>This method loops through the Set values and calls the provided callback function for each value.</p><pre>const set = new Set();<br>set.add(5).add(8).add(2); // Set(3) {5, 8, 2}<br>set.forEach((value) =&gt; {<br>  console.log(value);<br>});<br>/*<br>5<br>8<br>2<br>*/</pre><p>We can also use the for…of loop to iterate over Set.</p><pre>const set = new Set();<br>set.add(5).add(8).add(2); // Set(3) {5, 8, 2}<br>for (const value of set) {<br>  console.log(value);<br>}<br>/*<br>5<br>8<br>2<br>*/</pre><h3>Converting Set into Array</h3><p>There are many ways to convert a Set into an Array, but we will only discuss the easiest and most convenient ones. As we know, the Set is iterable, we can use the spread operator or Array.from() method to create an array from the Set.</p><pre>const set = new Set();<br>set.add(5).add(10).add(&#39;Hello&#39;); // Set(3) {5, 10, &#39;Hello&#39;}<br>const arr1 = [...set];<br>const arr2 = Array.from(set);<br>console.log(arr1); // [5, 10, &#39;Hello&#39;]<br>console.log(arr2); // [5, 10, &#39;Hello&#39;]</pre><h3>Removing duplicates from Array using Set</h3><p>To remove duplicates from Array using Set, first, we can create a Set object from Array and then convert the Set back to Array.</p><pre>const arr = [10, 5, 20, 10, 6, 5, 8, 5, 20];<br>const set = new Set(arr);<br>const newArr = [...set];<br>console.log(newArr); // [10, 5, 20, 6, 8]<br><br>// shorthand<br>console.log([...new Set(arr)]);</pre><h3>You may also like</h3><ul><li><a href="https://jscurious.com/map-in-javascript-and-how-it-is-better-than-object/">Map in JavaScript and when its a better choice than Object</a></li><li><a href="https://jscurious.com/play-audio-with-htmlaudioelement-api-in-javascript/">Play audio with HTMLAudioElement API in JavaScript</a></li><li><a href="https://jscurious.com/the-urlsearchparams-api/">The URLSearchParams API in JavaScript</a></li><li><a href="https://jscurious.com/object-defineproperty-method-in-javascript/">The Object.defineProperty() method in JavaScript</a></li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">A brief guide to Promises in JavaScript</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript/">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tips and tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e330ab7a886c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-set-object-to-store-unique-values-e330ab7a886c">JavaScript Set Object — to Store Unique Values</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Ways to Check if a Key Exists in an Object in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/5-ways-to-check-if-a-key-exists-in-an-object-in-javascript-53ad09dc2bf4?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ad09dc2bf4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Sat, 06 Aug 2022 18:46:59 GMT</pubDate>
            <atom:updated>2022-12-01T15:37:35.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xVnX7UbTQu-JGbr8" /><figcaption>Photo by <a href="https://unsplash.com/@walling?utm_source=medium&amp;utm_medium=referral">Walling</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Using the “in” operator</h3><p>The in operator returns true if the specified property is present in the specified object or in its prototype chain, otherwise it returns false.</p><pre>const app = { name: &#39;Instagram&#39;, type: &#39;Social Media&#39; };<br>console.log(&#39;name&#39; in app); // true<br>console.log(&#39;release_date&#39; in app); // false</pre><h3>Using the Reflect.has() method</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect">Reflect</a> is a built-in object that provides some utility methods for JavaScript operations. The has() method of this object returns true if the specified property is present in the specified object or in its prototype chain, otherwise it returns false. Syntax is: Reflect.has(targetObject, propertyKey);</p><p>Let’s use it in one example.</p><pre>const app = { name: &#39;Instagram&#39;, type: &#39;Social Media&#39; };<br>console.log(Reflect.has(app, &#39;name&#39;)); // true<br>console.log(Reflect.has(app, &#39;release_date&#39;)); // false</pre><h3>Using the hasOwnProperty() method</h3><p>This method is present in the object prototype. So any object which is not created with Object.create(null), has access to this method. This method returns true if the specified property is present in the object (not inherited), otherwise, it returns false.</p><pre>const app = { name: &#39;Instagram&#39;, type: &#39;Social Media&#39; };<br>console.log(app.hasOwnProperty(&#39;type&#39;)); // true<br>console.log(app.hasOwnProperty(&#39;founder_name&#39;)); // false</pre><h3>By accessing the property and comparing it with “undefined”</h3><p>If we access any property that doesn’t exist on the object, it returns undefined. This way, we can access the property and compare its value with undefined to know whether it exists or not.</p><pre>const app = { name: &#39;Instagram&#39;, type: &#39;Social Media&#39; };<br>console.log(app[&#39;name&#39;] === undefined); // false<br>console.log(app[&#39;founder_name&#39;] === undefined); // true<br><br>// or simply use an if block without comparing to undefined<br>if (app[&#39;founder_name&#39;]) {<br>    // do your work<br>}</pre><p>We can’t determine the existence of a property with this approach when a property exists in the object and has a value of undefined.</p><pre>const auth = { token: undefined };<br>console.log(auth[&#39;token&#39;] === undefined); // true<br>console.log(auth[&#39;timestamp&#39;] === undefined); // true</pre><h3>The Object.hasOwn() method (ES2022 update)</h3><p>This method returns true if the specified property is present in the object (not inherited), otherwise it returns false.</p><pre>const app = { name: &#39;Instagram&#39;, type: &#39;Social Media&#39; };<br>console.log(Object.hasOwn(app, &#39;type&#39;)); // true<br>console.log(Object.hasOwn(app, &#39;founder_name&#39;)); // false</pre><p>Apart from the hasOwnProperty() and hasOwn() method, the other three ways work fine in the case of inherited properties. Let’s see one example of that.</p><pre>function square(side) {<br>    this.side = side;<br>}<br><br>square.prototype.getArea = function () {<br>    return Math.pow(this.side, 2);<br>}<br><br>const sq = new square(5);<br>console.log(sq); // { side: 5 };<br>console.log(sq.getArea()); // 25<br>/*<br> Here &quot;side&quot; will be part of own object whereas<br> &quot;getArea&quot; will be inherited through prototype chain.<br>*/<br><br>// checking with &#39;in&#39;<br>console.log(&#39;side&#39; in sq); // true<br>console.log(&#39;getArea&#39; in sq); // true<br><br>// checking with &#39;Reflect.has()&#39;<br>console.log(Reflect.has(sq, &#39;side&#39;)); // true<br>console.log(Reflect.has(sq, &#39;getArea&#39;)); // true<br><br>// checking with &#39;hasOwnProperty()&#39;<br>console.log(sq.hasOwnProperty(&#39;side&#39;)); // true<br>console.log(sq.hasOwnProperty(&#39;getArea&#39;)); // false<br><br>// comparing with &#39;undefined&#39;<br>console.log(sq[&#39;side&#39;] !== undefined); // true<br>console.log(sq[&#39;getArea&#39;] !== undefined); // true<br><br>// checking with &#39;hasOwn()&#39;<br>console.log(Object.hasOwn(sq, &#39;side&#39;)); // true<br>console.log(Object.hasOwn(sq, &#39;getArea&#39;)); // false</pre><h3>Conclusion</h3><p>The first two approaches (in operator and Reflect.has() method) is more prominent while the other three come with some limitations.</p><ul><li>As the name suggests, the hasOwnProperty() and hasOwn() methods work only for the object’s own properties and not for inherited properties.</li><li>The hasOwnProperty() method is not available for objects created with Object.create(null).</li><li>The “comparing with undefined” approach works fine unless the specified property exists but has undefined as value.</li></ul><h3>You may also like</h3><ul><li><a href="https://jscurious.com/map-in-javascript-and-how-it-is-better-than-object/">Map in JavaScript and when its a better choice than Object</a></li><li><a href="https://jscurious.com/javascript-set-object-to-store-unique-values/">JavaScript Set object to store unique values</a></li><li><a href="https://jscurious.com/the-notification-api-in-javascript/">Send push notifications with the Notification API in JavaScript</a></li><li><a href="https://jscurious.com/play-audio-with-htmlaudioelement-api-in-javascript/">Play audio with HTMLAudioElement API in JavaScript</a></li><li><a href="https://jscurious.com/object-defineproperty-method-in-javascript/">The Object.defineProperty() method in JavaScript</a></li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">A brief guide to Promises in JavaScript</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript/">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tips and tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>,</em></strong><em> and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ad09dc2bf4" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-ways-to-check-if-a-key-exists-in-an-object-in-javascript-53ad09dc2bf4">5 Ways to Check if a Key Exists in an Object in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief Guide to the Object.defineProperty() Method in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/a-brief-guide-to-object-defineproperty-method-in-javascript-400006e05dcc?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/400006e05dcc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 10:00:50 GMT</pubDate>
            <atom:updated>2022-07-04T03:00:20.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i6xgf44wkrs3zgWH" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Object.defineProperty() method adds or modifies a property in an object. We can use this method to provide extra configuration details about the object’s properties and control their behavior. The syntax is:</p><pre>Object.defineProperty(object, prop, descriptor);</pre><ul><li>object – Any object on which we want to define the property.</li><li>prop – The name of the property to be added or modified.</li><li>descriptor – It’s an object which specifies configuration details about the property.</li></ul><p>Let’s explore the properties that we can use in the descriptor object and what they do.</p><p>There are two types of properties available in any object, one is a data property that has a value, and another is an accessor property that is described by <a href="https://jscurious.com/javascript-getters-and-setters/">getter-setter</a> functions. The descriptor properties are different for both data and accessor properties, and we can’t use them together.</p><h3>Common descriptor properties</h3><p>The data and accessor properties have two descriptor properties in common, and they are as follows:</p><h4>configurable</h4><p>It indicates whether the property can be re-configurable (re-define using defineProperty()) or deleted. If not set, it defaults to false. If set to false, we can’t delete this property, and if we try to redefine it, it throws an error.</p><pre>const ob = { x: 20 };<br>Object.defineProperty(ob, &quot;x&quot;, { configurable: false });<br>delete ob.x;<br>console.log(ob); // { x: 20 }<br>// re-define property x<br>Object.defineProperty(ob, &quot;x&quot;, { configurable: true });<br>// TypeError: Cannot redefine property: x</pre><h4>enumerable</h4><p>It indicates whether the property appears during the enumeration of properties on the object. If not set, it defaults to false. If set to false, this property won’t appear in methods like Object.keys, Object.values, Object.entries, Object.assign, spread operator, for...in loop, etc.</p><pre>const ob = { x: 20, y: 30, z: 40 };<br>Object.defineProperty(ob, &quot;x&quot;, { enumerable: false });</pre><pre>console.log(Object.keys(ob)); // [&#39;y&#39;, &#39;z&#39;]<br>console.log(Object.assign({}, ob)); // { y: 30, z: 40 }<br>console.log({ ...ob }); // { y: 30, z: 40 }<br>for (const key in ob) {<br>  console.log(key); // y z<br>}</pre><h3>Data descriptor properties</h3><p>The data descriptor has two properties named value and writable. Let’s explore them.</p><h4>value</h4><p>It sets the value of the property. If not provided, it defaults to undefined.</p><pre>const ob = { x: 20 };<br>Object.defineProperty(ob, &quot;x&quot;, { value: 40 });<br>Object.defineProperty(ob, &quot;y&quot;, { value: 55 });<br>console.log(ob); // { x: 40, y: 55 }</pre><h4>writable</h4><p>It indicates whether the property value can be changed using the assignment operator (=). If not set, it defaults to false. If set to false, property value can’t be changed using the assignment operator but it still can be changed using the defineProperty() method.</p><pre>const ob = { x: 20 };<br>Object.defineProperty(ob, &quot;x&quot;, { writable: false });<br>ob.x = 100;<br>console.log(ob.x); // 20<br>Object.defineProperty(ob, &quot;x&quot;, { value: 55 });<br>console.log(ob.x); // 55</pre><blockquote>If any property is added while creating the object or through dot/bracket notation, then the default value of configurable, enumerable, and writable would be set to true.</blockquote><h3>Accessor descriptor properties</h3><p>The accessor descriptor also has two properties named get and set. Let’s explore them.</p><h4>get</h4><p>It is used to create a getter function. Default value is undefined.</p><pre>const ob = { x: 10 };<br>Object.defineProperty(ob, &quot;x2&quot;, {<br>  get: function () {<br>    return this.x ** 2;<br>  },<br>});</pre><pre>console.log(ob.x2); // 100</pre><h4>set</h4><p>It is used to create a setter function. Default value is undefined.</p><pre>const ob = {};<br>Object.defineProperty(ob, &quot;x&quot;, {<br>  get: function () {<br>    return this._x;<br>  },<br>  set: function(value) {<br>    this._x = value;<br>  }<br>});</pre><pre>console.log(ob.x); // undefined<br>ob.x = 99;<br>console.log(ob.x); // 99</pre><p>If we mix the data and accessor descriptor properties, it throws an error.</p><pre>const ob = {};<br>Object.defineProperty(ob, &quot;x&quot;, {<br>  value: 20,<br>  get: function () {<br>    return this._x;<br>  }<br>});</pre><pre>// TypeError: Invalid property descriptor. <br>// Cannot both specify accessors and a value or writable attribute</pre><blockquote>If neither of the data and accessor properties is mentioned in the defineProperty() method, then the property is treated as data property by default.</blockquote><p>So far, we have discussed how to set the property descriptor. Now let’s see how to view the descriptor of any property.</p><h3>The Object.getOwnPropertyDescriptor() method</h3><p>This method takes an object and its property name as arguments and returns the respective property descriptor object.</p><pre>const ob = { x: 20 };<br>console.log(Object.getOwnPropertyDescriptor(ob, &quot;x&quot;));<br>/*<br>{<br>  configurable: true,<br>  enumerable: true,<br>  value: 20,<br>  writable: true<br>}<br>*/<br>ob.y = 30;<br>console.log(Object.getOwnPropertyDescriptor(ob, &quot;y&quot;));<br>/*<br>{<br>  configurable: true,<br>  enumerable: true,<br>  value: 30,<br>  writable: true<br>}<br>*/<br>Object.defineProperty(ob, &quot;z&quot;, {<br>  value: 40,<br>  writable: true,<br>});<br>console.log(Object.getOwnPropertyDescriptor(ob, &quot;z&quot;));<br>/*<br>{<br>  configurable: false,<br>  enumerable: false,<br>  value: 40,<br>  writable: true<br>}<br>*/</pre><h3>You may also like</h3><ul><li><a href="https://jscurious.com/map-in-javascript-and-how-it-is-better-than-object/">Map in JavaScript and how it is better than Object</a></li><li><a href="https://jscurious.com/javascript-set-object-to-store-unique-values/">JavaScript Set object to store unique values</a></li><li><a href="https://jscurious.com/different-ways-to-check-if-a-key-exists-in-an-object/">Different ways to check if a key exists in an object in JavaScript</a></li><li><a href="https://jscurious.com/difference-between-object-freeze-object-seal-and-object-preventextensions/">Difference between Object.freeze(), Object.seal() and Object.preventExtensions(</a>)</li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">A brief guide to Promises in JavaScript</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript/">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Check out our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Community Discord</em></strong></a><em> and join our </em><a href="https://inplainenglish.pallet.com/talent/welcome"><strong><em>Talent Collective</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=400006e05dcc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/a-brief-guide-to-object-defineproperty-method-in-javascript-400006e05dcc">A Brief Guide to the Object.defineProperty() Method in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are JavaScript Getters and Setters?]]></title>
            <link>https://javascript.plainenglish.io/javascript-getters-and-setters-d5ac2cbb7287?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ac2cbb7287</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Mon, 09 May 2022 19:03:07 GMT</pubDate>
            <atom:updated>2022-05-11T01:02:52.202Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the ‘get’ and ‘set’ keywords in detail.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQNuKYhjaYspXE3IUdwZsw.jpeg" /></figure><p>The getters and setters are helpful to access object properties and manipulate them in an encapsulated way. Let’s explore these methods in detail.</p><h3>Getter</h3><p>The get keyword is used to create a getter function that will return a computed value. Unlike normal functions, we don’t need to call the getter function; instead, we can access it directly with its name.</p><pre>const person = {<br>  first_name: &#39;Peter&#39;,<br>  last_name: &#39;Parker&#39;,<br>  get full_name() {<br>      return `${this.first_name} ${this.last_name}`<br>  }<br>}</pre><pre>console.log(person.full_name); // Peter Parker</pre><p>The get keyword binds the getter function with an object property of the same name. When we access this object property, the getter function result gets returned.</p><p>Just remember, until and unless we access the object property, its value never gets calculated. That means it won’t execute the getter function and assign the returned value to the object property beforehand.</p><h3>Things to remember while creating getters</h3><ul><li>It should not have any parameters.</li><li>There should not be another data property or getter with the same name present.</li></ul><p>Like data properties, we can also delete getters.</p><pre>const obj = {<br>  get data() {<br>      return &#39;jscurious&#39;;<br>  }<br>}<br>delete obj.data;<br>console.log(obj.data); // undefined</pre><h3>Setter</h3><p>The set keyword is used to create a setter function. The set keyword binds the setter function with an object property of the same name. So, whenever we try to change the value of this object property, the setter function gets executed.</p><pre>const obj = {<br>  msg: &#39;&#39;,<br>  set message(value) {<br>    this.msg = value;<br>  }<br>}<br>obj.message = &#39;Hello&#39;;<br>console.log(obj.msg); // Hello</pre><h3>Things to remember while creating setters</h3><ul><li>It should exactly have one parameter.</li><li>There should not be another data property or setter with the same name present. But both getter and setter can have the same name.</li></ul><p>Like data properties, we can also delete setters.</p><pre>const obj = {<br>  msg: &#39;&#39;,<br>  set message(value) {<br>    this.msg = value;<br>  }<br>}<br>delete obj.message;</pre><h3>Using getter and setter inside a class</h3><p>Let’s create one encapsulated class. The class will have one private field that can be accessed only through setter and getter.</p><pre>class Square {<br>  #side_value;<br>  <br>  set side(value) {<br>    this.#side_value = value;<br>  }<br>  get side() {<br>    return this.#side_value;<br>  }<br>  get area() {<br>    return this.#side_value ** 2;<br>  }<br>}</pre><pre>const sq = new Square();<br>sq.side = 25;<br>console.log(sq.side); // 25<br>console.log(sq.area); // 625</pre><p>“<strong>Note:</strong> The # in field name indicates a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">private field</a> in class and it can’t be accessed outside the class. The ** (or the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation">exponentiation operator</a>) in area getter function is equivalent to Math.pow().”</p><h3>You may also like</h3><ul><li><a href="https://jscurious.com/javascript-set-object-to-store-unique-values/">JavaScript Set object to store unique values</a></li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/object-defineproperty-method-in-javascript/">A brief guide to Object.defineProperty() method</a></li><li><a href="https://jscurious.com/the-vibration-api-in-javascript/">The Vibration API in JavaScript</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/difference-between-object-freeze-object-seal-and-object-preventextensions/">Object.freeze() vs Object.seal() vs Object.preventExtensions()</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript shorthand coding tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ac2cbb7287" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-getters-and-setters-d5ac2cbb7287">What are JavaScript Getters and Setters?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Vibration API in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/the-vibration-api-in-javascript-64cda2a919a6?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/64cda2a919a6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Wed, 15 Dec 2021 18:17:42 GMT</pubDate>
            <atom:updated>2022-02-03T18:38:21.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2uC93d8wq6ocRWcv" /><figcaption>Photo by <a href="https://unsplash.com/@abeso?utm_source=medium&amp;utm_medium=referral">Sebastian Bednarek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vibrations are the best way to provide physical feedback to users for any action mostly for mobile users. For example, while showing a warning message or alert, while receiving a message or notification etc.</p><p>The Vibration API allows web apps to access the vibration hardware of the device (if exists) to create vibrations. It provides a method named navigator.vibrate() for the same purpose.</p><h3>The navigator.vibrate() method</h3><p>This method takes a value of vibration duration in milliseconds and vibrates the device for that long.</p><pre>navigator.vibrate(500); <br>// device will vibrate for 500ms</pre><p>The Vibration API doesn’t support in few of the browsers like IE, Opera, Safari, etc., so it will be better to check the browser support before using it.</p><pre>if (navigator.vibrate) {<br>   navigator.vibrate(500);<br>}</pre><h3>Vibrating in a pattern</h3><p>The vibrate() method can also accept an array of values as an argument. We can provide different values for how much time it will vibrate and how much time it won’t. It will vibrate for values at even index and pause for values at odd index.</p><pre>navigator.vibrate([320, 200, 320, 1000, 320, 200, 320]);</pre><p>Here it will first vibrate for 320ms and pause for 200ms, then again vibrate for 320ms and pause for 1000ms, and so on.</p><p>To cancel a running vibration, we can call vibrate() method by passing 0 or an empty array as an argument.</p><pre>navigator.vibrate(0);<br>// OR<br>navigator.vibrate([]);</pre><p>Try out these powerful codes and see them in action (Try this on a mobile device).</p><h3>You may also like</h3><ul><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/javascript-set-object-to-store-unique-values/">JavaScript Set object to store unique values</a></li><li><a href="https://jscurious.com/generator-functions-in-javascript/">Generator functions in JavaScript</a></li><li><a href="https://jscurious.com/javascript-getters-and-setters/">JavaScript getters and setters</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20+ JavaScript Shorthand coding tricks</a></li></ul><p><em>Thanks for your time :)</em><br><strong><em>Amitav Mishra</em></strong></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><strong><em>.</em></strong><em> Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter here</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64cda2a919a6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-vibration-api-in-javascript-64cda2a919a6">The Vibration API in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Async and Await — Your Asynchronous Buddies]]></title>
            <link>https://javascript.plainenglish.io/javascript-async-and-await-your-asynchronous-buddies-516fb5b1750?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/516fb5b1750</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 15:46:09 GMT</pubDate>
            <atom:updated>2021-07-03T23:03:47.620Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript Async and Await — Your Asynchronous Buddies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rdH-QCFoDElPKMzA" /><figcaption>Photo by <a href="https://unsplash.com/@photographybyniels?utm_source=medium&amp;utm_medium=referral">Niels Kehl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The async and await keywords help us in handling <a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">Promises</a> more conveniently and it is more readable than regular promise handling using then() and catch().</p><p>Let’s see how we consume Promises using .then() and .catch().</p><pre>let flag = true;</pre><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      if(flag) resolve(&#39;I am resolved&#39;);<br>      else reject(new Error(&#39;I am rejected&#39;));<br>    }, 1000);<br>});</pre><pre>promise.then(res =&gt; console.log(res)).catch(err =&gt; console.log(err));<br>// I am resolved</pre><p>The above Promise can be consumed by using async and await like below.</p><pre>async function demo() {<br>    let promise = new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&#39;I am resolved&#39;);<br>        }, 1000);<br>    });<br>    <br>    let res = await promise;<br>    console.log(res);  // I am resolved<br>}</pre><pre>demo();</pre><blockquote><em>The </em><em>await keyword should only be used inside an </em><em>async function.</em></blockquote><h3>The async keyword</h3><p>If we use async before any function then the function will return a Promise. If the function is not returning any Promise explicitly then it will wrap a Promise around the return value implicitly. Let’s see one example.</p><pre>async function greet() {<br>    return &#39;Welcome&#39;;<br>}</pre><pre>greet().then(res =&gt; console.log(res));<br>// Welcome</pre><h3>The await keyword</h3><p>The await keyword waits for a Promise and pauses the code in that line until the Promise gets resolved. Remember the await keyword should always be used inside the async function otherwise, it will throw an error.</p><pre>async function foo() {<br>    let promise = new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&#39;I am resolved&#39;);<br>        }, 1000);<br>    });</pre><pre>let res = await promise;<br>    console.log(res);<br>    console.log(&#39;end&#39;);<br>}</pre><pre>foo();<br>// I am resolved<br>// end</pre><p>Here the code execution gets paused in the line where await is used and resumes when the Promise resolves. Therefore after 1 second when the Promise will resolve, the console statements will be printed.</p><h3>Handling Errors</h3><p>We can use the <a href="https://jscurious.com/javascript-error-handling-using-try-catch/">try…catch</a> block to handle errors in async / await.</p><pre>async function foo() {<br>    let promise = new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            reject(new Error(&#39;I am rejected&#39;));<br>        }, 1000);<br>    });</pre><pre>try {<br>        let res = await promise;<br>        console.log(res);<br>    } catch (e) {<br>        console.log(e);<br>    }<br>}</pre><pre>foo();<br>// Error: I am rejected</pre><h3>References</h3><ul><li><a href="https://jscurious.com/a-brief-guide-to-promises-in-javascript/">Promises in JavaScript</a></li><li><a href="https://jscurious.com/callback-functions-in-javascript/">Callback functions in JavaScript</a></li><li><a href="https://jscurious.com/javascript-error-handling-using-try-catch/">JavaScript Error Handling using try…catch</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=516fb5b1750" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-async-and-await-your-asynchronous-buddies-516fb5b1750">JavaScript Async and Await — Your Asynchronous Buddies</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief Guide to Promises in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/a-brief-guide-to-promises-in-javascript-226f33f5230e?source=rss-ce60062d05dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/226f33f5230e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Amitav Mishra]]></dc:creator>
            <pubDate>Sun, 16 May 2021 06:29:38 GMT</pubDate>
            <atom:updated>2021-07-11T15:09:44.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-mGE9FjKkWbA22Og" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A Promise in JavaScript is an object which returns a result after an asynchronous operation has finished. The result of a promise can either be a success or a failure.</p><p>The Promise has 3 states.</p><ul><li>Pending — The Promise has no result yet.</li><li>Fulfilled — The Promise has resolved.</li><li>Rejected — The Promise has rejected.</li></ul><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    const number = Math.round(Math.random() * 10);<br>    if(number &lt;= 5) {<br>        resolve(&#39;Success&#39;);<br>    } else {<br>        reject(new Error(&#39;Failed&#39;));<br>    }<br>});</pre><p>To create a Promise we use the Promise() constructor with the new keyword. The Promise() the constructor accepts a callback function called “executer” which accepts two arguments i.e resolve and reject.</p><p>We need to call the resolve() function when the executer function obtains the result and call the reject() function when there is an error.</p><p>Now to consume the Promise we use the Promise methods like then(), catch() and finally().</p><h3>Promise.then()</h3><p>The then() method can accept two callback functions, first one executes when the Promise is resolved and the second one when Promise is rejected.</p><pre>function getPromise(isTrue) {<br>    return new Promise((resolve, reject) =&gt; {<br>        if(isTrue) {<br>            resolve(&#39;Success&#39;);<br>        } else {<br>            reject(new Error(&#39;Failed&#39;));<br>        }<br>    });<br>}</pre><pre>getPromise(true).then(<br>    response =&gt; console.log(&#39;Promise is resolved with result = &#39; + response),<br>    error =&gt; console.log(&#39;Promise is rejected with error = &#39; + error.message)<br>);<br>// Promise is resolved with result = Success</pre><pre>getPromise(false).then(<br>    response =&gt; console.log(&#39;Promise is resolved with result = &#39; + response),<br>    error =&gt; console.log(&#39;Promise is rejected with error = &#39; + error.message)<br>);<br>// Promise is rejected with error = Failed</pre><p>If we want to handle success and failure cases separately then we can use then() only for success and catch() for failure.</p><h3>Promise.catch()</h3><p>The catch() method takes a callback function which executes when the Promise is rejected.</p><pre>function getPromise(isTrue) {<br>    return new Promise((resolve, reject) =&gt; {<br>        if(isTrue) {<br>            resolve(&#39;Success&#39;);<br>        } else {<br>            reject(new Error(&#39;Failed&#39;));<br>        }<br>    });<br>}</pre><pre>getPromise(false)<br>.then(response =&gt; console.log(&#39;Promise is resolved with result = &#39; + response))<br>.catch(error =&gt; console.log(&#39;Promise is rejected with error = &#39; + error.message))<br>// Promise is rejected with error = Failed</pre><p>If we are handling errors both in then() and catch(), then only the error handler inside then() executes in case of any error and not the handler inside catch().</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    reject(new Error(&#39;An error occurred&#39;));<br>});</pre><pre>promise.then(null, () =&gt; console.log(&#39;Error caught inside then&#39;))<br>.catch(() =&gt; console.log(&#39;Error caught inside catch&#39;))<br>// Error caught inside then</pre><p>If further, any error occurred in the error handler of then(), then it will get caught in catch().</p><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    reject(new Error(&#39;Error occurred in Promise&#39;));<br>});</pre><pre>promise.then(null, <br>    err =&gt; {<br>        console.log(&#39;Error caught inside then, message: &#39; + err.message);<br>        throw new Error(&#39;Error occured in then&#39;);<br>    })<br>.catch(err =&gt; {<br>    console.log(&#39;Error caught inside catch, message: &#39; + err.message);<br>});</pre><pre>// Error caught inside then, message: Error occurred in Promise<br>// Error caught inside catch, message: Error occured in then</pre><h3>Promise.finally()</h3><p>The finally() method takes a callback function which executes after the Promise is either resolved or rejected.</p><h3>On Success</h3><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    resolve(&#39;Success&#39;);<br>});</pre><pre>promise.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.log(err.message))<br>.finally(() =&gt; console.log(&#39;Executing Finally&#39;));<br>// Success<br>// Executing Finally</pre><h3>On failure</h3><pre>let promise = new Promise((resolve, reject) =&gt; {<br>    reject(new Error(&#39;Failed&#39;));<br>});</pre><pre>promise.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.log(err.message))<br>.finally(() =&gt; console.log(&#39;Executing Finally&#39;));<br>// Failed<br>// Executing Finally</pre><h3>Promises Chaining</h3><p>We can execute a sequence of asynchronous operations one after the other by chaining methods then(), catch() and finally().</p><pre>takeOrder()<br>.then(order =&gt; makeOrder(order))<br>.then(order =&gt; serveOrder(order))<br>.then(status =&gt; console.log(status))<br>.catch(err =&gt; console.log(err));</pre><p>Here takeOrder() will return a Promise that will be consumed in first then() method. The makeOrder() will return a Promise which will be consumed in the second then() method and serveOrder() will again return a Promise which will be consumed in third then() method. If any error occurred in any of the promises then it will get caught in catch() method.</p><h3>Promise.all()</h3><p>The Promise.all() method takes an iterable of promises as an input and returns a single Promise and it gets resolved when all the promises get resolved or any one of them gets rejected.</p><pre>function getPromise(delay) {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(delay + 100);<br>        }, delay);<br>    })<br>}</pre><pre>Promise.all([getPromise(1000), getPromise(3000), getPromise(2000)])<br>.then(responses =&gt; console.log(responses))<br>.catch(error =&gt; console.log(error));</pre><h3>Promise.race()</h3><p>The Promise.race() method takes an iterable of promises and returns a single Promise which gets resolved/rejected as soon as any of the Promises are resolved or rejected.</p><pre>let promise1 = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        resolve(&#39;Promise 1&#39;);<br>    }, 1000);<br>});</pre><pre>let promise2 = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        resolve(&#39;Promise 2&#39;);<br>    }, 500);<br>});</pre><pre>Promise.race([promise1, promise2])<br>.then(res =&gt; console.log(res)) // Promise 2<br>.catch(err =&gt; console.log(err));</pre><h4>You may also like</h4><ul><li><a href="https://jscurious.com/understanding-async-and-await-in-javascript/">Understanding async and await in JavaScript</a></li><li><a href="https://jscurious.com/callback-functions-in-javascript/">Callback functions in JavaScript</a></li><li><a href="https://jscurious.com/html-datalist-tag-for-filter-search/">HTML datalist tag for filter search</a></li><li><a href="https://jscurious.com/javascript-fetch-api-to-make-http-requests/">JavaScript Fetch API to make HTTP requests</a></li><li><a href="https://jscurious.com/20-javascript-shorthand-techniques-that-will-save-your-time/">20 JavaScript Shorthand Coding Techniques that will save your time</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=226f33f5230e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/a-brief-guide-to-promises-in-javascript-226f33f5230e">A Brief Guide to Promises in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>