<?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"><channel><title><![CDATA[Learn about HTML, CSS, JavaScript, React, Vue, Angular, Jest, and more!]]></title><description><![CDATA[Discover the latest trends and best practices in frontend web technologies. Master your skills in testing, development, and Node.js with our comprehensive guide.]]></description><link>https://frontendgenius.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 21 May 2026 14:34:18 GMT</lastBuildDate><atom:link href="https://frontendgenius.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Best UX Practices for Data Table Design]]></title><description><![CDATA[Data Table Design UX Patterns
Overview
A well-designed data table enhances usability, efficiency, and accessibility. This guide outlines key best practices and interaction patterns to ensure an optimal enterprise table experience.

1️⃣ Full-Screen Mo...]]></description><link>https://frontendgenius.com/best-ux-practices-for-data-table-design</link><guid isPermaLink="true">https://frontendgenius.com/best-ux-practices-for-data-table-design</guid><category><![CDATA[datatable]]></category><category><![CDATA[UX]]></category><category><![CDATA[UXdesign ]]></category><category><![CDATA[table]]></category><category><![CDATA[#Ux research]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sat, 29 Mar 2025 08:30:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743150068220/fce8ca9f-e993-4e0f-b10a-95e672fd2737.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-data-table-design-ux-patterns"><strong>Data Table Design UX Patterns</strong></h1>
<h2 id="heading-overview">Overview</h2>
<p>A well-designed data table enhances usability, efficiency, and accessibility. This guide outlines key best practices and interaction patterns to ensure an optimal enterprise table experience.</p>
<hr />
<h2 id="heading-1-full-screen-mode">1️⃣ Full-Screen Mode</h2>
<p><strong>Purpose:</strong> Improve information immersion by maximizing screen space.</p>
<ul>
<li><p>Enable full-screen mode to remove unnecessary UI elements.</p>
</li>
<li><p>Allow users to toggle full-screen mode easily.</p>
</li>
<li><p>Maintain state persistence when switching views.</p>
</li>
</ul>
<hr />
<h2 id="heading-2-navigation-amp-scrolling">2️⃣ Navigation &amp; Scrolling</h2>
<p><strong>Purpose:</strong> Ensure smooth navigation for large datasets.</p>
<ul>
<li><p>Implement smooth scrolling (horizontal &amp; vertical).</p>
</li>
<li><p>Use sticky headers, footers, and action controls.</p>
</li>
<li><p>Ensure seamless keyboard and mouse interactions.</p>
</li>
</ul>
<hr />
<h2 id="heading-3-pagination-sorting-amp-searching">3️⃣ Pagination, Sorting &amp; Searching</h2>
<p><strong>Purpose:</strong> Help users find and organize data efficiently.</p>
<ul>
<li><p>Provide clear pagination controls with page size options.</p>
</li>
<li><p>Implement sortable columns with intuitive indicators.</p>
</li>
<li><p>Highlight search matches within table rows.</p>
</li>
</ul>
<hr />
<h2 id="heading-4-multi-select-amp-bulk-actions">4️⃣ Multi-Select &amp; Bulk Actions</h2>
<p><strong>Purpose:</strong> Allow users to manage multiple rows efficiently.</p>
<ul>
<li><p>Display checkboxes on hover to indicate selection capability.</p>
</li>
<li><p>Show bulk actions (Delete, Export, Duplicate) only when rows are selected.</p>
</li>
<li><p>Ensure quick selection/deselection options.</p>
</li>
</ul>
<hr />
<h2 id="heading-5-row-actions-amp-discoverability">5️⃣ Row Actions &amp; Discoverability</h2>
<p><strong>Purpose:</strong> Make row interactions intuitive and efficient.</p>
<ul>
<li><p>Use hover states to reveal row actions.</p>
</li>
<li><p>Support expandable rows for additional details.</p>
</li>
<li><p>Provide tooltips for quick insights on actions.</p>
</li>
</ul>
<hr />
<h2 id="heading-6-cell-editing-amp-data-entry">6️⃣ Cell Editing &amp; Data Entry</h2>
<p><strong>Purpose:</strong> Allow for seamless in-table data modifications.</p>
<ul>
<li><p>Indicate editable cells with a text cursor on hover.</p>
</li>
<li><p>Support inline editing for minimal friction.</p>
</li>
<li><p>Require row expansion for editing high-risk data.</p>
</li>
<li><p>Offer alternative edit modes (modal-based, sidebar editing).</p>
</li>
</ul>
<hr />
<h2 id="heading-7-feedback-amp-confirmation">7️⃣ Feedback &amp; Confirmation</h2>
<p><strong>Purpose:</strong> Provide clear confirmation of data changes.</p>
<ul>
<li><p>Confirm edits via auto-save, Enter key, or Save button.</p>
</li>
<li><p>Display success feedback (checkmark, confirmation message).</p>
</li>
<li><p>Ensure clear undo functionality if needed.</p>
</li>
</ul>
<hr />
<h2 id="heading-8-ui-optimization-amp-clutter-reduction">8️⃣ UI Optimization &amp; Clutter Reduction</h2>
<p><strong>Purpose:</strong> Ensure a clean and distraction-free user experience.</p>
<ul>
<li><p>Display actions only when relevant to reduce clutter.</p>
</li>
<li><p>Prioritize essential controls for clarity.</p>
</li>
<li><p>Maintain consistent interaction patterns across tables.</p>
</li>
</ul>
<hr />
<h2 id="heading-9-row-density-amp-state-persistence">9️⃣ Row Density &amp; State Persistence</h2>
<p><strong>Purpose:</strong> Offer customization while preserving user preferences.</p>
<ul>
<li><p>Provide row density controls (compact, default, expanded) as an icon switcher.</p>
</li>
<li><p>Ensure state preservation so user settings persist across sessions.</p>
</li>
<li><p>Include a reset to default option to restore the table to its original state.</p>
</li>
</ul>
<hr />
<h2 id="heading-ux-checklist">✅ UX Checklist</h2>
<p>Use this checklist to ensure the best data table experience:</p>
<p><strong>Implementation Tips:</strong></p>
<ul>
<li><p>Align with design &amp; development teams.</p>
</li>
<li><p>Conduct usability testing to validate improvements.</p>
</li>
<li><p>Monitor user feedback for future enhancements.</p>
</li>
</ul>
<hr />
<h2 id="heading-numbers-formatting-amp-alignment">Numbers: Formatting &amp; Alignment</h2>
<h3 id="heading-right-align-numeric-columns"><strong>Right-Align Numeric Columns</strong></h3>
<p>Unlike text, numerical values are easier to compare when right-aligned. Align numbers according to the decimal position to ensure consistency.</p>
<h3 id="heading-use-tabular-typography"><strong>Use Tabular Typography</strong></h3>
<p>Monospace fonts improve readability and comparison of numerical data. They ensure uniform character spacing for better visual alignment.</p>
<h3 id="heading-exceptions"><strong>Exceptions</strong></h3>
<p><strong>Left-align qualitative numbers</strong> (e.g., dates, zip codes, phone numbers). These are not pure numerical values and are more readable when left-aligned.</p>
<h3 id="heading-examples"><strong>Examples:</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Data Type</td><td>Alignment</td></tr>
</thead>
<tbody>
<tr>
<td>Amounts (Money, Quantities)</td><td>Right-Aligned</td></tr>
<tr>
<td>Measures (Weight, Distance)</td><td>Right-Aligned</td></tr>
<tr>
<td>Percentages</td><td>Right-Aligned</td></tr>
<tr>
<td>Dates</td><td>Left-Aligned</td></tr>
<tr>
<td>Zip/Postal Codes</td><td>Left-Aligned</td></tr>
<tr>
<td>Phone Numbers</td><td>Left-Aligned</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>A well-designed data table provides a seamless and efficient user experience. By implementing these UX patterns, designers and developers can create data tables that enhance usability, improve workflow efficiency, and ensure data accessibility.</p>
]]></content:encoded></item><item><title><![CDATA[Branch and Commit Naming Convention Strategy]]></title><description><![CDATA[Branch Naming Conventions
A well-defined branch naming strategy ensures clarity, collaboration, and ease of tracking development work. Below are the standardized branch prefixes to be followed:
Branch Prefixes:

base-: Base branch for a specific modu...]]></description><link>https://frontendgenius.com/branch-and-commit-naming-convention-strategy</link><guid isPermaLink="true">https://frontendgenius.com/branch-and-commit-naming-convention-strategy</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Branching Strategies]]></category><category><![CDATA[commit messages]]></category><category><![CDATA[GitHub Actions]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Fri, 28 Mar 2025 08:06:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743148998849/e128d3a1-8777-4c12-b94c-30ea671230d2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-branch-naming-conventions">Branch Naming Conventions</h2>
<p>A well-defined branch naming strategy ensures clarity, collaboration, and ease of tracking development work. Below are the standardized branch prefixes to be followed:</p>
<h3 id="heading-branch-prefixes"><strong>Branch Prefixes:</strong></h3>
<ul>
<li><p><strong>base-</strong>: Base branch for a specific module or project.</p>
</li>
<li><p><strong>stage-</strong>: Staging environment branch for pre-production testing.</p>
</li>
<li><p><strong>feature-</strong>: New feature development.</p>
</li>
<li><p><strong>fix-</strong>: Bug fixes.</p>
</li>
<li><p><strong>test-</strong>: Testing-related changes.</p>
</li>
</ul>
<h3 id="heading-branch-naming-format"><strong>Branch Naming Format:</strong></h3>
<p>Use the Jira issue key in branch names to maintain traceability between Jira work items and development.</p>
<pre><code class="lang-javascript">git checkout -b JRA<span class="hljs-number">-123</span>-feature-login-improvement
</code></pre>
<p>Here, <code>JRA-123</code> represents the Jira work item, followed by the branch type and description.</p>
<h2 id="heading-commit-message-conventions">Commit Message Conventions</h2>
<p>Adopting a structured commit message format enhances readability and helps in effective version control management. Below are the standard commit prefixes:</p>
<h3 id="heading-commit-prefixes"><strong>Commit Prefixes:</strong></h3>
<ul>
<li><p><strong>feat</strong>: Adds or removes a new feature to the API or UI.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 feat: Implement user login API"</code></li>
</ul>
</li>
<li><p><strong>fix</strong>: Fixes a bug introduced in a previous feature commit.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 fix: Correct login validation error"</code></li>
</ul>
</li>
<li><p><strong>refactor</strong>: Improves code structure without changing behavior.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 refactor: Simplify authentication logic"</code></li>
</ul>
</li>
<li><p><strong>perf</strong>: Performance improvements without altering behavior.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 perf: Optimize database queries"</code></li>
</ul>
</li>
<li><p><strong>style</strong>: Code formatting changes (e.g., indentation, white spaces, missing semicolons).</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 style: Fix indentation in user service"</code></li>
</ul>
</li>
<li><p><strong>test</strong>: Adding or modifying tests.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 test: Add unit tests for login endpoint"</code></li>
</ul>
</li>
<li><p><strong>docs</strong>: Documentation updates.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 docs: Update README with API usage"</code></li>
</ul>
</li>
<li><p><strong>build</strong>: Changes affecting build scripts, dependencies, or CI/CD pipelines.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 build: Upgrade dependencies to latest version"</code></li>
</ul>
</li>
<li><p><strong>ops</strong>: Changes related to infrastructure or deployment.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 ops: Update Kubernetes deployment configs"</code></li>
</ul>
</li>
<li><p><strong>chore</strong>: Miscellaneous changes like modifying .gitignore.</p>
<ul>
<li>Example: <code>git commit -m "JRA-123 chore: Update .gitignore to exclude logs"</code></li>
</ul>
</li>
</ul>
<h2 id="heading-linking-jira-work-items-to-commits-and-pull-requests">Linking Jira Work Items to Commits and Pull Requests</h2>
<p>To integrate Jira with development tools like Bitbucket, GitHub, or GitLab, follow these best practices:</p>
<h3 id="heading-branch-creation"><strong>Branch Creation</strong></h3>
<p>Include the Jira work item key in the branch name.</p>
<pre><code class="lang-javascript">git checkout -b JRA<span class="hljs-number">-123</span>-feature-payment-integration
</code></pre>
<h3 id="heading-commit-messages"><strong>Commit Messages</strong></h3>
<p>Reference the Jira work item key at the start of commit messages.</p>
<pre><code class="lang-javascript">git commit -m <span class="hljs-string">"JRA-123 feat: Implement payment gateway API"</span>
</code></pre>
<h3 id="heading-pull-requests"><strong>Pull Requests</strong></h3>
<p>Include the Jira work item key in the pull request title.</p>
<pre><code class="lang-javascript">JRA<span class="hljs-number">-123</span>: Implement <span class="hljs-keyword">new</span> authentication flow
</code></pre>
<h3 id="heading-push-changes"><strong>Push Changes</strong></h3>
<p>Ensure the branch is pushed to the repository.</p>
<pre><code class="lang-javascript">git push origin JRA<span class="hljs-number">-123</span>-feature-login-improvement
</code></pre>
<h2 id="heading-viewing-linked-development-information-in-jira">Viewing Linked Development Information in Jira</h2>
<p>Once changes are pushed, Jira will display development data linked to the work item.</p>
<h3 id="heading-to-view-linked-commits-branches-or-pull-requests-in-jira"><strong>To view linked commits, branches, or pull requests in Jira:</strong></h3>
<ol>
<li><p>Navigate to the Jira work item.</p>
</li>
<li><p>Under the <strong>Development</strong> section, click the number of pull requests, branches, or commits.</p>
</li>
<li><p>On the Jira board, hover over development icons to see linked activities.</p>
</li>
</ol>
<h3 id="heading-automated-jira-integration-benefits"><strong>Automated Jira Integration Benefits:</strong></h3>
<ul>
<li><p>Ensures every commit, branch, and pull request is traceable.</p>
</li>
<li><p>Enables seamless linking of development activities with Jira tickets.</p>
</li>
<li><p>Provides a clear history of changes and their purpose.</p>
</li>
</ul>
<h2 id="heading-git-best-practices">Git Best Practices</h2>
<h3 id="heading-keeping-a-linear-commit-history">Keeping a Linear Commit History</h3>
<ul>
<li><p>Always ensure a linear commit history for easy debugging and review.</p>
</li>
<li><p>Use <code>git merge --ff-only</code> when merging branches:</p>
</li>
</ul>
<pre><code class="lang-javascript">git checkout develop
git pull
git checkout some-branch-name
git pull
git merge some-branch-name --ff-only
</code></pre>
<h3 id="heading-handling-fast-forward-merge-conflicts">Handling Fast-Forward Merge Conflicts</h3>
<p>If you encounter an error like:</p>
<pre><code class="lang-javascript">fatal: Not possible to fast-forward, aborting.
</code></pre>
<p>Follow these steps:</p>
<ol>
<li><p>Reset to the last known good commit:</p>
<pre><code class="lang-javascript"> git reset --hard <span class="hljs-number">123445</span> <span class="hljs-comment">// commit hash</span>
</code></pre>
</li>
<li><p>Force push the corrected branch:</p>
<pre><code class="lang-javascript"> git push origin some-branch-name --force
</code></pre>
</li>
<li><p>Cherry-pick specific commits if needed:</p>
<pre><code class="lang-javascript"> git cherry-pick <span class="hljs-number">123445</span> <span class="hljs-comment">// commit hash</span>
 git push origin some-branch-name
</code></pre>
</li>
</ol>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>A consistent branch and commit naming convention simplifies code tracking, enhances collaboration, and improves CI/CD efficiency. By integrating Jira work items, developers can streamline workflows, maintain project transparency, and optimize version control management.</p>
]]></content:encoded></item><item><title><![CDATA[100+ JavaScript Snippets for Beginners: Simplify Your Coding Journey]]></title><description><![CDATA[As a beginner in coding, it can be challenging to find the right code snippets to help you simplify your coding journey. With JavaScript being one of the most popular programming languages, it is crucial to have a vast selection of code snippets that...]]></description><link>https://frontendgenius.com/100-javascript-snippets-for-beginners-simplify-your-coding-journey</link><guid isPermaLink="true">https://frontendgenius.com/100-javascript-snippets-for-beginners-simplify-your-coding-journey</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[coding]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[#codenewbies]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Wed, 19 Apr 2023 09:34:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681910512178/032fdd91-20a2-499f-89b0-ccb0aaa4f0bd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a beginner in coding, it can be challenging to find the right code snippets to help you simplify your coding journey. With JavaScript being one of the most popular programming languages, it is crucial to have a vast selection of code snippets that you can easily refer to when working on your projects. In this article, we will explore 100+ JavaScript snippets that will help you simplify your coding journey.</p>
<p><em>Before I go on, let me recommend something to you.</em></p>
<p><em>If you want to significantly improve your JavaScript knowledge or frontend knowledge and want to land your first job or if you are working want to grow as a developer like a pro take the wonderful Ebook "</em><a target="_blank" href="https://frontendgenius.gumroad.com/l/becomefrontenddeveloper"><strong>Get Hired: The Ultimate Guide to Becoming a Frontend Developer and Landing Your First Job</strong></a>", This ebook is an excellent resource for anyone interested in pursuing a career in frontend development or looking to advance their existing career.</p>
<p><strong>1. all</strong></p>
<p>This snippet returns <code>true</code> if the predicate function returns <code>true</code> for all elements in a collection and <code>false</code> otherwise. You can omit the second argument <code>fn</code>if you want to use <code>Boolean</code>as a default value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> all = <span class="hljs-function">(<span class="hljs-params">arr, fn = <span class="hljs-built_in">Boolean</span></span>) =&gt;</span> arr.every(fn);

all([<span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x &gt; <span class="hljs-number">1</span>); <span class="hljs-comment">// true</span>
all([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>2. allEqual</strong></p>
<p>This snippet checks whether all elements of the array are equal.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> allEqual = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.every(<span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> val === arr[<span class="hljs-number">0</span>]);

allEqual([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]); <span class="hljs-comment">// false</span>
allEqual([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>]); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>3. approximatelyEqual</strong></p>
<p>This snippet checks whether two numbers are approximately equal to each other, with a small difference.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> approximatelyEqual = <span class="hljs-function">(<span class="hljs-params">v1, v2, epsilon = <span class="hljs-number">0.001</span></span>) =&gt;</span> <span class="hljs-built_in">Math</span>.abs(v1 - v2) &lt; epsilon;

approximatelyEqual(<span class="hljs-built_in">Math</span>.PI / <span class="hljs-number">2.0</span>, <span class="hljs-number">1.5708</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>4. arrayToCSV</strong></p>
<p>This snippet converts the elements that don’t have commas or double quotes to strings with comma-separated values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arrayToCSV = <span class="hljs-function">(<span class="hljs-params">arr, delimiter = <span class="hljs-string">','</span></span>) =&gt;</span>
  arr.map(<span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span> v.map(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> <span class="hljs-string">`"<span class="hljs-subst">${x}</span>"`</span>).join(delimiter)).join(<span class="hljs-string">'\n'</span>);

arrayToCSV([[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], [<span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>]]); <span class="hljs-comment">// '"a","b"\n"c","d"'</span>
arrayToCSV([[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], [<span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>]], <span class="hljs-string">';'</span>); <span class="hljs-comment">// '"a";"b"\n"c";"d"'</span>
</code></pre>
<p><strong>5. arrayToHtmlList</strong></p>
<p>This snippet converts the elements of an array into `` tags and appends them to the list of the given ID.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arrayToHtmlList = <span class="hljs-function">(<span class="hljs-params">arr, listID</span>) =&gt;</span>
  (<span class="hljs-function"><span class="hljs-params">el</span> =&gt;</span> (
    (el = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#'</span> + listID)),
    (el.innerHTML += arr.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-string">`&lt;li&gt;<span class="hljs-subst">${item}</span>&lt;/li&gt;`</span>).join(<span class="hljs-string">''</span>))
  ))();

arrayToHtmlList([<span class="hljs-string">'item 1'</span>, <span class="hljs-string">'item 2'</span>], <span class="hljs-string">'by);</span>
</code></pre>
<p><strong>6. attempt</strong></p>
<p>This snippet executes a function, returning either the result or the caught error object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> attempt = <span class="hljs-function">(<span class="hljs-params">fn, ...args</span>) =&gt;</span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> fn(...args);
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-keyword">return</span> e <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Error</span> ? e : <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(e);
  }
};
<span class="hljs-keyword">var</span> elements = attempt(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">selector</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">document</span>.querySelectorAll(selector);
}, <span class="hljs-string">'&gt;_&gt;'</span>);
<span class="hljs-keyword">if</span> (elements <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Error</span>) elements = []; <span class="hljs-comment">// elements = []</span>
</code></pre>
<p><strong>7. average</strong></p>
<p>This snippet returns the average of two or more numerical values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> average = <span class="hljs-function">(<span class="hljs-params">...nums</span>) =&gt;</span> nums.reduce(<span class="hljs-function">(<span class="hljs-params">acc, val</span>) =&gt;</span> acc + val, <span class="hljs-number">0</span>) / nums.length;
average(...[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// 2</span>
average(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// 2</span>
</code></pre>
<p><strong>8. averageBy</strong></p>
<p>This snippet returns the average of an array after initially doing the mapping of each element to a value using a given function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> averageBy = <span class="hljs-function">(<span class="hljs-params">arr, fn</span>) =&gt;</span>
  arr.map(<span class="hljs-keyword">typeof</span> fn === <span class="hljs-string">'function'</span> ? fn : <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> val[fn]).reduce(<span class="hljs-function">(<span class="hljs-params">acc, val</span>) =&gt;</span> acc + val, <span class="hljs-number">0</span>) /
  arr.length;

averageBy([{ <span class="hljs-attr">n</span>: <span class="hljs-number">4</span> }, { <span class="hljs-attr">n</span>: <span class="hljs-number">2</span> }, { <span class="hljs-attr">n</span>: <span class="hljs-number">8</span> }, { <span class="hljs-attr">n</span>: <span class="hljs-number">6</span> }], <span class="hljs-function"><span class="hljs-params">o</span> =&gt;</span> o.n); <span class="hljs-comment">// 5</span>
averageBy([{ <span class="hljs-attr">n</span>: <span class="hljs-number">4</span> }, { <span class="hljs-attr">n</span>: <span class="hljs-number">2</span> }, { <span class="hljs-attr">n</span>: <span class="hljs-number">8</span> }, { <span class="hljs-attr">n</span>: <span class="hljs-number">6</span> }], <span class="hljs-string">'n'</span>); <span class="hljs-comment">// 5</span>
</code></pre>
<p><strong>9. bifurcate</strong></p>
<p>This snippet splits values into two groups and then puts a truthy element of <code>filter</code>in the first group, and in the second group otherwise.</p>
<p>You can use <code>Array.prototype.reduce()</code>and <code>Array.prototype.push()</code>to add elements to groups based on <code>filter</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> bifurcate = <span class="hljs-function">(<span class="hljs-params">arr, filter</span>) =&gt;</span>
  arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, val, i</span>) =&gt;</span> (acc[filter[i] ? <span class="hljs-number">0</span> : <span class="hljs-number">1</span>].push(val), acc), [[], []]);
bifurcate([<span class="hljs-string">'beep'</span>, <span class="hljs-string">'boop'</span>, <span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>], [<span class="hljs-literal">true</span>, <span class="hljs-literal">true</span>, <span class="hljs-literal">false</span>, <span class="hljs-literal">true</span>]); 
<span class="hljs-comment">// [ ['beep', 'boop', 'bar'], ['foo'] ]</span>
</code></pre>
<p><strong>10. bifurcateBy</strong></p>
<p>This snippet splits values into two groups, based on a predicate function. If the predicate function returns a truthy value, the element will be placed in the first group. Otherwise, it will be placed in the second group.</p>
<p>You can use <code>Array.prototype.reduce()</code>and <code>Array.prototype.push()</code>to add elements to groups, based on the value returned by <code>fn</code>for each element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> bifurcateBy = <span class="hljs-function">(<span class="hljs-params">arr, fn</span>) =&gt;</span>
  arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, val, i</span>) =&gt;</span> (acc[fn(val, i) ? <span class="hljs-number">0</span> : <span class="hljs-number">1</span>].push(val), acc), [[], []]);

bifurcateBy([<span class="hljs-string">'beep'</span>, <span class="hljs-string">'boop'</span>, <span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>], <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x[<span class="hljs-number">0</span>] === <span class="hljs-string">'b'</span>); 
<span class="hljs-comment">// [ ['beep', 'boop', 'bar'], ['foo'] ]</span>
</code></pre>
<p><strong>11. bottomVisible</strong></p>
<p>This snippet checks whether the bottom of a page is visible.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> bottomVisible = <span class="hljs-function">() =&gt;</span>
  <span class="hljs-built_in">document</span>.documentElement.clientHeight + <span class="hljs-built_in">window</span>.scrollY &gt;=
  (<span class="hljs-built_in">document</span>.documentElement.scrollHeight || <span class="hljs-built_in">document</span>.documentElement.clientHeight);

bottomVisible(); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>12. byteSize</strong></p>
<p>This snippet returns the length of a string in bytes.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> byteSize = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span> <span class="hljs-keyword">new</span> Blob([str]).size;

byteSize(<span class="hljs-string">'😀'</span>); <span class="hljs-comment">// 4</span>
byteSize(<span class="hljs-string">'Hello World'</span>); <span class="hljs-comment">// 11</span>
</code></pre>
<p><strong>13. capitalize</strong></p>
<p>This snippet capitalizes the first letter of a string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> capitalize = <span class="hljs-function">(<span class="hljs-params">[first, ...rest]</span>) =&gt;</span>
  first.toUpperCase() + rest.join(<span class="hljs-string">''</span>);

capitalize(<span class="hljs-string">'fooBar'</span>); <span class="hljs-comment">// 'FooBar'</span>
capitalize(<span class="hljs-string">'fooBar'</span>, <span class="hljs-literal">true</span>); <span class="hljs-comment">// 'FooBar'</span>
</code></pre>
<p><strong>14. capitalizeEveryWord</strong></p>
<p>This snippet capitalizes the first letter of every word in a given string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> capitalizeEveryWord = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span> str.replace(<span class="hljs-regexp">/\b[a-z]/g</span>, <span class="hljs-function"><span class="hljs-params">char</span> =&gt;</span> char.toUpperCase());

capitalizeEveryWord(<span class="hljs-string">'hello world!'</span>); <span class="hljs-comment">// 'Hello World!'</span>
</code></pre>
<p><strong>15. castArray</strong></p>
<p>This snippet converts a non-array value into array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> castArray = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> (<span class="hljs-built_in">Array</span>.isArray(val) ? val : [val]);

castArray(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// ['foo']</span>
castArray([<span class="hljs-number">1</span>]); <span class="hljs-comment">// [1]</span>
</code></pre>
<p><strong>16. compact</strong></p>
<p>This snippet removes false values from an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> compact = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.filter(<span class="hljs-built_in">Boolean</span>);

compact([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-literal">false</span>, <span class="hljs-number">2</span>, <span class="hljs-string">''</span>, <span class="hljs-number">3</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span> * <span class="hljs-number">23</span>, <span class="hljs-literal">NaN</span>, <span class="hljs-string">'s'</span>, <span class="hljs-number">34</span>]); 
<span class="hljs-comment">// [ 1, 2, 3, 'a', 's', 34 ]</span>
</code></pre>
<p><strong>17. countOccurrences</strong></p>
<p>This snippet counts the occurrences of a value in an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> countOccurrences = <span class="hljs-function">(<span class="hljs-params">arr, val</span>) =&gt;</span> arr.reduce(<span class="hljs-function">(<span class="hljs-params">a, v</span>) =&gt;</span> (v === val ? a + <span class="hljs-number">1</span> : a), <span class="hljs-number">0</span>);
countOccurrences([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">1</span>); <span class="hljs-comment">// 3</span>
</code></pre>
<p><strong>18. Create Directory</strong></p>
<p>This snippet uses <code>existsSync()</code> to check whether a directory exists and then <code>mkdirSync()</code> to create it if it doesn’t.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> createDirIfNotExists = <span class="hljs-function"><span class="hljs-params">dir</span> =&gt;</span> (!fs.existsSync(dir) ? fs.mkdirSync(dir) : <span class="hljs-literal">undefined</span>);
createDirIfNotExists(<span class="hljs-string">'test'</span>); 
<span class="hljs-comment">// creates the directory 'test', if it doesn't exist</span>
</code></pre>
<p><strong>19. currentURL</strong></p>
<p>This snippet returns the current URL.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentURL = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">window</span>.location.href;

currentURL(); <span class="hljs-comment">// 'https://medium.com/@fatosmorina'</span>
</code></pre>
<p><strong>20. dayOfYear</strong></p>
<p>This snippet gets the day of the year from a <code>Date</code>object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dayOfYear = <span class="hljs-function"><span class="hljs-params">date</span> =&gt;</span>
  <span class="hljs-built_in">Math</span>.floor((date - <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(date.getFullYear(), <span class="hljs-number">0</span>, <span class="hljs-number">0</span>)) / <span class="hljs-number">1000</span> / <span class="hljs-number">60</span> / <span class="hljs-number">60</span> / <span class="hljs-number">24</span>);

dayOfYear(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()); <span class="hljs-comment">// 272</span>
</code></pre>
<p><strong>21. decapitalize</strong></p>
<p>This snippet turns the first letter of a string into lowercase.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> decapitalize = <span class="hljs-function">(<span class="hljs-params">[first, ...rest]</span>) =&gt;</span>
  first.toLowerCase() + rest.join(<span class="hljs-string">''</span>)

decapitalize(<span class="hljs-string">'FooBar'</span>); <span class="hljs-comment">// 'fooBar'</span>
decapitalize(<span class="hljs-string">'FooBar'</span>); <span class="hljs-comment">// 'fooBar</span>
</code></pre>
<p><strong>22. deepFlatten</strong></p>
<p>This snippet flattens an array recursively.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> deepFlatten = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> [].concat(...arr.map(<span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span> (<span class="hljs-built_in">Array</span>.isArray(v) ? deepFlatten(v) : v)));

deepFlatten([<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>], [[<span class="hljs-number">3</span>], <span class="hljs-number">4</span>], <span class="hljs-number">5</span>]); <span class="hljs-comment">// [1,2,3,4,5]</span>
</code></pre>
<p><strong>23. default</strong></p>
<p>This snippet assigns default values for all properties in an object that are <em>undefined</em>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> defaults = <span class="hljs-function">(<span class="hljs-params">obj, ...defs</span>) =&gt;</span> <span class="hljs-built_in">Object</span>.assign({}, obj, ...defs.reverse(), obj);

defaults({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> }, { <span class="hljs-attr">b</span>: <span class="hljs-number">6</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-number">3</span> }); <span class="hljs-comment">// { a: 1, b: 2 }</span>
</code></pre>
<p><strong>24. defer</strong></p>
<p>This snippet delays the execution of a function until the current call stack is cleared.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> defer = <span class="hljs-function">(<span class="hljs-params">fn, ...args</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1</span>, ...args);

defer(<span class="hljs-built_in">console</span>.log, <span class="hljs-string">'a'</span>), <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'b'</span>); <span class="hljs-comment">// logs 'b' then 'a'</span>
</code></pre>
<p><strong>25. degreesToRads</strong></p>
<p>This code snippet can be used to convert a value from degrees to radians.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> degreesToRads = <span class="hljs-function"><span class="hljs-params">deg</span> =&gt;</span> (deg * <span class="hljs-built_in">Math</span>.PI) / <span class="hljs-number">180.0</span>;

degreesToRads(<span class="hljs-number">90.0</span>); <span class="hljs-comment">// ~1.5708</span>
</code></pre>
<p><strong>26. difference</strong></p>
<p>This snippet finds the difference between two arrays.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> difference = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> s = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(b);
  <span class="hljs-keyword">return</span> a.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> !s.has(x));
};

difference([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]); <span class="hljs-comment">// [3]</span>
</code></pre>
<p><strong>27. differenceBy</strong></p>
<p>This method returns the difference between two arrays, after applying a given function to each element of both lists.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> differenceBy = <span class="hljs-function">(<span class="hljs-params">a, b, fn</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> s = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(b.map(fn));
  <span class="hljs-keyword">return</span> a.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> !s.has(fn(x)));
};

differenceBy([<span class="hljs-number">2.1</span>, <span class="hljs-number">1.2</span>], [<span class="hljs-number">2.3</span>, <span class="hljs-number">3.4</span>], <span class="hljs-built_in">Math</span>.floor); <span class="hljs-comment">// [1.2]</span>
differenceBy([{ <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> }, { <span class="hljs-attr">x</span>: <span class="hljs-number">1</span> }], [{ <span class="hljs-attr">x</span>: <span class="hljs-number">1</span> }], <span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span> v.x); <span class="hljs-comment">// [ { x: 2 } ]</span>
</code></pre>
<p><strong>28. differenceWith</strong></p>
<p>This snippet removes the values for which the comparator function returns <code>false</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> differenceWith = <span class="hljs-function">(<span class="hljs-params">arr, val, comp</span>) =&gt;</span> arr.filter(<span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> val.findIndex(<span class="hljs-function"><span class="hljs-params">b</span> =&gt;</span> comp(a, b)) === <span class="hljs-number">-1</span>);

differenceWith([<span class="hljs-number">1</span>, <span class="hljs-number">1.2</span>, <span class="hljs-number">1.5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">0</span>], [<span class="hljs-number">1.9</span>, <span class="hljs-number">3</span>, <span class="hljs-number">0</span>], <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.round(a) === <span class="hljs-built_in">Math</span>.round(b)); 
<span class="hljs-comment">// [1, 1.2]</span>
</code></pre>
<p><strong>29. digitize</strong></p>
<p>This snippet gets a number as input and returns an array of its digits.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> digitize = <span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> [...<span class="hljs-string">`<span class="hljs-subst">${n}</span>`</span>].map(<span class="hljs-function"><span class="hljs-params">i</span> =&gt;</span> <span class="hljs-built_in">parseInt</span>(i));

digitize(<span class="hljs-number">431</span>); <span class="hljs-comment">// [4, 3, 1]</span>
</code></pre>
<p><strong>30. distance</strong></p>
<p>This snippet returns the distance between two points by calculating the Euclidean distance.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> distance = <span class="hljs-function">(<span class="hljs-params">x0, y0, x1, y1</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.hypot(x1 - x0, y1 - y0);

distance(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// 2.23606797749979</span>
</code></pre>
<p><strong>31. Drop Elements</strong></p>
<p>This snippet returns a new array with <code>n</code> elements removed from the left.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> drop = <span class="hljs-function">(<span class="hljs-params">arr, n = <span class="hljs-number">1</span></span>) =&gt;</span> arr.slice(n);

drop([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// [2,3]</span>
drop([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">2</span>); <span class="hljs-comment">// [3]</span>
drop([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">42</span>); <span class="hljs-comment">// []</span>
</code></pre>
<p><strong>32. dropRight</strong></p>
<p>This snippet returns a new array with <code>n</code> elements removed from the right.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dropRight = <span class="hljs-function">(<span class="hljs-params">arr, n = <span class="hljs-number">1</span></span>) =&gt;</span> arr.slice(<span class="hljs-number">0</span>, -n);

dropRight([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// [1,2]</span>
dropRight([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">2</span>); <span class="hljs-comment">// [1]</span>
dropRight([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">42</span>); <span class="hljs-comment">// []</span>
</code></pre>
<p><strong>33. dropRightWhile</strong></p>
<p>This snippet removes elements from the right side of an array until the passed function returns <code>true</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dropRightWhile = <span class="hljs-function">(<span class="hljs-params">arr, func</span>) =&gt;</span> {
  <span class="hljs-keyword">while</span> (arr.length &gt; <span class="hljs-number">0</span> &amp;&amp; !func(arr[arr.length - <span class="hljs-number">1</span>])) arr = arr.slice(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>);
  <span class="hljs-keyword">return</span> arr;
};

dropRightWhile([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], <span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n &lt; <span class="hljs-number">3</span>); <span class="hljs-comment">// [1, 2]</span>
</code></pre>
<p><strong>34. dropWhile</strong></p>
<p>This snippet removes elements from an array until the passed function returns <code>true</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dropWhile = <span class="hljs-function">(<span class="hljs-params">arr, func</span>) =&gt;</span> {
  <span class="hljs-keyword">while</span> (arr.length &gt; <span class="hljs-number">0</span> &amp;&amp; !func(arr[<span class="hljs-number">0</span>])) arr = arr.slice(<span class="hljs-number">1</span>);
  <span class="hljs-keyword">return</span> arr;
};

dropWhile([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], <span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n &gt;= <span class="hljs-number">3</span>); <span class="hljs-comment">// [3,4]</span>
</code></pre>
<p><strong>35. elementContains</strong></p>
<p>This snippet checks whether the parent element contains the child.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> elementContains = <span class="hljs-function">(<span class="hljs-params">parent, child</span>) =&gt;</span> parent !== child &amp;&amp; parent.contains(child);

elementContains(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'head'</span>), <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'title'</span>)); <span class="hljs-comment">// true</span>
elementContains(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>), <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>36. Filter Duplicate Elements</strong></p>
<p>This snippet removes duplicate values in an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> filterNonUnique = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> [ …<span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(arr)];
filterNonUnique([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p><strong>37. findKey</strong></p>
<p>This snippet returns the first key that satisfies a given function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> findKey = <span class="hljs-function">(<span class="hljs-params">obj, fn</span>) =&gt;</span> <span class="hljs-built_in">Object</span>.keys(obj).find(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span> fn(obj[key], key, obj));

findKey(
  {
    <span class="hljs-attr">barney</span>: { <span class="hljs-attr">age</span>: <span class="hljs-number">36</span>, <span class="hljs-attr">active</span>: <span class="hljs-literal">true</span> },
    <span class="hljs-attr">fred</span>: { <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">active</span>: <span class="hljs-literal">false</span> },
    <span class="hljs-attr">pebbles</span>: { <span class="hljs-attr">age</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">active</span>: <span class="hljs-literal">true</span> }
  },
  <span class="hljs-function"><span class="hljs-params">o</span> =&gt;</span> o[<span class="hljs-string">'active'</span>]
); <span class="hljs-comment">// 'barney'</span>
</code></pre>
<p><strong>38. findLast</strong></p>
<p>This snippet returns the last element for which a given function returns a truthy value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> findLast = <span class="hljs-function">(<span class="hljs-params">arr, fn</span>) =&gt;</span> arr.filter(fn).pop();

findLast([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], <span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n % <span class="hljs-number">2</span> === <span class="hljs-number">1</span>); <span class="hljs-comment">// 3</span>
</code></pre>
<p><strong>39. flatten</strong></p>
<p>This snippet flattens an array up to a specified depth using recursion.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> flatten = <span class="hljs-function">(<span class="hljs-params">arr, depth = <span class="hljs-number">1</span></span>) =&gt;</span>
  arr.reduce(<span class="hljs-function">(<span class="hljs-params">a, v</span>) =&gt;</span> a.concat(depth &gt; <span class="hljs-number">1</span> &amp;&amp; <span class="hljs-built_in">Array</span>.isArray(v) ? flatten(v, depth - <span class="hljs-number">1</span>) : v), []);

flatten([<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>], <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]); <span class="hljs-comment">// [1, 2, 3, 4]</span>
flatten([<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>, [<span class="hljs-number">3</span>, [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>], <span class="hljs-number">6</span>], <span class="hljs-number">7</span>], <span class="hljs-number">8</span>], <span class="hljs-number">2</span>); <span class="hljs-comment">// [1, 2, 3, [4, 5], 6, 7, 8]</span>
</code></pre>
<p><strong>40. forEachRight</strong></p>
<p>This snippet executes a function for each element of an array starting from the array’s last element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> forEachRight = <span class="hljs-function">(<span class="hljs-params">arr, callback</span>) =&gt;</span>
  arr
    .slice(<span class="hljs-number">0</span>)
    .reverse()
    .forEach(callback);

forEachRight([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(val)); <span class="hljs-comment">// '4', '3', '2', '1'</span>
</code></pre>
<p><strong>41. forOwn</strong></p>
<p>This snippet iterates on each property of an object and iterates a callback for each one respectively.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> forOwn = <span class="hljs-function">(<span class="hljs-params">obj, fn</span>) =&gt;</span> <span class="hljs-built_in">Object</span>.keys(obj).forEach(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span> fn(obj[key], key, obj));
forOwn({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, <span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(v)); <span class="hljs-comment">// 'bar', 1</span>
</code></pre>
<p><strong>42. functionName</strong></p>
<p>This snippet prints the name of a function into the console.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> functionName = <span class="hljs-function"><span class="hljs-params">fn</span> =&gt;</span> (<span class="hljs-built_in">console</span>.debug(fn.name), fn);

functionName(<span class="hljs-built_in">Math</span>.max); <span class="hljs-comment">// max (logged in debug channel of console)</span>
</code></pre>
<p><strong>43. Get Time From Date</strong></p>
<p>This snippet can be used to get the time from a <code>Date</code>object as a string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getColonTimeFromDate = <span class="hljs-function"><span class="hljs-params">date</span> =&gt;</span> date.toTimeString().slice(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>);

getColonTimeFromDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()); <span class="hljs-comment">// "08:38:00"</span>
</code></pre>
<p><strong>44. Get Days Between Dates</strong></p>
<p>This snippet can be used to find the difference in days between two dates.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getDaysDiffBetweenDates = <span class="hljs-function">(<span class="hljs-params">dateInitial, dateFinal</span>) =&gt;</span>
  (dateFinal - dateInitial) / (<span class="hljs-number">1000</span> * <span class="hljs-number">3600</span> * <span class="hljs-number">24</span>);

getDaysDiffBetweenDates(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2019-01-13'</span>), <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2019-01-15'</span>)); <span class="hljs-comment">// 2</span>
</code></pre>
<p><strong>45. getStyle</strong></p>
<p>This snippet can be used to get the value of a CSS rule for a particular element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getStyle = <span class="hljs-function">(<span class="hljs-params">el, ruleName</span>) =&gt;</span> getComputedStyle(el)[ruleName];

getStyle(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>), <span class="hljs-string">'font-size'</span>); <span class="hljs-comment">// '16px'</span>
</code></pre>
<p><strong>46. getType</strong></p>
<p>This snippet can be used to get the type of a value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getType = <span class="hljs-function"><span class="hljs-params">v</span> =&gt;</span>
  v === <span class="hljs-literal">undefined</span> ? <span class="hljs-string">'undefined'</span> : v === <span class="hljs-literal">null</span> ? <span class="hljs-string">'null'</span> : v.constructor.name.toLowerCase();

getType(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])); <span class="hljs-comment">// 'set'</span>
</code></pre>
<p><strong>47. hasClass</strong></p>
<p>This snippet checks whether an element has a particular class.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> hasClass = <span class="hljs-function">(<span class="hljs-params">el, className</span>) =&gt;</span> el.classList.contains(className);
hasClass(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p.special'</span>), <span class="hljs-string">'special'</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>48. head</strong></p>
<p>This snippet returns the <code>head</code> of a list.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> head = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr[<span class="hljs-number">0</span>];

head([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// 1</span>
</code></pre>
<p><strong>49. hide</strong></p>
<p>This snippet can be used to hide all elements specified.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> hide = <span class="hljs-function">(<span class="hljs-params">...el</span>) =&gt;</span> [...el].forEach(<span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> (e.style.display = <span class="hljs-string">'none'</span>));

hide(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'img'</span>)); <span class="hljs-comment">// Hides all &lt;img&gt; elements on the page</span>
</code></pre>
<p><strong>50. httpsRedirect</strong></p>
<p>This snippet can be used to redirect from HTTP to HTTPS in a particular domain.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> httpsRedirect = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (location.protocol !== <span class="hljs-string">'https:'</span>) location.replace(<span class="hljs-string">'https://'</span> + location.href.split(<span class="hljs-string">'//'</span>)[<span class="hljs-number">1</span>]);
};

httpsRedirect(); <span class="hljs-comment">// If you are on http://mydomain.com, you are redirected to https://mydomain.com</span>
</code></pre>
<p><strong>51. indexOfAll</strong></p>
<p>This snippet can be used to get all indexes of a value in an array, which returns an empty array, in case this value is not included in it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> indexOfAll = <span class="hljs-function">(<span class="hljs-params">arr, val</span>) =&gt;</span> arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, el, i</span>) =&gt;</span> (el === val ? [...acc, i] : acc), []);

indexOfAll([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">1</span>); <span class="hljs-comment">// [0,3]</span>
indexOfAll([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">4</span>); <span class="hljs-comment">// []</span>
</code></pre>
<p><strong>52. initial</strong></p>
<p>This snippet returns all elements of an array except the last one.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initial = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.slice(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>);

initial([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// [1,2]const initial = arr =&gt; arr.slice(0, -1);</span>
initial([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// [1,2]</span>
</code></pre>
<p><strong>53. insertAfter</strong></p>
<p>This snippet can be used to insert an HTML string after the end of a particular element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> insertAfter = <span class="hljs-function">(<span class="hljs-params">el, htmlString</span>) =&gt;</span> el.insertAdjacentHTML(<span class="hljs-string">'afterend'</span>, htmlString);

insertAfter(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myId'</span>), <span class="hljs-string">'&lt;p&gt;after&lt;/p&gt;'</span>); <span class="hljs-comment">// &lt;div id="myId"&gt;...&lt;/div&gt; &lt;p&gt;after&lt;/p&gt;</span>
</code></pre>
<p><strong>54. insertBefore</strong></p>
<p>This snippet can be used to insert an HTML string before a particular element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> insertBefore = <span class="hljs-function">(<span class="hljs-params">el, htmlString</span>) =&gt;</span> el.insertAdjacentHTML(<span class="hljs-string">'beforebegin'</span>, htmlString);

insertBefore(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myId'</span>), <span class="hljs-string">'&lt;p&gt;before&lt;/p&gt;'</span>); <span class="hljs-comment">// &lt;p&gt;before&lt;/p&gt; &lt;div id="myId"&gt;...&lt;/div&gt;</span>
</code></pre>
<p><strong>55. intersection</strong></p>
<p>This snippet can be used to get an array with elements that are included in two other arrays.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> intersection = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> s = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(b);
  <span class="hljs-keyword">return</span> a.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> s.has(x));
};

intersection([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>]); <span class="hljs-comment">// [2, 3]</span>
</code></pre>
<p><strong>56. intersectionBy</strong></p>
<p>This snippet can be used to return a list of elements that exist in both arrays, after a particular function has been executed to each element of both arrays.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> intersectionBy = <span class="hljs-function">(<span class="hljs-params">a, b, fn</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> s = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(b.map(fn));
  <span class="hljs-keyword">return</span> a.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> s.has(fn(x)));
};

intersectionBy([<span class="hljs-number">2.1</span>, <span class="hljs-number">1.2</span>], [<span class="hljs-number">2.3</span>, <span class="hljs-number">3.4</span>], <span class="hljs-built_in">Math</span>.floor); <span class="hljs-comment">// [2.1]</span>
</code></pre>
<p><strong>57. intersectionWith</strong></p>
<p>This snippet can be used to return a list of elements that exist in both arrays by using a comparator function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> intersectionWith = <span class="hljs-function">(<span class="hljs-params">a, b, comp</span>) =&gt;</span> a.filter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> b.findIndex(<span class="hljs-function"><span class="hljs-params">y</span> =&gt;</span> comp(x, y)) !== <span class="hljs-number">-1</span>);

intersectionWith([<span class="hljs-number">1</span>, <span class="hljs-number">1.2</span>, <span class="hljs-number">1.5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">0</span>], [<span class="hljs-number">1.9</span>, <span class="hljs-number">3</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3.9</span>], <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.round(a) === <span class="hljs-built_in">Math</span>.round(b)); <span class="hljs-comment">// [1.5, 3, 0]</span>
</code></pre>
<p><strong>58. is</strong></p>
<p>This snippet can be used to check if a value is of a particular type.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> is = <span class="hljs-function">(<span class="hljs-params">type, val</span>) =&gt;</span> ![, <span class="hljs-literal">null</span>].includes(val) &amp;&amp; val.constructor === type;

is(<span class="hljs-built_in">Array</span>, [<span class="hljs-number">1</span>]); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">ArrayBuffer</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>()); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">Map</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>()); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">RegExp</span>, <span class="hljs-regexp">/./g</span>); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">Set</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>()); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">WeakMap</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>()); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">WeakSet</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>()); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">String</span>, <span class="hljs-string">''</span>); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">String</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">String</span>(<span class="hljs-string">''</span>)); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">Number</span>, <span class="hljs-number">1</span>); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">Number</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>(<span class="hljs-number">1</span>)); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">Boolean</span>, <span class="hljs-literal">true</span>); <span class="hljs-comment">// true</span>
is(<span class="hljs-built_in">Boolean</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">true</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>59. isAfterDate</strong></p>
<p>This snippet can be used to check whether a date is after another date.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isAfterDate = <span class="hljs-function">(<span class="hljs-params">dateA, dateB</span>) =&gt;</span> dateA &gt; dateB;

isAfterDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2010</span>, <span class="hljs-number">10</span>, <span class="hljs-number">21</span>), <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2010</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>60. isAnagram</strong></p>
<p>This snippet can be used to check whether a particular string is an anagram with another string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isAnagram = <span class="hljs-function">(<span class="hljs-params">str1, str2</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> normalize = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span>
    str
      .toLowerCase()
      .replace(<span class="hljs-regexp">/[^a-z0-9]/gi</span>, <span class="hljs-string">''</span>)
      .split(<span class="hljs-string">''</span>)
      .sort()
      .join(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">return</span> normalize(str1) === normalize(str2);
};

isAnagram(<span class="hljs-string">'iceman'</span>, <span class="hljs-string">'cinema'</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>61. isArrayLike</strong></p>
<p>This snippet can be used to check if a provided argument is iterable like an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isArrayLike = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span> obj != <span class="hljs-literal">null</span> &amp;&amp; <span class="hljs-keyword">typeof</span> obj[<span class="hljs-built_in">Symbol</span>.iterator] === <span class="hljs-string">'function'</span>;

isArrayLike(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.className'</span>)); <span class="hljs-comment">// true</span>
isArrayLike(<span class="hljs-string">'abc'</span>); <span class="hljs-comment">// true</span>
isArrayLike(<span class="hljs-literal">null</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>62. isBeforeDate</strong></p>
<p>This snippet can be used to check whether a date is before another date.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isBeforeDate = <span class="hljs-function">(<span class="hljs-params">dateA, dateB</span>) =&gt;</span> dateA &lt; dateB;

isBeforeDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2010</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>), <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2010</span>, <span class="hljs-number">10</span>, <span class="hljs-number">21</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>63. isBoolean</strong></p>
<p>This snippet can be used to check whether an argument is a boolean.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isBoolean = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">'boolean'</span>;

isBoolean(<span class="hljs-literal">null</span>); <span class="hljs-comment">// false</span>
isBoolean(<span class="hljs-literal">false</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>64. isBrowser</strong></p>
<p>This snippet can be used to determine whether the current runtime environment is a browser. This is helpful for avoiding errors when running front-end modules on the server (Node).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isBrowser = <span class="hljs-function">() =&gt;</span> ![<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span>, <span class="hljs-keyword">typeof</span> <span class="hljs-built_in">document</span>].includes(<span class="hljs-string">'undefined'</span>);

isBrowser(); <span class="hljs-comment">// true (browser)</span>
isBrowser(); <span class="hljs-comment">// false (Node)</span>
</code></pre>
<p><strong>65. isBrowserTabFocused</strong></p>
<p>This snippet can be used to determine whether the browser tab is focused.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isBrowserTabFocused = <span class="hljs-function">() =&gt;</span> !<span class="hljs-built_in">document</span>.hidden;

isBrowserTabFocused(); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>66. isLowerCase</strong></p>
<p>This snippet can be used to determine whether a string is lower case.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isLowerCase = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span> str === str.toLowerCase();

isLowerCase(<span class="hljs-string">'abc'</span>); <span class="hljs-comment">// true</span>
isLowerCase(<span class="hljs-string">'a3@$'</span>); <span class="hljs-comment">// true</span>
isLowerCase(<span class="hljs-string">'Ab4'</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>67. isNil</strong></p>
<p>This snippet can be used to check whether a value is <code>null</code> or <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isNil = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> val === <span class="hljs-literal">undefined</span> || val === <span class="hljs-literal">null</span>;

isNil(<span class="hljs-literal">null</span>); <span class="hljs-comment">// true</span>
isNil(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>68. isNull</strong></p>
<p>This snippet can be used to check whether a value is <code>null</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isNull = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> val === <span class="hljs-literal">null</span>;

isNull(<span class="hljs-literal">null</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>69. isNumber</strong></p>
<p>This snippet can be used to check whether a provided value is a number.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isNumber</span>(<span class="hljs-params">n</span>) </span>{
    <span class="hljs-keyword">return</span> !<span class="hljs-built_in">isNaN</span>(<span class="hljs-built_in">parseFloat</span>(n)) &amp;&amp; <span class="hljs-built_in">isFinite</span>(n);
}

isNumber(<span class="hljs-string">'1'</span>); <span class="hljs-comment">// false</span>
isNumber(<span class="hljs-number">1</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>70. isObject</strong></p>
<p>This snippet can be used to check whether a provided value is an object. It uses the Object constructor to create an object wrapper for the given value.</p>
<p>If it is already an object, then an object type that corresponds to the given value will be returned. Otherwise, a new object will be returned.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isObject = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span> obj === <span class="hljs-built_in">Object</span>(obj);

isObject([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]); <span class="hljs-comment">// true</span>
isObject([]); <span class="hljs-comment">// true</span>
isObject([<span class="hljs-string">'Hello!'</span>]); <span class="hljs-comment">// true</span>
isObject({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }); <span class="hljs-comment">// true</span>
isObject({}); <span class="hljs-comment">// true</span>
isObject(<span class="hljs-literal">true</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>71. isObjectLike</strong></p>
<p>This snippet can be used to check if a value is not <code>null</code>and that its <code>typeof</code> is “object”.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isObjectLike = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> val !== <span class="hljs-literal">null</span> &amp;&amp; <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">'object'</span>;

isObjectLike({}); <span class="hljs-comment">// true</span>
isObjectLike([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// true</span>
isObjectLike(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x); <span class="hljs-comment">// false</span>
isObjectLike(<span class="hljs-literal">null</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>72. isPlainObject</strong></p>
<p>This snippet checks whether a value is an object created by the Object constructor.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isPlainObject = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> !!val &amp;&amp; <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">'object'</span> &amp;&amp; val.constructor === <span class="hljs-built_in">Object</span>;

isPlainObject({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }); <span class="hljs-comment">// true</span>
isPlainObject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>()); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>73. isPromiseLike</strong></p>
<p>This snippet checks whether an object looks like a <code>Promise</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isPromiseLike = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span>
  obj !== <span class="hljs-literal">null</span> &amp;&amp;
  (<span class="hljs-keyword">typeof</span> obj === <span class="hljs-string">'object'</span> || <span class="hljs-keyword">typeof</span> obj === <span class="hljs-string">'function'</span>) &amp;&amp;
  <span class="hljs-keyword">typeof</span> obj.then === <span class="hljs-string">'function'</span>;

isPromiseLike({
  <span class="hljs-attr">then</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">''</span>;
  }
}); <span class="hljs-comment">// true</span>
isPromiseLike(<span class="hljs-literal">null</span>); <span class="hljs-comment">// false</span>
isPromiseLike({}); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>74. isSameDate</strong></p>
<p>This snippet can be used to check whether two dates are equal.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isSameDate = <span class="hljs-function">(<span class="hljs-params">dateA, dateB</span>) =&gt;</span> dateA.toISOString() === dateB.toISOString();

isSameDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2010</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>), <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2010</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>75. isString</strong></p>
<p>This snippet can be used to check whether an argument is a string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isString = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">'string'</span>;

isString(<span class="hljs-string">'10'</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>76. isSymbol</strong></p>
<p>This snippet can be used to check whether an argument is a symbol.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isSymbol = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">'symbol'</span>;

isSymbol(<span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'x'</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>77. isUndefined</strong></p>
<p>This snippet can be used to check whether a value is <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isUndefined = <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> val === <span class="hljs-literal">undefined</span>;

isUndefined(<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>78. isUpperCase</strong></p>
<p>This snippet can be used to check whether a string is upper case.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isUpperCase = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span> str === str.toUpperCase();

isUpperCase(<span class="hljs-string">'ABC'</span>); <span class="hljs-comment">// true</span>
isLowerCase(<span class="hljs-string">'A3@$'</span>); <span class="hljs-comment">// true</span>
isLowerCase(<span class="hljs-string">'aB4'</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>79. isValidJSON</strong></p>
<p>This snippet can be used to check whether a string is a valid JSON.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isValidJSON = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-built_in">JSON</span>.parse(str);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
};

isValidJSON(<span class="hljs-string">'{"name":"Adam","age":20}'</span>); <span class="hljs-comment">// true</span>
isValidJSON(<span class="hljs-string">'{"name":"Adam",age:"20"}'</span>); <span class="hljs-comment">// false</span>
isValidJSON(<span class="hljs-literal">null</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>80. last</strong></p>
<p>This snippet returns the last element of an array</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> last = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr[arr.length - <span class="hljs-number">1</span>];

last([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// 3</span>
</code></pre>
<p><strong>81. matches</strong></p>
<p>This snippet compares two objects to determine if the first one contains the same property values as the second one.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> matches = <span class="hljs-function">(<span class="hljs-params">obj, source</span>) =&gt;</span>
  <span class="hljs-built_in">Object</span>.keys(source).every(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span> obj.hasOwnProperty(key) &amp;&amp; obj[key] === source[key]);

matches({ <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>, <span class="hljs-attr">hair</span>: <span class="hljs-string">'long'</span>, <span class="hljs-attr">beard</span>: <span class="hljs-literal">true</span> }, { <span class="hljs-attr">hair</span>: <span class="hljs-string">'long'</span>, <span class="hljs-attr">beard</span>: <span class="hljs-literal">true</span> }); <span class="hljs-comment">// true</span>
matches({ <span class="hljs-attr">hair</span>: <span class="hljs-string">'long'</span>, <span class="hljs-attr">beard</span>: <span class="hljs-literal">true</span> }, { <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>, <span class="hljs-attr">hair</span>: <span class="hljs-string">'long'</span>, <span class="hljs-attr">beard</span>: <span class="hljs-literal">true</span> }); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong>82. maxDate</strong></p>
<p>This snippet can be used to get the latest date.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> maxDate = <span class="hljs-function">(<span class="hljs-params">...dates</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Math</span>.max.apply(<span class="hljs-literal">null</span>, ...dates));

<span class="hljs-keyword">const</span> array = [
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2017</span>, <span class="hljs-number">4</span>, <span class="hljs-number">13</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2018</span>, <span class="hljs-number">2</span>, <span class="hljs-number">12</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2016</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2016</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>)
];
maxDate(array); <span class="hljs-comment">// 2018-03-11T22:00:00.000Z</span>
</code></pre>
<p><strong>83. maxN</strong></p>
<p>This snippet returns the <code>n</code> largest elements from a list. If <code>n</code>is greater than or equal to the list’s length, then it will return the original list (sorted in descending order).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> maxN = <span class="hljs-function">(<span class="hljs-params">arr, n = <span class="hljs-number">1</span></span>) =&gt;</span> [...arr].sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> b - a).slice(<span class="hljs-number">0</span>, n);

maxN([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// [3]</span>
maxN([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">2</span>); <span class="hljs-comment">// [3,2]</span>
</code></pre>
<p><strong>84. minDate</strong></p>
<p>This snippet can be used to get the earliest date.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> minDate = <span class="hljs-function">(<span class="hljs-params">...dates</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Math</span>.min.apply(<span class="hljs-literal">null</span>, ...dates));

<span class="hljs-keyword">const</span> array = [
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2017</span>, <span class="hljs-number">4</span>, <span class="hljs-number">13</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2018</span>, <span class="hljs-number">2</span>, <span class="hljs-number">12</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2016</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2016</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>)
];
minDate(array); <span class="hljs-comment">// 2016-01-08T22:00:00.000Z</span>
</code></pre>
<p><strong>85. minN</strong></p>
<p>This snippet returns the <code>n</code> smallest elements from a list. If <code>n</code>is greater than or equal to the list’s length, then it will return the original list (sorted in ascending order).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> minN = <span class="hljs-function">(<span class="hljs-params">arr, n = <span class="hljs-number">1</span></span>) =&gt;</span> [...arr].sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b).slice(<span class="hljs-number">0</span>, n);

minN([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]); <span class="hljs-comment">// [1]</span>
minN([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">2</span>); <span class="hljs-comment">// [1,2]</span>
</code></pre>
<p><strong>86. negate</strong></p>
<p>This snippet can be used to apply the not operator (<code>!</code>) to a predicate function with its arguments.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> negate = <span class="hljs-function"><span class="hljs-params">func</span> =&gt;</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> !func(...args);

[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>].filter(negate(<span class="hljs-function"><span class="hljs-params">n</span> =&gt;</span> n % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>)); <span class="hljs-comment">// [ 1, 3, 5 ]</span>
</code></pre>
<p><strong>87. nodeListToArray</strong></p>
<p>This snippet can be used to convert a <code>nodeList</code> to an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nodeListToArray = <span class="hljs-function"><span class="hljs-params">nodeList</span> =&gt;</span> [...nodeList];

nodeListToArray(<span class="hljs-built_in">document</span>.childNodes); <span class="hljs-comment">// [ &lt;!DOCTYPE html&gt;, html ]</span>
</code></pre>
<p><strong>88. pad</strong></p>
<p>This snippet can be used to <code>pad</code> a string on both sides with a specified character if it is shorter than the specified length.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pad = <span class="hljs-function">(<span class="hljs-params">str, length, char = <span class="hljs-string">' '</span></span>) =&gt;</span>
  str.padStart((str.length + length) / <span class="hljs-number">2</span>, char).padEnd(length, char);

pad(<span class="hljs-string">'cat'</span>, <span class="hljs-number">8</span>); <span class="hljs-comment">// '  cat   '</span>
pad(<span class="hljs-built_in">String</span>(<span class="hljs-number">42</span>), <span class="hljs-number">6</span>, <span class="hljs-string">'0'</span>); <span class="hljs-comment">// '004200'</span>
pad(<span class="hljs-string">'foobar'</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// 'foobar'</span>
</code></pre>
<p><strong>89. radsToDegrees</strong></p>
<p>This snippet can be used to convert an angle from radians to degrees.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> radsToDegrees = <span class="hljs-function"><span class="hljs-params">rad</span> =&gt;</span> (rad * <span class="hljs-number">180.0</span>) / <span class="hljs-built_in">Math</span>.PI;

radsToDegrees(<span class="hljs-built_in">Math</span>.PI / <span class="hljs-number">2</span>); <span class="hljs-comment">// 90</span>
</code></pre>
<p><strong>90. Random Hexadecimal Color Code</strong></p>
<p>This snippet can be used to generate a random hexadecimal color code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> randomHexColorCode = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> n = (<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">0xfffff</span> * <span class="hljs-number">1000000</span>).toString(<span class="hljs-number">16</span>);
  <span class="hljs-keyword">return</span> <span class="hljs-string">'#'</span> + n.slice(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>);
};

randomHexColorCode(); <span class="hljs-comment">// "#e34155"</span>
</code></pre>
<p><strong>91. randomIntArrayInRange</strong></p>
<p>This snippet can be used to generate an array with <code>n</code> random integers in a specified range.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> randomIntArrayInRange = <span class="hljs-function">(<span class="hljs-params">min, max, n = <span class="hljs-number">1</span></span>) =&gt;</span>
  <span class="hljs-built_in">Array</span>.from({ <span class="hljs-attr">length</span>: n }, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * (max - min + <span class="hljs-number">1</span>)) + min);

randomIntArrayInRange(<span class="hljs-number">12</span>, <span class="hljs-number">35</span>, <span class="hljs-number">10</span>); <span class="hljs-comment">// [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]</span>
</code></pre>
<p><strong>92. randomIntegerInRange</strong></p>
<p>This snippet can be used to generate a random integer in a specified range.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> randomIntegerInRange = <span class="hljs-function">(<span class="hljs-params">min, max</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * (max - min + <span class="hljs-number">1</span>)) + min;

randomIntegerInRange(<span class="hljs-number">0</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// 3</span>
</code></pre>
<p><strong>93. randomNumberInRange</strong></p>
<p>This snippet can be used to return a random number in a specified range.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> randomNumberInRange = <span class="hljs-function">(<span class="hljs-params">min, max</span>) =&gt;</span> <span class="hljs-built_in">Math</span>.random() * (max - min) + min;

randomNumberInRange(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>); <span class="hljs-comment">// 6.0211363285087005</span>
</code></pre>
<p><strong>94. readFileLines</strong></p>
<p>This snippet can be used to read a file by getting an array of lines from a file.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> readFileLines = <span class="hljs-function"><span class="hljs-params">filename</span> =&gt;</span>
  fs
    .readFileSync(filename)
    .toString(<span class="hljs-string">'UTF8'</span>)
    .split(<span class="hljs-string">'\n'</span>);

<span class="hljs-keyword">let</span> arr = readFileLines(<span class="hljs-string">'test.txt'</span>);
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// ['line1', 'line2', 'line3']</span>
</code></pre>
<p><strong>95. Redirect to a URL</strong></p>
<p>This snippet can be used to do a redirect to a specified URL.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> redirect = <span class="hljs-function">(<span class="hljs-params">url, asLink = <span class="hljs-literal">true</span></span>) =&gt;</span>
  asLink ? (<span class="hljs-built_in">window</span>.location.href = url) : <span class="hljs-built_in">window</span>.location.replace(url);

redirect(<span class="hljs-string">'https://google.com'</span>);
</code></pre>
<p><strong>96. reverse</strong></p>
<p>This snippet can be used to reverse a string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> reverseString = <span class="hljs-function"><span class="hljs-params">str</span> =&gt;</span> [...str].reverse().join(<span class="hljs-string">''</span>);

reverseString(<span class="hljs-string">'foobar'</span>); <span class="hljs-comment">// 'raboof'</span>
</code></pre>
<p><strong>97. round</strong></p>
<p>This snippet can be used to round a number to a specified number of digits.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> round = <span class="hljs-function">(<span class="hljs-params">n, decimals = <span class="hljs-number">0</span></span>) =&gt;</span> <span class="hljs-built_in">Number</span>(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">Math</span>.round(<span class="hljs-string">`<span class="hljs-subst">${n}</span>e<span class="hljs-subst">${decimals}</span>`</span>)}</span>e-<span class="hljs-subst">${decimals}</span>`</span>);

round(<span class="hljs-number">1.005</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 1.01</span>
</code></pre>
<p><strong>98. runPromisesInSeries</strong></p>
<p>This snippet can be used to run an array of promises in series.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> runPromisesInSeries = <span class="hljs-function"><span class="hljs-params">ps</span> =&gt;</span> ps.reduce(<span class="hljs-function">(<span class="hljs-params">p, next</span>) =&gt;</span> p.then(next), <span class="hljs-built_in">Promise</span>.resolve());
<span class="hljs-keyword">const</span> delay = <span class="hljs-function"><span class="hljs-params">d</span> =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">r</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(r, d));

runPromisesInSeries([<span class="hljs-function">() =&gt;</span> delay(<span class="hljs-number">1000</span>), <span class="hljs-function">() =&gt;</span> delay(<span class="hljs-number">2000</span>)]); 
<span class="hljs-comment">// Executes each promise sequentially, taking a total of 3 seconds to complete</span>
</code></pre>
<p><strong>99. sample</strong></p>
<p>This snippet can be used to get a random number from an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sample = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr[<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * arr.length)];

sample([<span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>]); <span class="hljs-comment">// 9</span>
</code></pre>
<p><strong>100. sampleSize</strong></p>
<p>This snippet can be used to get <code>n</code>random elements from unique positions from an array up to the size of the array. Elements in the array are shuffled using the <a target="_blank" href="https://morioh.com/redirect?l=https%3A%2F%2Fgithub.com%2F30-seconds%2F30-seconds-of-code%23shuffle"><strong>Fisher-Yates algorithm</strong></a></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sampleSize = <span class="hljs-function">(<span class="hljs-params">[...arr], n = <span class="hljs-number">1</span></span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> m = arr.length;
  <span class="hljs-keyword">while</span> (m) {
    <span class="hljs-keyword">const</span> i = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  <span class="hljs-keyword">return</span> arr.slice(<span class="hljs-number">0</span>, n);
};

sampleSize([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">2</span>); <span class="hljs-comment">// [3,1]</span>
sampleSize([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">4</span>); <span class="hljs-comment">// [2,3,1]</span>
<span class="hljs-string">``</span><span class="hljs-string">`.</span>
</code></pre>
<p>Thank you for reading!!</p>
<p>If you like my work!!</p>
<p>Please follow me on Twitter <a target="_blank" href="https://twitter.com/frontendgenius">https://twitter.com/frontendgenius</a></p>
]]></content:encoded></item><item><title><![CDATA[Get Ahead with These 50+ ChatGPT Use Cases]]></title><description><![CDATA[Welcome to our blog guys where we'll be sharing over 50+ ChatGPT use cases that can help you get ahead in various aspects of your life. As a large language model trained by OpenAI, ChatGPT can assist you in a multitude of tasks, from answering genera...]]></description><link>https://frontendgenius.com/get-ahead-with-these-50-chatgpt-use-cases</link><guid isPermaLink="true">https://frontendgenius.com/get-ahead-with-these-50-chatgpt-use-cases</guid><category><![CDATA[chatgpt]]></category><category><![CDATA[AI]]></category><category><![CDATA[Chat-GPT]]></category><category><![CDATA[chatgptguide]]></category><category><![CDATA[Artificial Intelligence]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Mon, 03 Apr 2023 09:08:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680510798675/7d743216-37fc-4496-888d-da4ea7ed9d54.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to our blog guys where we'll be sharing over 50+ ChatGPT use cases that can help you get ahead in various aspects of your life. As a large language model trained by OpenAI, ChatGPT can assist you in a multitude of tasks, from answering general knowledge questions to providing personalized recommendations. Whether you're a student, professional, or just someone looking to simplify their daily tasks, ChatGPT has got you covered. With its advanced natural language processing abilities, ChatGPT can understand and respond to your queries like a human. So, let's explore the numerous ways in which ChatGPT can enhance your productivity, learning, and overall lifestyle.</p>
<h2 id="heading-8-business-ideas-you-can-start-now-using-chatgpt">8 business ideas you can start now using ChatGPT</h2>
<p>ChatGPT, the popular AI language model, has captured the attention of the internet. Its potential for generating income online is virtually limitless. You can start a variety of businesses using ChatGPT without spending any money. Here are eight business ideas you can get started with right away.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680510823682/af0ce96a-8747-40f8-9f16-c4790b8d26e4.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>1. Landing page</strong></p>
<p>Landing pages are standalone web pages designed to direct visitors to take one specific action (like purchasing a product) With ChatGPT, you can write compelling landing pages that target a client's ideal audience.</p>
<p><img src="https://pbs.twimg.com/media/Fk__mcWaAAAmCyo?format=png&amp;name=small" alt="Image" /></p>
<p><strong>2. Email marketing</strong></p>
<p>Email marketing campaigns are a great way for businesses to increase awareness or promote their products/services. With ChatGPT, you can write email sequences to nurture your client's audience or drive conversions.</p>
<p><img src="https://pbs.twimg.com/media/Fk__mpoakAEGEo4?format=png&amp;name=small" alt="Image" /></p>
<p><strong>3. Weekly newsletter</strong></p>
<p>Growing a newsletter is a great way to build and monetize an audience. With ChatGPT, you can plan and write a newsletter much faster to grow an email list and eventually sell sponsorship spots.</p>
<p><img src="https://pbs.twimg.com/media/Fk__m5caMAANsmi?format=png&amp;name=small" alt="Image" /></p>
<p><strong>4. Video scriptwriting</strong></p>
<p>A good video script captures attention and delivers a clear message to its viewers. With ChatGPT, you can craft video scripts for TikTok or YouTube to sell or use for your own purposes.</p>
<p><img src="https://pbs.twimg.com/media/Fk__nHBagAU54mF?format=png&amp;name=small" alt="Image" /></p>
<p><strong>5. Blog post</strong></p>
<p>writing Long-form content builds authority within an industry or niche. With ChatGPT, you can combat writer's block and create blog posts to sell in a fraction of the amount of time.</p>
<p><img src="https://pbs.twimg.com/media/Fk__nX1aYAQwH78?format=png&amp;name=small" alt="Image" /></p>
<p><strong>6. Blog headlines</strong></p>
<p>A strong, catchy headline will have readers clicking on a blog post. With ChatGPT, you can help clients create interesting headlines which stop the scroll.</p>
<p><img src="https://pbs.twimg.com/media/Fk__noEaYAA4XW9?format=jpg&amp;name=small" alt="Image" /></p>
<p><strong>7. Product descriptions</strong></p>
<p>Detailed product descriptions help buyers make purchase decisions. With ChatGPT, you can write product descriptions for e-commerce websites.</p>
<p><img src="https://pbs.twimg.com/media/Fk__n0DaYAI6_8s?format=png&amp;name=small" alt="Image" /></p>
<p><strong>8. Niche eBooks</strong></p>
<p>Many brands and creators use eBooks as lead magnets or low-ticket offers. With ChatGPT, you can outline and write eBooks on specific topics.</p>
<p><img src="https://pbs.twimg.com/media/Fk__oBlaEAARV44?format=png&amp;name=small" alt="Image" /></p>
<p>Final thoughts: It's still difficult to predict how ChatGPT and other AI will change the future of work. But one thing remains clear: Understanding how to use them is a competitive edge. Is it perfect? Far from it. But it'll save significant amounts of time with work.</p>
<h2 id="heading-10-mindblowing-things-you-can-do-using-chhatgpt-right-now">10 Mindblowing things you can do using ChhatGPT right now</h2>
<p>ChatGPT has crossed 1M+ users in just 5 days. To compare, it took Netflix 41 months, FB - 10 months, and Instagram - 2.5 months. But many haven’t yet realized its full potential. Here are the 10 mindblowing things you can do using it right now.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680510851143/dbcc830e-1a0d-4288-9c6b-628053fea5fd.jpeg" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="https://twitter.com/thesyedhuq/status/1607784637589487616/photo/1">  
</a><strong>1. Generate code:</strong></p>
<p>ChatGPT can help you generate code to build your app/website from scratch. You save time and effort and can focus on the more important tasks. 100X engineer just arrived.</p>
<p>See the below tweet.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/packyM/status/1598405769669771264?s=20">https://twitter.com/packyM/status/1598405769669771264?s=20</a></div>
<p> </p>
<p>Rakshit, who had zero programming knowledge, used this feature to create a Twitter bot.</p>
<p><a target="_blank" href="https://medium.com/@rlodha1/how-i-used-chat-gpt-to-build-a-twitter-bot-without-any-programming-language-35bbc43f6ad">How I used Chat GPT to build a Twitter bot without knowing any programming language</a></p>
<p><strong>2. Track fitness:</strong></p>
<p>Alex created a weight loss, diet, and workout plan on top of ChatGPT.</p>
<p>He has always been curious about the capabilities of AI and how it can impact our lives. So when I stumbled upon ChatGPT, a language model trained by OpenAI he was intrigued. After playing around with it for a bit, He decided to put it to the test and see if it could create a personalized weight loss plan for him.</p>
<p>Read the full tweet thread below.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/anothercohen/status/1599531037570502656?s=20">https://twitter.com/anothercohen/status/1599531037570502656?s=20</a></div>
<p> </p>
<p><strong>3. Debug code:</strong></p>
<p>ChatGPT is your 24/7 debugging companion. It finds the bugs, fixes them, and even explains the solution.</p>
<p>ChatGPT could be a good debugging companion; it not only explains the bug but fixes it and explain the fix.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/amasad/status/1598042665375105024?s=20">https://twitter.com/amasad/status/1598042665375105024?s=20</a></div>
<p> </p>
<p><strong>4. Have a personal assistant:</strong></p>
<p>Integrate ChatGPT to your WhatsApp and automate the manual and repetitive tasks: write emails, get quick answers to any questions, fasten research, and more.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/danielgross/status/1598735800497119232?s=20">https://twitter.com/danielgross/status/1598735800497119232?s=20</a></div>
<p> </p>
<p><strong>5. Marketing Plan</strong></p>
<p>Create a marketing/SEO strategy, audit your website, do keyword research, write articles/copy, and more—all in less than 30 minutes.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/heykahn/status/1599749880515244034?s=20">https://twitter.com/heykahn/status/1599749880515244034?s=20</a></div>
<p> </p>
<p><strong>6. Create a Virtual Machine:</strong></p>
<p>Research Scientist Jonas Degrave ran a virtual machine (Linux terminal) inside ChatGPT.</p>
<p>Unless you have been living under a rock, you have heard of <a target="_blank" href="https://chat.openai.com/chat?ref=engraved.blog">this new ChatGPT assistant</a> made by OpenAI. You might be aware of its capabilities for <a target="_blank" href="https://twitter.com/SergeyI49013776/status/1598430479878856737?ref=engraved.blog">solving IQ tests</a>, <a target="_blank" href="https://news.ycombinator.com/item?id=33833420&amp;ref=engraved.blog">tackling leetcode problems</a>, or <a target="_blank" href="https://twitter.com/jdjkelly/status/1598021488795586561?ref=engraved.blog">helping people write LateX</a>. It is an amazing resource for people to retrieve all kinds of information and solve tedious tasks, like copywriting!</p>
<p><a target="_blank" href="https://www.engraved.blog/building-a-virtual-machine-inside/">https://www.engraved.blog/building-a-virtual-machine-inside/</a></p>
<p><strong>7. Creative liberty:</strong></p>
<p>Write essays, music, sitcom/movie scripts, and jokes.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/GuyP/status/1598668947439685633?s=20">https://twitter.com/GuyP/status/1598668947439685633?s=20</a></div>
<p> </p>
<p><strong>8. Develop plugins</strong></p>
<p>ChatGPT created a working WordPress plugin on the first try.</p>
<p>ChatGPT <a target="_blank" href="https://twitter.com/sama/status/1599668808285028353">passed 1 million users</a> today and Twitter is brimming with a steady stream of creative questions and applications for the AI-powered chatbot. The language model, <a target="_blank" href="https://openai.com/blog/chatgpt/">created by OpenAI</a>, is powered by GPT-3.5, a series of models trained on text and code from before Q4 2021. The model features a dialogue format that gives ChatGPT the ability to “answer follow-up questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests.”</p>
<p><a target="_blank" href="https://wptavern.com/chatgpt-creates-a-working-wordpress-plugin-on-the-first-try">ChatGPT Creates a Working WordPress Plugin</a></p>
<p><strong>9. Game development:</strong></p>
<p>An 11-year-old developed a game using the ChatGPT prompts. Thousands of people have already played it.</p>
<p><img src="https://pbs.twimg.com/card_img/1640635372907515905/mo0SWRxp?format=jpg&amp;name=small" alt class="image--center mx-auto" /></p>
<p><a target="_blank" href="https://mpost.io/11-year-old-boys-game-for-chatgpt-is-blowing-up-the-internet/">11-year-old boy’s game for ChatGPT is blowing up the internet</a></p>
<p><strong>10. Medical aid</strong></p>
<p>You can develop a 24/7 chatbot to seek treatments for a few medical problems. Of course, as mentioned below, you need to check for biases and misinformation, but this is a good start.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/RoxanaDaneshjou/status/1598170660186251264?s=20">https://twitter.com/RoxanaDaneshjou/status/1598170660186251264?s=20</a></div>
<p> </p>
<h2 id="heading-10-techniques-to-get-massively-ahead-with-ai">10 techniques to get massively ahead with AI</h2>
<p>Everyone’s using ChatGPT. But almost everyone's STUCK in beginner mode. 10 techniques to get massively ahead with AI: (cut-and-paste these prompts).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680510933992/2a4ae45f-9e12-4e57-8c15-8fedfdd0f7dc.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>1. Simulate an expert</strong></p>
<p>Ask ChatGPT to play the part of a customer, co-host, or talented expert. Have a conversation with it, or ask it to generate content as if it were that specific persona.</p>
<p>/Example prompt/</p>
<p>You are a talented analyst at a top-tier market research firm, a graduate of Harvard Business School. Coach me to create content that connects with C-level executives at B2B SaaS companies. What open-ended questions do I ask? Prioritize uncommon, expert advice.</p>
<p><strong>2. Challenge the conventional narrative</strong></p>
<p>Ask for examples of what contradicts the dominant narrative. Generate content that challenges readers' assumptions. Seek out provocative angles that defy expectations and break the mold.</p>
<p>/Example prompt/</p>
<p>Topic: Growing your email newsletter For the above topic, give examples that contradict the dominant narrative. Generate an outline for thought-provoking content that challenges assumptions.</p>
<p><strong>3. Use unconventional prompts</strong></p>
<p>Try using prompts that are more open-ended or abstract. This way you’ll get unique and creative responses nobody else is. By getting weird, you can unlock ChatGPT's creative potential in finding vivid language and unexpected topics.</p>
<p>/Example prompts/</p>
<p>Write a poem about copywriting. - Describe feeling like an entrepreneur in 10 adjectives.</p>
<p><strong>4. Ultra-Brainstormer</strong></p>
<p>It’s easy to have ChatGPT generate a list of potential topic ideas for your next project. But often they're generic and expected. Instead, ask it to come up with new angles or approaches to cover a familiar topic.</p>
<p>/Example prompt/ Topic: How to double your creative output. For the topic above, brainstorm new angles or approaches. Prioritize ideas that are uncommon or novel.</p>
<p><strong>5. Capture your writing style</strong></p>
<p>Feed ChatGPT your writing. Ask it to help you create a style guide for future outputs. It’ll give you the exact words to describe your voice and tone in a way that AIs understand.</p>
<p>/Example prompt/</p>
<p>Analyze the text below for style, voice, and tone. Using NLP, create a prompt to write a new article in the same style, voice, and tone: (Insert your text here)</p>
<p><strong>6. Add in human-written techniques</strong></p>
<p>Ask ChatGPT it to work according to good advice you've read elsewhere. In the prompt below, I take some tips on persuasive writing from the Grammarly blog and ask it to apply them to my topic.</p>
<p>/Example prompt/</p>
<p>Write a brief post about why copywriting is an essential skill in 2023. Use these strategies: - Use strong persuasive language - Ask questions to transition between paragraphs - Back up main points with evidence and examples - Speak directly to the reader</p>
<p><strong>7. Have ChatGPT write from different perspectives</strong></p>
<p>Ask it to write from the perspective of a group of characters with different backgrounds or viewpoints. Explore new ideas and perspectives, and add depth to your writing.</p>
<p>/Example prompt/</p>
<p>Topic: Productivity for entrepreneurs For the above topic, write multiple perspectives from a group with different viewpoints. For each perspective, write in their own voice, using phrases that person would use.</p>
<p><strong>8. Write in different styles or tones, such as satire or irony</strong></p>
<p>Takeaway: By experimenting with different voices and perspectives, you can use ChatGPT to create more dynamic and varied content.</p>
<p>/Example prompt/</p>
<p>Give the most ironic, satirical advice you can about using ChatGPT to create more effective content.</p>
<p><strong>9. Use ChatGPT to write in different formats</strong></p>
<p>Ask ChatGPT to vary its output.</p>
<p>• Outline</p>
<p>• Mind map</p>
<p>• Bullet points</p>
<p>• Persuasive essay</p>
<p>• Chunks of text of less than 280 characters</p>
<p>• Using the structure: 1) What, 2) Why, 3) How</p>
<p>/Example prompt/</p>
<p>Create a mind map on the topic of using Notion to stay organized as a content creator, listing out the central idea, main branches, and sub-branches.</p>
<p><strong>10. Generate content with a specific purpose or goal in mind</strong></p>
<p>Tell ChatGPT who your audience is and what you want to achieve with your content. Remember, it has no context about who you are or what you want unless you give it some. So give it context.</p>
<p>/Example prompt/</p>
<p>Topic: How to grow your coaching business For audience: Business coaches Content goal: Motivate audience to feel excited about growing their business while teaching them one tip. Writing style: Clear, concise, conversational, down-to-earth, humble, experienced</p>
<p><strong>Get creative with ChatGPT</strong></p>
<p>• The more you experiment, the more you'll discover</p>
<p>• Try out new and unconventional ideas</p>
<p>• Seek out new ways to find interesting and unique content angles Oh, and have a little fun, creating truly unique content in the process.</p>
<p>BTW — if you're looking to jump way ahead: Check out <a target="_blank" href="https://twitter.com/thatroblennon">Rob Lennon</a> just-released course and AI writing system. Comes with a ton of example prompts way more sophisticated.</p>
<p><a target="_blank" href="https://aicontentreactor.com/">AI Content Reactor</a></p>
<h2 id="heading-11-ways-to-use-it-to-create-your-content">11 ways to use it to create your content</h2>
<p>11 unique ways to use technology to create compelling content. In today's digital age, technology has revolutionized the way we communicate and share information. Whether you're a content creator, blogger, or marketer, the right tools can make a significant difference in the quality and effectiveness of your content. From social media platforms to content creation tools, we will be exploring a range of options that can help you elevate your content game and engage your audience like never before. So, let's dive in and discover how you can leverage technology to create outstanding content.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680511032614/14b9a544-2cb4-4426-8335-e7d48f6e2d82.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>1. Twitter Thread Hooks</strong></p>
<p>Get ideas for your thread hooks. Ask ChatGPT to write hooks on your topic. Example of hooks for how to use ChatGPT for content creation.</p>
<p><img src="https://pbs.twimg.com/media/FkHlO55XwAQKKC8?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>Generate more</strong></p>
<p>The thread hooks might not work for you. Generate a few more:</p>
<p><img src="https://pbs.twimg.com/media/FkHlPhUXwBgXZf1?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>2. Thread Conclusions</strong></p>
<p>ChatGPT can write a thread conclusion for you. Re-write it in your voice, or use it if English isn't your first language:</p>
<p><img src="https://pbs.twimg.com/media/FkHlQOkXwCQmBIO?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>3. Thread CTA's</strong></p>
<p>Finish your thread with a call to action. Ask ChatGPT to write more if you're not satisfied:</p>
<p><img src="https://pbs.twimg.com/media/FkHlQ9NXwAow4xE?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>4. Tweets</strong></p>
<p>Ask ChatGPT to write a Tweet for you. Use it as a template or rewrite it in your own words. Here's an example for a Tweet about the benefits of journaling:</p>
<p><img src="https://pbs.twimg.com/media/FkHlRoSXwBIvspW?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>5. Tweets: Listicles</strong></p>
<p>Ask ChatGPT for a listicle Tweet. Here are two Tweets about no-code too.</p>
<p><img src="https://pbs.twimg.com/media/FkHlS2DXwAIATnC?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>6. Quotes with Explanations</strong></p>
<p>Using a relevant quote can add more depth to your content. Ask ChatGPT for quotes on a topic. Bonus: Get examples for each quote to add value to your audience.</p>
<p><img src="https://pbs.twimg.com/media/FkHlThTXwAscguN?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>7. Email Newsletter</strong></p>
<p>Subject Lines Ask ChatGPT for email subject lines for your newsletter. Here's a few examples to welcome new subscribers:</p>
<p><img src="https://pbs.twimg.com/media/FkHlUEuXwAYBWSk?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>8. Emails</strong></p>
<p>Once you have a subject line, ask ChatGPT to write the email. Here's an example of a welcome message for new subscribers:</p>
<p><img src="https://pbs.twimg.com/media/FkHlUxEXwDMHdoJ?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>9. Instagram Post Captions</strong></p>
<p>Ask ChatGPT to write a caption for your Instagram posts. Examples of a post about a new computer:</p>
<p><img src="https://pbs.twimg.com/media/FkHlVXDXwBsTxbk?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>10. LInkedIn Posts</strong></p>
<p>Ask ChatGPT to write a LinkedIn post. Example of a LinkedIn post about the different ways you can use ChatGPT to generate leads to your business:</p>
<p><img src="https://pbs.twimg.com/media/FkHlWOWXwAIHT2A?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p>YouTube Video Intros Ask ChatGPT to write an intro script for your YouTube video. I asked for a script to explain how to use ChatGPT for content creation:</p>
<p><img src="https://pbs.twimg.com/media/FkHlW-RXwC8LmYk?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p><strong>11. Brainstorm</strong></p>
<p>Topic Ideas You can use ChatGPT to help you brainstorm ideas for content topics. I asked for 3 ways to have a growth mindset. ChatGPT gave me 2 extra ideas:</p>
<p><img src="https://pbs.twimg.com/media/FkHlXmGXgAAdmqY?format=png&amp;name=small" alt="Image" class="image--center mx-auto" /></p>
<p>Recap 11 ways to use ChatGPT to create your content:</p>
<p>• Thread Hooks</p>
<p>• Thread conclusions</p>
<p>• CTAs</p>
<p>• Tweets</p>
<p>• Quotes</p>
<p>• Email subject lines</p>
<p>• Emails</p>
<p>• IG captions</p>
<p>• LinkedIn posts</p>
<p>• YouTube intros</p>
<p>• Topic ideas</p>
<h2 id="heading-10-ways-to-use-chatgpt-for-your-marketing-strategy"><strong>10 ways to use ChatGPT for your marketing strategy</strong></h2>
<p>ChatGPT will save your marketing team thousands of hours, If they know how to use it. Here are 10 unconventional ways ChatGPT will augment your marketing team in 2023.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680511055928/52de1152-c9d5-4418-a8c1-c3c44e733bb3.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>1. Chatbot Scripting</strong></p>
<p>Example prompt: "Write a script for a chatbot that can help customers find the right pair of shoes."</p>
<p><strong>2. Social Media Engagement</strong></p>
<p>Create 100% personalized comments on social media. Example prompt: "Write a reply to this tweet [tweet] that'll show our support."</p>
<p><strong>3. Virtual Event Scripting</strong></p>
<p>ChatGPT can help you write scripts for virtual events such as webinars, online conferences, or product launches. Example prompt: "Write a script for a virtual product launch event that will keep the audience engaged."</p>
<p><strong>4. Gamification</strong></p>
<p>ChatGPT can help you write fun interactive elements like quizzes, trivia games or scavenger hunts that will make your marketing campaigns more engaging. Example prompt: "Write a set of trivia questions based on productivity frameworks."</p>
<p><strong>5. Influencer Outreach</strong></p>
<p>ChatGPT can help you write cold DMs to help you sign big influencer campaigns. Example prompt: "Write a cold DM to an influencer asking to collaborate with them based on this bio [bio here]."</p>
<p><strong>6. Podcast Scripting</strong></p>
<p>ChatGPT can help you write scripts for podcast episodes that will keep the listeners engaged and interested in your topic. Example prompt: "Write a script for a podcast episode discussing the future of AI and productivity."</p>
<p><strong>7. Content Generation</strong></p>
<p>ChatGPT can help generate a lot of content fast. Example prompt: "Write a short Instagram caption for a photo of our new organic running shoes."</p>
<p><strong>8. Language Translation</strong></p>
<p>ChatGPT can help translate your messages into different languages so you can reach more people. Example prompt: "Translate the following sentence into Spanish: 'Check out our new collection of clothing'"</p>
<p><strong>9. Lead generation</strong></p>
<p>ChatGPT can help you write CTAs that persuade people to optin. Example prompt: "Write a CTA that will convince website visitors to sign up for our newsletter."</p>
<p><strong>10. Email Campaigns</strong></p>
<p>ChatGPT can help you write high-quality emails fast. Example prompt: "Write an email to customers who haven't purchased in the last three months."</p>
<h2 id="heading-7-ways-to-maximize-your-productivity-using-chatgpt">7 ways to maximize your productivity using ChatGPT</h2>
<p>Chat GPT is Ground-Shattering technology But 99% of people are stuck in beginner mode 7 dead simple ways you can use Chat-GPT to 10X your productivity in 2023.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680511165378/5786005e-7954-4d9c-9160-b4884f40fca8.jpeg" alt class="image--center mx-auto" /></p>
<p><strong>1. Generate code</strong></p>
<p>Chat-GPT can write runnable code in seconds Professionals can use it to shave of days of work Newbies can use it to get started. You don't have all day so here is Chat-GPT coding a functional calculator (I checked):</p>
<p>Example: How would you write a Python function that takes in a list of integers and returns the sum of all even numbers in the list?</p>
<p><strong>2. Formal writing</strong></p>
<p>Ever wanted a personal assistant? Well Chat-GPT works for free and never get's tired or complains Chat-GPT can write:</p>
<p>Copy, Emails, Essays, Contracts, Newsletters, Video Scripts If you can do it Chat-GPT can do it 10 times faster.</p>
<p>Example: Write a persuasive essay arguing for or against the implementation of a national minimum wage increase to $15 per hour. In your essay, provide evidence and statistics to support your position and address potential counterarguments. Additionally, consider the economic and social implications of such a policy and its potential impact on both workers and businesses.</p>
<p><strong>3. Analyze Information</strong></p>
<p>Not only can it write but it can summarize Save yourself the hassle by letting Chat-GPT summarize: Books, Articles, Long emails, Youtube videos, University Lectures, A Textbook chapters.</p>
<p>Example: You come across a news article claiming that a new study shows that coffee can reduce the risk of heart disease. Analyze the information presented in the article and identify any potential limitations or biases in the study.</p>
<p><strong>4. Creative Work</strong></p>
<p>Chat-GPT is only limited by your imagination Ask Chat-GPT to generate ideas Think of clever solutions to problems Or even better write a poem about AI in the tone of Eminem.</p>
<p>Example: Write a short story about a character who discovers a hidden portal to a magical world.</p>
<p><strong>5. Make money</strong></p>
<p>online Chat-GPT has opened the realm of opportunity Use Chat-GPT to formulate a business plan. Teach you a new skill. Or even code you a day trading bot (seriously).</p>
<p>Example: What are some creative and legitimate ways to make money from home?</p>
<p><strong>6. Simulate an expert</strong></p>
<p>Chat-GPT can play any role you want it to. Ask for advice. Debate any topic. Learn a new skill Anything is possible with AI.</p>
<p>Example: Prompt: You are an expert in baking cakes. Imagine you're speaking to a novice baker who wants to make a cake for their friend's birthday. Provide them with step-by-step instructions on how to bake a chocolate cake, including tips and tricks for making it moist and fluffy.</p>
<p><strong>7. Create personalized workout and diet plans</strong></p>
<p>New to the gym? Chat-GPT is your free personal trainer. Instantly create a workout plan tailored to your needs.</p>
<p>Example: You're looking to create a personalized workout and diet plan for a client who wants to lose weight and build muscle. Design a comprehensive plan that will help them reach their fitness goals while taking into account their current fitness level, dietary preferences, and any health conditions they may have. Provide them with actionable steps they can take to achieve their goals and maintain a healthy lifestyle long-term.</p>
<p><strong>In summary</strong>, ChatGPT is an advanced language model created by OpenAI that is designed to process natural language and generate human-like responses. It is a powerful tool that can be used for a wide range of purposes, including customer support, content creation, language translation, and more. In this article, we explore over 50+ different use cases for ChatGPT that can help businesses and individuals get ahead in their respective fields.</p>
<p>Overall, ChatGPT is a versatile and powerful tool that can be used in countless ways. Whether you're a business looking to automate your customer support processes or an individual looking to improve your language skills, ChatGPT has something to offer. By exploring the many different use cases for ChatGPT, you can unlock its full potential and get ahead in your respective field.</p>
<p><a target="_blank" href="https://twitter.com/jaencarrodine/status/1613922728179802113/photo/1">  
</a></p>
]]></content:encoded></item><item><title><![CDATA[Learning JavaScript Fundamentals Before Choosing a Front-End Framework]]></title><description><![CDATA[Feeling overwhelmed by the multitude of front-end frameworks available for your JavaScript project? Fear not, as many of them offer similar functionality with distinct approaches. While React, Angular, and Vue, the most popular options, differ in the...]]></description><link>https://frontendgenius.com/learning-javascript-fundamentals-before-choosing-a-front-end-framework</link><guid isPermaLink="true">https://frontendgenius.com/learning-javascript-fundamentals-before-choosing-a-front-end-framework</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[Angular]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[framework]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Tue, 28 Mar 2023 05:08:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679132928854/c70ff313-3cbb-4394-b77a-72ffcb1bf372.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Feeling overwhelmed by the multitude of front-end frameworks available for your JavaScript project? Fear not, as many of them offer similar functionality with distinct approaches. While React, Angular, and Vue, the most popular options, differ in their syntax and development processes, their fundamental concepts remain comparable.</p>
<p>Before selecting a front-end framework, it is essential to prioritize mastering the fundamental principles of JavaScript. Simply understanding the basics of variables, arrays, and functions is insufficient. It is critical to delve deeper and acquire proficiency in concepts such as ES6, promises, HTTP requests, and high-order array methods such as map, filter, and reduce.</p>
<p>A common mistake that people make is rushing into using frameworks without fully understanding them, which can lead to complications. For instance, they may struggle to differentiate between what belongs to the framework and what is part of JavaScript. A prime example is the map method, a high-order array method in JavaScript that is utilized in React to iterate over an array and create a list in JSX. Individuals who hastily adopt React may mistakenly assume that map is exclusive to React, when in fact it is a standard feature of JavaScript.</p>
<p>Several YouTubers tend to sensationalize the process of choosing a framework, but such hype is unnecessary. The key factor to focus on is understanding JavaScript. There are numerous online courses available, such as "<a target="_blank" href="https://www.udemy.com/course/modern-javascript-from-the-beginning/">Modern JavaScript from the Beginning</a>" on Udemy, that offers a comprehensive introduction to JavaScript basics.</p>
<p>For a more in-depth exploration of JavaScript, <a target="_blank" href="https://frontendmasters.com/teachers/kyle-simpson/">Kyle Simpson</a>'s courses on Frontend Masters are highly recommended. Additionally, practicing algorithms is an excellent way to enhance your skills and develop proficiency in diverse problem-solving techniques.</p>
<p>Many websites offer algorithm challenges, like <a target="_blank" href="https://www.freecodecamp.org/">FreeCodeCamp</a> and <a target="_blank" href="https://codesignal.com/">CodeFights</a>. When it comes to front-end frameworks, two crucial concepts are components and state. Components are encapsulated pieces of the user interface, like a navbar or search form, while the state is the current status of the application. Understanding these concepts is vital when working with front-end frameworks.</p>
<h2 id="heading-the-importance-of-javascript-fundamentals">The Importance of JavaScript Fundamentals</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679132956769/c9fab89c-8ada-497b-ab55-7f266053526e.jpeg" alt class="image--center mx-auto" /></p>
<p>JavaScript is a programming language that plays a significant role in creating dynamic and interactive web pages. For front-end developers responsible for developing the parts of websites that users directly interact with, JavaScript is an essential tool.</p>
<p>Understanding the fundamental concepts of JavaScript is critical for several reasons. Firstly, it enables developers to write more efficient and effective code. A strong grasp of concepts like data types, variables, functions, and loops helps developers create code that is easier to read, modular, and maintainable.</p>
<p>Furthermore, a strong understanding of JavaScript fundamentals is essential for grasping more advanced concepts like front-end frameworks. Working with frameworks such as React, <a target="_blank" href="https://angular.io/">Angular</a>, and <a target="_blank" href="https://vuejs.org/">Vue</a>, which rely heavily on JavaScript concepts, can be challenging without a solid understanding of the basics. By mastering JavaScript fundamentals, developers can better understand the workings of these frameworks and build more complex and robust applications.</p>
<p>Some specific JavaScript fundamentals that are important for front-end development include:</p>
<ul>
<li><p>Data types: Understanding data types like strings, numbers, and booleans is important for writing code that can handle user input and display information to users.</p>
</li>
<li><p>Variables: Variables allow developers to store and manipulate data in their code. Understanding how to declare, assign, and use variables is crucial for writing effective JavaScript.</p>
</li>
<li><p>Functions: Functions are reusable blocks of code that can perform specific tasks. Understanding how to define and call functions is important for writing modular code that can be easily reused.</p>
</li>
<li><p>Loops: Loops allow developers to repeat a block of code multiple times. Understanding how to write loops is important for efficiently performing repetitive tasks.</p>
</li>
</ul>
<p>Beyond front-end development, understanding JavaScript fundamentals can be useful in a variety of other contexts. For example, JavaScript is also commonly used in server-side development, game development, and even in Internet of Things (IoT) devices.</p>
<h2 id="heading-common-front-end-frameworks-and-their-dependencies">Common Front-End Frameworks and Their Dependencies</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679132971846/d1d8c41f-baf0-41ee-8364-ff90378fee65.jpeg" alt class="image--center mx-auto" /></p>
<p>React, Angular, and Vue are among the most popular front-end frameworks used by developers today. These frameworks have distinct features and advantages, but all depend heavily on JavaScript to operate.</p>
<p>For instance, <a target="_blank" href="https://react.dev/">React</a> is a component-based framework that enables developers to create user interfaces using reusable components. These components are written in JavaScript, making it crucial to have a good grasp of JavaScript fundamentals such as functions and variables to write efficient React code.</p>
<p><a target="_blank" href="https://angular.io/">Angular</a>, on the other hand, is a full-featured framework that provides tools for everything from data binding to routing and animations. Like React, Angular is built on JavaScript and requires a solid understanding of JavaScript concepts to be used effectively.</p>
<p><a target="_blank" href="https://vuejs.org/">Vue</a> is a newer framework that has gained popularity in recent years due to its ease of use and flexibility. Like React and Angular, Vue relies heavily on JavaScript, and knowledge of JavaScript fundamentals is key to using Vue effectively.</p>
<p>For example, in React, the use of the <code>useState</code> hook requires an understanding of how to work with JavaScript objects and how to update state values using the setState function. In Angular, knowledge of JavaScript arrays and loops is important for working with the framework's built-in ngFor directive, which allows developers to easily iterate over lists of data.</p>
<p>In Vue, understanding JavaScript concepts like functions and variables is important for working with the framework's reactivity system, which allows components to automatically update when their underlying data changes.</p>
<p>Overall, a solid understanding of JavaScript fundamentals is crucial for effectively using front-end frameworks like React, Angular, and Vue. By understanding how these frameworks rely on JavaScript and how JavaScript concepts can be applied in specific contexts, developers can write more efficient and effective code and create better user experiences for their users.</p>
<h2 id="heading-learning-javascript-fundamentals">Learning JavaScript Fundamentals</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679132985513/c8dc11ed-100d-4549-abfe-44a2b8a2c332.jpeg" alt class="image--center mx-auto" /></p>
<p>One of the best ways to learn JavaScript is by taking an online course. There are many excellent resources available, such as <a target="_blank" href="https://www.codecademy.com/">Codecademy</a>, <a target="_blank" href="https://www.udemy.com/">Udemy</a>, and <a target="_blank" href="https://www.pluralsight.com/">Pluralsight</a>, that offer comprehensive courses on JavaScript fundamentals. These courses often include interactive lessons and exercises that allow learners to practice and apply what they've learned.</p>
<p>In addition to courses, there are also many tutorials and books available that can help learners solidify their understanding of JavaScript fundamentals. Websites like MDN Web Docs and <a target="_blank" href="https://www.w3schools.com/">W3Schools</a> offer in-depth tutorials on a wide range of JavaScript concepts, and there are many books available on the topic, such as "JavaScript: The Definitive Guide" by David Flanagan and "<a target="_blank" href="https://eloquentjavascript.net/">Eloquent JavaScript</a>" by Marijn Haverbeke.</p>
<p>However, it's important to note that while these resources can be helpful, the most effective way to learn JavaScript fundamentals is through hands-on practice and experimentation. By building projects and working on exercises, learners can apply what they've learned and gain a deeper understanding of how JavaScript works.</p>
<p>Some specific examples of projects or exercises that can help readers solidify their understanding of JavaScript fundamentals include:</p>
<ol>
<li><p>Building a simple to-do list app: This project allows learners to practice working with variables, functions, and DOM manipulation.</p>
</li>
<li><p>Creating a weather app: This project involves working with APIs, manipulating data, and using conditional statements.</p>
</li>
<li><p>Implementing a basic game: This project allows learners to practice working with loops, arrays, and object-oriented programming concepts.</p>
</li>
<li><p>Solving coding challenges: Websites like Codewars and HackerRank offer coding challenges that allow learners to practice their JavaScript skills and see how they compare to other developers.</p>
</li>
</ol>
<p>Learning JavaScript fundamentals is an important first step for anyone looking to become a front-end developer. By taking courses, reading tutorials and books, and practicing hands-on exercises and projects, learners can gain a solid understanding of JavaScript and become more effective developers.</p>
<p>In summary, having a strong understanding of JavaScript fundamentals is essential for front-end development and working with popular frameworks like React, Angular, and Vue. Concepts such as data types, variables, functions, and loops are necessary for writing efficient and effective code and providing a great user experience.</p>
<p>To solidify understanding, hands-on practice and experimentation are crucial. There are many resources available to help learners get started, including online courses, tutorials, books, and coding challenges.</p>
<p>Readers need to prioritize learning JavaScript fundamentals before jumping into a specific framework. By doing so, they will have a better understanding of how the framework works and be able to write more efficient code. Ultimately, understanding JavaScript fundamentals is a foundational skill for front-end developers and is crucial for building successful web applications.</p>
]]></content:encoded></item><item><title><![CDATA[Top 8 Reasons Why You Should Learn HTML, CSS, and JavaScript]]></title><description><![CDATA[Welcome to our article on the top 8 reasons why you should learn HTML, CSS, and JavaScript. In today's digital age, web development is an essential skill to have. The internet has become an integral part of our lives, and businesses rely heavily on i...]]></description><link>https://frontendgenius.com/top-8-reasons-why-you-should-learn-html-css-and-javascript</link><guid isPermaLink="true">https://frontendgenius.com/top-8-reasons-why-you-should-learn-html-css-and-javascript</guid><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[learning]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sun, 19 Mar 2023 05:26:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678696696039/0d6ed0fd-165a-440a-a17a-7a1e0b75b6b6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to our article on the top 8 reasons why you should learn HTML, CSS, and JavaScript. In today's digital age, web development is an essential skill to have. The internet has become an integral part of our lives, and businesses rely heavily on it for their operations. As a result, the demand for web developers is on the rise, making it an excellent career path with a promising future. Whether you're interested in building your own website or pursuing a career in web development, learning HTML, CSS, and JavaScript is a great place to start. In this article, we'll explore the top 8 reasons why you should learn these essential web development skills.</p>
<h2 id="heading-reason-1-web-development-is-a-high-demand-field"><strong>Reason 1: Web Development is a High-Demand Field</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697482609/08cbe4eb-08ba-41a1-aa77-87c33622908c.png" alt class="image--center mx-auto" /></p>
<p>In today's digital age, businesses rely heavily on the internet for their operations. As a result, the demand for web developers is on the rise. According to the Bureau of Labor Statistics, employment of web developers is projected to grow 13 percent from 2018 to 2028, much faster than the average for all occupations. This growth is driven by the increasing popularity of e-commerce and mobile devices, which require websites that are optimized for viewing on a variety of devices.</p>
<p>Furthermore, web development is a field with a diverse range of job opportunities. From front-end developers who focus on the design and user experience of a website, to back-end developers who create the server-side logic and database interactions, there are many areas in which you can specialize. Additionally, web development is a skill that is in demand across many industries, from tech startups to healthcare organizations, offering a variety of career paths.</p>
<p>Learning HTML, CSS, and JavaScript is the foundation of web development and can open up many doors for career opportunities. By developing these essential skills, you can position yourself to take advantage of the many job opportunities available in this high-demand field.</p>
<h2 id="heading-reason-2-html-css-and-javascript-are-the-building-blocks-of-the-web"><strong>Reason 2: HTML, CSS, and JavaScript are the Building Blocks of the Web</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697492744/d15746d9-b17c-4811-afa6-3da538f1e297.png" alt class="image--center mx-auto" /></p>
<p>HTML, CSS, and JavaScript are the three essential languages that form the foundation of the web. HTML is the markup language used to structure and display content on a website. CSS is used to style and lay out the content, making it visually appealing and easy to navigate. JavaScript, on the other hand, adds interactivity and dynamic functionality to a website.</p>
<p>For example, consider a simple web page that displays a blog post. HTML is used to structure the content of the blog post, including headings, paragraphs, and images. CSS is used to style the content, such as setting the font size and color and arranging the elements on the page. JavaScript can be used to add features like a search bar, interactive buttons, or a carousel for displaying multiple images.</p>
<h2 id="heading-reason-3-you-can-build-your-own-website-or-blog"><strong>Reason 3: You Can Build Your Own Website or Blog</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697506469/a8f7bd33-f878-498e-b616-f30414074922.png" alt class="image--center mx-auto" /></p>
<p>One of the most rewarding aspects of learning HTML, CSS, and JavaScript is the ability to build your own website or blog. Whether you want to share your thoughts with the world, promote your business, or showcase your portfolio, creating your own website is an excellent way to do so.</p>
<h2 id="heading-reason-4-enhance-your-job-prospects-and-earning-potential"><strong>Reason 4: Enhance Your Job Prospects and Earning Potential</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697517752/b8c582bc-ee09-446d-aa32-d7d3ea84fcd4.png" alt class="image--center mx-auto" /></p>
<p>As we mentioned earlier, web development is a high-demand field with excellent career prospects. Learning HTML, CSS, and JavaScript can enhance your job prospects and earning potential. With these skills, you can pursue a variety of career paths, including web development, front-end developer, UX designer, and more.</p>
<h2 id="heading-reason-5-create-user-friendly-websites-and-improve-user-experience"><strong>Reason 5: Create User-Friendly Websites and Improve User Experience</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697527779/ce2ff9e5-c944-4d97-be3e-cc8635d2f3b2.png" alt class="image--center mx-auto" /></p>
<p>With HTML, CSS, and JavaScript, you can create websites that are both visually appealing and user-friendly. By implementing responsive design, you can ensure your website looks great on any device. You can also add features like dropdown menus, image carousels, and more to improve user experience.</p>
<h2 id="heading-reason-6-add-interactive-and-dynamic-elements-to-your-website">Reason 6: Add Interactive and Dynamic Elements to Your Website</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697539289/d20ff446-e9bd-4f40-accf-9737e815b554.png" alt class="image--center mx-auto" /></p>
<p>One of the most exciting aspects of web development is the ability to add interactive and dynamic elements to a website. JavaScript, in particular, is a powerful language for creating these types of features. By learning JavaScript, you can bring your website to life and create a more engaging user experience.</p>
<p>For example, you can use JavaScript to add animations, such as a rotating banner or a pop-up window that appears when a user clicks a button. You can also use JavaScript to create interactive forms, such as a survey or a contact form that responds to user input. Additionally, you can use JavaScript to create games or other interactive elements, such as a map that allows users to explore different locations.</p>
<h2 id="heading-reason-7-build-mobile-friendly-websites"><strong>Reason 7: Build Mobile-Friendly Websites</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697552780/c3150710-2064-4ebc-a930-8df882935aba.png" alt class="image--center mx-auto" /></p>
<p>As more and more people access the internet on their mobile devices, building mobile-friendly websites is essential. With HTML, CSS, and JavaScript, you can create responsive websites that adapt to different screen sizes and devices. This ensures your website is accessible to all users, regardless of the device they're using.</p>
<h2 id="heading-reason-8-stay-up-to-date-with-the-latest-web-development-trends"><strong>Reason 8: Stay Up-to-Date with the Latest Web Development Trends</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678697562545/748d5c06-9623-482c-a7c5-60bc8825070b.png" alt class="image--center mx-auto" /></p>
<p>Web development is a rapidly evolving field, with new technologies and trends emerging on a regular basis. By learning HTML, CSS, and JavaScript, you'll be able to stay up-to-date with the latest web development trends and advancements.</p>
<p>For example, in recent years, there has been a significant shift towards mobile-first design, where websites are designed to be mobile-friendly and responsive. Additionally, there has been a rise in the use of front-end frameworks like React, Angular, and Vue, which simplify the process of building complex web applications. By staying up-to-date with these trends and technologies, you'll be able to create modern and relevant websites that meet the needs of today's users.</p>
<p>So, guys, we have highlighted the top 8 reasons why you should learn HTML, CSS, and JavaScript for web development also we have explained how web development is a high-demand field, how these three languages are the building blocks of the web, and how they allow you to create responsive and mobile-friendly websites.</p>
<p>We have also discussed how learning web development can open up new career opportunities and help you become a more well-rounded developer. Furthermore, we have highlighted the importance of adding interactive and dynamic elements to your website using JavaScript and staying up-to-date with the latest web development trends. By learning HTML, CSS, and JavaScript, you'll be equipped with the skills and knowledge you need to succeed in the exciting and rapidly-evolving field of web development.</p>
<p>See you next time !!</p>
<p>Stay tuned { Happy Coding }</p>
]]></content:encoded></item><item><title><![CDATA[10 Tips to Master HTML CSS and JavaScript in Record Time]]></title><description><![CDATA[In today's digital age, web development is a critical skill for individuals and businesses alike. Three core technologies make up the foundation of the web: HTML, CSS, and JavaScript. Mastery of these three languages can open up a world of possibilit...]]></description><link>https://frontendgenius.com/10-tips-to-master-html-css-and-javascript-in-record-time</link><guid isPermaLink="true">https://frontendgenius.com/10-tips-to-master-html-css-and-javascript-in-record-time</guid><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Mon, 13 Mar 2023 07:37:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530042751/e96bf54b-35b0-4eff-852d-d86e842aea71.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's digital age, web development is a critical skill for individuals and businesses alike. Three core technologies make up the foundation of the web: HTML, CSS, and JavaScript. Mastery of these three languages can open up a world of possibilities for creating and designing websites. However, learning them can be a daunting task, especially for beginners. In this article, we provide ten tips to help you master HTML, CSS, and JavaScript in record time.</p>
<h2 id="heading-start-with-the-basics"><strong>Start with the Basics</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530136554/0775bf6a-61f9-4881-a7e5-47356f5fab70.png" alt class="image--center mx-auto" /></p>
<p>When learning any new language, it's important to start with the basics. This applies to HTML, CSS, and JavaScript as well. Begin by learning the fundamental syntax, concepts, and rules of each language. Understanding the basics will enable you to build a strong foundation, which will help you to tackle more complex topics in the future.</p>
<p>For example, when learning HTML, start with understanding the basic tags such as <code>&lt;html&gt;</code>, <code>&lt;head&gt;</code>, <code>&lt;title&gt;</code>, <code>&lt;body&gt;</code>, and <code>&lt;p&gt;</code>. Learn how to create headings, paragraphs, and lists. Understand how to create hyperlinks and images. Similarly, when learning CSS, start with learning how to change the color, font, and size of the text. Learn how to style headings, paragraphs, and lists. Understand how to add borders, margins, and padding. When learning JavaScript, start with learning basic concepts such as variables, data types, and functions. Understand how to write simple programs that interact with users.</p>
<h2 id="heading-follow-a-structured-learning-plan"><strong>Follow a Structured Learning Plan</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530154357/ff902a7a-05d1-4fd5-b94a-41f160844cc2.png" alt class="image--center mx-auto" /></p>
<p>Learning web development can be overwhelming, especially when you don't know where to start. A structured learning plan can help you stay on track and achieve your goals faster. Start by setting clear objectives and goals for what you want to accomplish. Break down the topics you need to learn into smaller, manageable chunks, and focus on them one at a time.</p>
<p>For example, if your goal is to learn HTML, CSS, and JavaScript, create a structured learning plan that includes specific objectives for each language. Focus on one language at a time, and break it down into smaller topics such as syntax, structure, and common tags. Use online resources such as tutorials, videos, and online courses to help guide your learning.</p>
<h2 id="heading-practice-practice-practice"><strong>Practice, Practice, Practice</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530171416/588406d9-bf70-423f-a167-d2de2ef68d10.png" alt class="image--center mx-auto" /></p>
<p>One of the best ways to master HTML, CSS, and JavaScript is through practice. Practice coding regularly, even if it's just for a few minutes each day. Consistency is key when it comes to learning anything new, and web development is no exception.</p>
<p>For example, when learning HTML, practice creating basic web pages that include headings, paragraphs, and lists. Experiment with adding images and hyperlinks. When learning CSS, practice styling web pages with different fonts, colors, and layouts. Experiment with different border styles, margin, and padding. When learning JavaScript, practice writing simple programs that interact with users. Experiment with different data types, operators, and functions.</p>
<h2 id="heading-create-projects"><strong>Create Projects</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530208802/cda1f71e-e7f6-4b12-97b0-8eebe6691905.png" alt class="image--center mx-auto" /></p>
<p>Creating projects is an excellent way to apply what you've learned and gain practical experience. Start by building small projects and gradually increase their complexity as you gain more confidence. Projects will help you to identify areas where you need improvement, and they will also give you a sense of accomplishment.</p>
<p>For example, when learning HTML, create a simple web page with a navigation menu, header, and footer. Add some images and links to other pages. As you progress, you could create a more complex web page with multiple sections and a responsive layout that adjusts to different screen sizes.</p>
<p>When learning CSS, you could create a project that focuses on a particular style, such as creating a website with a retro theme. Experiment with different fonts, colors, and layouts to achieve the desired effect. You could also create a project that focuses on responsive design, where the layout of the website adjusts to different screen sizes.</p>
<p>When learning JavaScript, you could create a project that focuses on interactivity, such as a simple game or quiz. Use your knowledge of variables, data types, and functions to create a program that interacts with the user. You could also create a project that integrates with APIs to display data from external sources.</p>
<p>The possibilities are endless when it comes to creating projects. Be creative and have fun with it. Not only will you gain valuable experience, but you'll also have something to showcase to potential employers or clients.</p>
<h2 id="heading-work-on-real-world-applications"><strong>Work on Real-World Applications</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530219871/d0f17564-460e-4298-9e50-f6c79db759c0.png" alt class="image--center mx-auto" /></p>
<p>Working on real-world applications will help you to understand how to solve practical problems using HTML, CSS, and JavaScript. You could work on a personal project or contribute to an open-source project. This will give you the opportunity to work with other developers and learn from their experience.</p>
<p>For example, you could contribute to a project like Bootstrap, a popular front-end framework that is used by millions of developers. Contributing to a project like this will give you the opportunity to work with other developers and learn how to solve practical problems using HTML, CSS, and JavaScript.</p>
<h2 id="heading-learn-from-other-developers"><strong>Learn from Other Developers</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530235281/b916ee2b-79e4-4f04-ac79-a499e849fec4.png" alt class="image--center mx-auto" /></p>
<p>Learning from other developers is an excellent way to improve your skills. You could attend conferences, workshops, or meetups to learn from experienced developers. You could also read blogs and watch videos to learn about new techniques and tools.</p>
<p>For example, you could attend a conference like Frontend Love, a popular conference that focuses on front-end development. You could also watch videos on platforms like YouTube or Udemy to learn about new techniques and tools.</p>
<h2 id="heading-participate-in-online-communities"><strong>Participate in Online Communities</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530252912/b715d1b1-357e-4dd4-a860-21f09566af80.png" alt class="image--center mx-auto" /></p>
<p>Participating in online communities is a great way to connect with other developers and learn from their experiences. You could join online communities like Reddit or Stack Overflow to ask questions and get feedback on your projects.</p>
<p>For example, you could join the r/Frontend community on Reddit to ask questions and get feedback on your projects. You could also participate in discussions on Stack Overflow to learn from experienced developers.</p>
<h2 id="heading-use-online-resources"><strong>Use Online Resources</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530265576/00c785bf-fcf7-420c-b0b4-d41a8336f725.png" alt class="image--center mx-auto" /></p>
<p>There are a plethora of online resources available to help you learn HTML, CSS, and JavaScript. You could use online courses, tutorials, blogs, or videos to learn the basics and advanced concepts. Online resources are often free or affordable, making them accessible to anyone with an internet connection.</p>
<p>For example, you could use Codecademy, a popular platform that offers interactive courses on HTML, CSS, and JavaScript. You could also read blogs like CSS-Tricks or A List Apart to learn about new techniques and best practices.</p>
<h2 id="heading-stay-updated"><strong>Stay Updated</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530288976/ebbe0e78-8021-473c-8057-c6bb7a01639f.png" alt class="image--center mx-auto" /></p>
<p>HTML, CSS, and JavaScript are constantly evolving, with new techniques and best practices being developed every day. It's important to stay updated with the latest trends and developments in front-end development to ensure that you're using the most effective and efficient techniques.</p>
<p>For example, you could subscribe to newsletters like CSS Weekly or JavaScript Weekly to stay updated with the latest trends and developments. You could also follow front-end developers on social media platforms like Twitter to learn about new tools and techniques.</p>
<h2 id="heading-stay-motivated"><strong>Stay Motivated</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678530301916/c2088b90-bba0-4cfe-8da1-141b90f41e4a.png" alt class="image--center mx-auto" /></p>
<p>Learning HTML, CSS, and JavaScript can be challenging at times, and it's easy to lose motivation. It's important to stay motivated and remember why you started learning in the first place. Set goals for yourself, celebrate your progress and remember that learning is a journey, not a destination.</p>
<p>For example, you could set a goal to build a fully functional website using HTML, CSS, and JavaScript within a certain timeframe. Celebrate your progress by sharing your work with others and getting feedback. Remember that every small step counts, and never give up on your dreams.</p>
<p>By following these tips, you'll be well on your way to mastering HTML, CSS, and JavaScript in record time. Remember to use online resources, stay updated, stay motivated, and most importantly, <mark>have fun!</mark></p>
<p><strong>Thanks for reading !!!</strong></p>
]]></content:encoded></item><item><title><![CDATA[Enhancing Web App User Experience: Making Modals Behave Like Mobile Apps ( ReactJs )]]></title><description><![CDATA[As web applications continue to evolve, the lines between web and mobile apps are becoming increasingly blurred. One area where this is particularly noticeable is in the way that users expect the back button to behave. In a mobile app, when a user pr...]]></description><link>https://frontendgenius.com/enhancing-web-app-user-experience-making-modals-behave-like-mobile-apps-reactjs</link><guid isPermaLink="true">https://frontendgenius.com/enhancing-web-app-user-experience-making-modals-behave-like-mobile-apps-reactjs</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[React]]></category><category><![CDATA[modal]]></category><category><![CDATA[user experience]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sat, 11 Mar 2023 06:40:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678268986970/463bc942-8ee1-46d6-bb98-7d70f7ef03e9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As web applications continue to evolve, the lines between web and mobile apps are becoming increasingly blurred. One area where this is particularly noticeable is in the way that users expect the back button to behave. In a mobile app, when a user presses the back button, they expect any pop-up or modal windows to close, rather than being taken back to the previous page. However, this behavior is not always consistent in web apps.</p>
<p>To create a more seamless experience for users, web developers can implement certain techniques to make web apps behave more like mobile apps. In this article, we will explore two approaches to achieving this: creating helper functions and using a hash in the URL.</p>
<h2 id="heading-helper-functions">Helper Functions</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678269035813/98dccbe0-488c-4abd-9459-cbb4c7150ec2.png" alt class="image--center mx-auto" /></p>
<p>One way to make a web app behave more like a mobile app is to create helper functions that allow you to override the default behavior of the back button when a modal window is open. With this approach, you can ensure that when a user presses the back button, they are taken back to the previous state of the modal window, rather than being taken back to the previous page.</p>
<p>To achieve this, you can create two helper functions: one to neutralize the back button when a modal window is open, and another to revive it when the modal window is closed.</p>
<p>The neutralizeBack function should take a callback function as its argument. This callback function will be executed when the back button is pressed while the modal window is open. Here's an example implementation of the neutralizeBack function</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> neutralizeBack = <span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> {
  <span class="hljs-built_in">window</span>.history.pushState(<span class="hljs-literal">null</span>, <span class="hljs-string">""</span>, <span class="hljs-built_in">window</span>.location.href);
  <span class="hljs-built_in">window</span>.onpopstate = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">window</span>.history.pushState(<span class="hljs-literal">null</span>, <span class="hljs-string">""</span>, <span class="hljs-built_in">window</span>.location.href);
    callback();
  };
};
</code></pre>
<p>The revivalBack function, on the other hand, should simply restore the default behavior of the back button. Here's an example implementation of the revivalBack function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> revivalBack = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">window</span>.onpopstate = <span class="hljs-literal">undefined</span>;
  <span class="hljs-built_in">window</span>.history.back();
};
</code></pre>
<p>To use these functions, you can simply call neutralizeBack with your desired callback function when you open a modal window, and call revivalBack when you close the modal window. Here's an example implementation:</p>
<pre><code class="lang-javascript">handleOpenModal = <span class="hljs-function">() =&gt;</span>
  setState(
    { <span class="hljs-attr">modalOpen</span>: <span class="hljs-literal">true</span> },
    <span class="hljs-function">() =&gt;</span> neutralizeBack(<span class="hljs-built_in">this</span>.handleCloseModal)
  );

handleCloseModal = <span class="hljs-function">() =&gt;</span>
  setState(
    { <span class="hljs-attr">modalOpen</span>: <span class="hljs-literal">false</span> },
    revivalBack
 );
</code></pre>
<h2 id="heading-using-a-hash-in-the-url">Using a Hash in the URL</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678269083278/e699aa27-64ba-44d2-a230-2f7b6ac5a101.png" alt class="image--center mx-auto" /></p>
<p>Another approach you can take is to use a hash in your URL to indicate the state of the modal window. A hash is a URL segment that starts with a hashtag (#). Navigating between different hashes in the URL does not trigger a page reload, but still adds an entry to the browser's history, allowing the back button to be used to close modal windows.</p>
<p>A hash is a URL segment that begins with a hashtag (#). Navigating between different hashes in the URL does not cause a page to reload, but still adds an entry to the browser's history, which allows the back button to close modal windows. This approach is relatively simple to implement and can provide a more intuitive user experience.</p>
<p>To implement this approach, you can create a custom hook that toggles the state of the modal window based on the URL hash. In the example implementation below, we create a custom hook called <code>useHashRouteToggle</code> that takes a <code>modalHash</code> parameter to define the hash used for the modal window:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useHashRouteToggle</span>(<span class="hljs-params">modalHash</span>) </span>{
  <span class="hljs-keyword">const</span> [isOpen, toggleOpen] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> toggleActive = <span class="hljs-function">(<span class="hljs-params">open</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (open) {
      <span class="hljs-built_in">window</span>.location.assign(modalHash);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">window</span>.location.replace(<span class="hljs-string">'#'</span>);
    }
  }

  useEffect(<span class="hljs-function">() =&gt;</span> { 
    <span class="hljs-keyword">const</span> handleOnHashChange = <span class="hljs-function">() =&gt;</span> {  
      <span class="hljs-keyword">const</span> isHashMatch = <span class="hljs-built_in">window</span>.location.hash === modalHash;   
      toggleOpen(isHashMatch);  
    };  

    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'hashchange'</span>, handleOnHashChange);  

    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">'hashchange'</span>, handleOnHashChange);  
  }, [modalHash]);

  <span class="hljs-keyword">return</span> [isActive, toggleActive];
}
</code></pre>
<p>With this custom hook, you can simply call toggleActive with the desired state of the modal window (true to show the modal, false to hide it).</p>
<p>The <code>useHashRouteToggle</code> hook returns an array with two items: <code>isOpen</code>, which is a boolean value indicating whether the modal window is currently open, and <code>toggleActive</code>, which is a function that toggles the state of the modal window. When <code>toggleActive</code> is called with <code>true</code>, it updates the URL to include the <code>modalHash</code> parameter. When <code>toggleActive</code> is called with <code>false</code>, it replaces the hash in the URL with an empty string.</p>
<p>The <code>useEffect</code> hook sets up an event listener for the <code>hashchange</code> event, which is triggered whenever the hash in the URL changes. If the current hash matches the <code>modalHash</code> parameter, the hook updates the <code>isOpen</code> state to <code>true</code>. If the current hash does not match the <code>modalHash</code> parameter, the hook updates the <code>isOpen</code> state to <code>false</code>.</p>
<p>Using a hash in the URL can be an effective way to handle modal windows in a web app. By creating a custom hook to toggle the state of the modal window based on the URL hash, you can provide a more consistent and intuitive user experience.</p>
<p>Here we have discussed how the behavior of the back button is different in mobile apps and web apps, and how web app developers can make their apps behave more like mobile apps in this regard. Two approaches are discussed: creating helper functions to override the default behavior of the back button when a modal window is open, and using a hash in the URL by creating a custom hook in react to indicate the state of the modal window. Example implementations are provided for both approaches.</p>
<p><strong>Stay tuned don't forget to subscribe to my newsletter !!!</strong></p>
]]></content:encoded></item><item><title><![CDATA[7 Steps to Create a Responsive Website]]></title><description><![CDATA[As more and more people access the internet through mobile devices, having a responsive website is crucial for businesses and individuals. A responsive website is one that can adapt to different screen sizes and devices, ensuring that users have a se...]]></description><link>https://frontendgenius.com/7-steps-to-create-a-responsive-website</link><guid isPermaLink="true">https://frontendgenius.com/7-steps-to-create-a-responsive-website</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[media queries]]></category><category><![CDATA[CSS Grid]]></category><category><![CDATA[mobile first]]></category><category><![CDATA[How to Create a Responsive Website]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Wed, 08 Mar 2023 07:03:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678001140641/7795a776-ae1d-4fd1-88d9-b124772a309f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As more and more people access the internet through mobile devices, having a responsive website is crucial for businesses and individuals. A responsive website is one that can adapt to different screen sizes and devices, ensuring that users have a seamless experience no matter what device they use. In this article, we will guide you through the 7 steps to create a responsive website.</p>
<p>A responsive website is one that can change its layout to fit different screen sizes, so it looks good on all devices - from desktop computers to smartphones.</p>
<h2 id="heading-plan-and-define-your-goals"><strong>Plan and Define Your Goals</strong></h2>
<p>Before you start building your website, think about your goals and your audience. Who are your visitors, and what do they want from your website? What do you want to achieve with your website? Once you have a clear idea of what you want, you can plan your website's structure and content.</p>
<p>For example, if you're building a website for a restaurant, you might want to include a menu, photos of the food, and information about the restaurant's location and opening hours.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677999571485/0d6c068a-a4c4-45e7-8030-ae180efa0175.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-choose-a-responsive-framework"><strong>Choose a Responsive Framework</strong></h2>
<p>To make your website responsive, you'll need to use a responsive framework. A framework is a pre-built set of code and design elements that you can use as a starting point for your website. There are many responsive frameworks available, such as Bootstrap and Foundation. Choose one that fits your needs and experience level.</p>
<p>For example, if you're new to web design, you might choose Bootstrap because it's easy to use and has lots of documentation.</p>
<p><a target="_blank" href="https://getbootstrap.com/">Build fast, responsive sites with Bootstrap</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678000285775/82c10d51-0ede-4ed0-94bf-1c9c062200fe.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-optimize-your-images"><strong>Optimize Your Images</strong></h2>
<p>Images are an important part of any website, but they can also slow down your site if they're not optimized. Make sure your images are the appropriate size and resolution for the web and compress them to reduce their file size without sacrificing quality. This will help your site load quickly on all devices.</p>
<p>For example, if you have a photo of a dish on your restaurant website, you can reduce the file size by compressing it and cropping out any unnecessary background.</p>
<p><a target="_blank" href="https://www.reduceimages.com/">Resize an Image</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678000487458/fac432dd-0a72-4713-a3d0-744f1c83581f.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-use-responsive-design-techniques"><strong>Use Responsive Design Techniques</strong></h2>
<p>To ensure that your website looks great on all devices, use responsive design techniques such as fluid grids, flexible images, and media queries. These techniques allow your website to adapt to different screen sizes and orientations, ensuring that users have a seamless experience no matter how they access your site.</p>
<p>For example, if you have a two-column layout on your desktop site, you might change it to a single column on mobile devices to make it easier to read.</p>
<p><a target="_blank" href="https://getbootstrap.com/docs/5.3/layout/grid/#example">Grid system</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678000636516/99b84ce1-26ea-4993-ab35-68fceaac94b7.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-test-your-site-on-multiple-devices"><strong>Test Your Site on Multiple Devices</strong></h2>
<p>Before launching your site, it's crucial to test it on multiple devices and screen sizes. This will help you identify any issues or inconsistencies and ensure that your site looks and functions as intended on all devices. You can use online tools such as BrowserStack or Adobe Device Preview to test your site on different devices.</p>
<p>For example, you can test your restaurant website on an iPhone, Android phone, and tablet to make sure it looks good on all devices.</p>
<h3 id="heading-how-to-test-website-on-multiple-devices">How to test website on multiple devices?</h3>
<ol>
<li><p>Open a website.</p>
</li>
<li><p>Right-click on the page and click on Inspect.</p>
</li>
<li><p>The Chrome DevTools window will open. ...</p>
</li>
<li><p>On the top left of the window, there are two icons. ...</p>
</li>
<li><p>The screen will change to show you what the website would look like on a mobile device.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678000800304/457b0200-0834-459b-94d7-86a32b62475e.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-optimize-your-site-for-speed"><strong>Optimize Your Site for Speed</strong></h2>
<p>Site speed is a crucial factor in user experience and search engine optimization. To ensure that your site loads quickly, optimize your code, compress your files, and use a content delivery network (CDN) to serve your site's assets from a server closer to the user. This will help your site load quickly on all devices and improve your search engine rankings.</p>
<p>For example, if your restaurant website takes too long to load, visitors may leave and go to a competitor's site instead.</p>
<p><a target="_blank" href="https://sematext.com/blog/improve-website-performance/">14 Website Speed Optimization Tips: Techniques to Improve Performance and User Experience</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678000916701/a3199bf7-af4c-430f-8f54-d913d2c5dfd7.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-continuously-monitor-and-improve-your-site"><strong>Continuously Monitor and Improve Your Site</strong></h2>
<p>Creating a responsive website is not a one-time task. It's important to continuously monitor your site's performance and make improvements as needed. Use analytics tools to track user behavior and identify areas for improvement, and regularly update your site's content to keep it fresh and engaging.</p>
<p>For example, One way to monitor your site's performance is to use analytics tools such as Google Analytics. This tool allows you to track user behavior, such as how many people are visiting your site, which pages they're visiting, and how long they're staying on each page. You can use this information to identify areas for improvement, such as pages that have a high bounce rate (where visitors leave your site after only viewing one page).</p>
<p>Another way to improve your site is to regularly update your content. This will keep your site fresh and engaging for your audience, and can also help improve your search engine rankings. You can update your site's content by adding new blog posts, updating product information, or adding new pages.</p>
<p>It's also important to stay up-to-date with the latest web design trends and technologies. As technology evolves, so do user expectations. For example, mobile devices are becoming increasingly popular, so it's important to ensure that your site is optimized for mobile viewing. By staying up-to-date with the latest trends and technologies, you can ensure that your site remains competitive and relevant.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678001039085/bef55fd9-3d64-4bc3-9dd8-857bbbef0c02.png" alt class="image--center mx-auto" /></p>
<p>In conclusion, creating a responsive website requires careful planning, attention to detail, and ongoing maintenance. By following these 7 steps, you can create a website that looks great on all devices, loads quickly, and meets the needs of your audience.</p>
]]></content:encoded></item><item><title><![CDATA[10 New JavaScript features to start using today]]></title><description><![CDATA[JavaScript is a widely used programming language in web development that continues to evolve with new features. By leveraging these features, developers can enhance their coding skills and increase productivity. In this article, we will explore eight...]]></description><link>https://frontendgenius.com/10-new-javascript-features-to-start-using-today</link><guid isPermaLink="true">https://frontendgenius.com/10-new-javascript-features-to-start-using-today</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ES6]]></category><category><![CDATA[Nullish coalescing]]></category><category><![CDATA[Optional chaining]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Fri, 03 Mar 2023 17:52:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677696346609/46becd82-ce74-46d5-85be-93b2d2958932.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript is a widely used programming language in web development that continues to evolve with new features. By leveraging these features, developers can enhance their coding skills and increase productivity. In this article, we will explore eight new features of JavaScript, along with examples of how to use them.</p>
<h2 id="heading-nullish-coalescing-operator">Nullish Coalescing Operator</h2>
<p>The Nullish Coalescing Operator (??) checks for null or undefined values and returns the first non-null or non-undefined value. This operator is more reliable than the logical OR operator (||) that can return falsy values.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">const</span> b = <span class="hljs-literal">undefined</span>;
<span class="hljs-keyword">const</span> c = <span class="hljs-string">"Hello World"</span>;
<span class="hljs-keyword">const</span> result = a ?? b ?? c; <span class="hljs-comment">// "Hello World"</span>
</code></pre>
<h2 id="heading-optional-chaining">Optional Chaining</h2>
<p>The Optional Chaining (?.) operator allows accessing nested properties without causing errors if the parent property is null or undefined.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">address</span>: {
    <span class="hljs-attr">city</span>: <span class="hljs-string">"New York"</span>,
    <span class="hljs-attr">zipCode</span>: <span class="hljs-string">"12345"</span>
  }
};
<span class="hljs-keyword">const</span> city = user.address?.city; <span class="hljs-comment">// "New York"</span>
<span class="hljs-keyword">const</span> zipCode = user.address?.zipCode; <span class="hljs-comment">// "12345"</span>
<span class="hljs-keyword">const</span> country = user.address?.country; <span class="hljs-comment">// undefined</span>
</code></pre>
<h2 id="heading-private-class-fields">Private Class Fields</h2>
<p>Private Class Fields (#) enable defining private instance variables in JavaScript classes. These fields are inaccessible from outside the class, adding a layer of data protection and creating more secure and robust code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BankAccount</span> </span>{
  #balance = <span class="hljs-number">0</span>;

  deposit(amount) {
    <span class="hljs-built_in">this</span>.#balance += amount;
  }

  withdraw(amount) {
    <span class="hljs-keyword">if</span> (amount &lt;= <span class="hljs-built_in">this</span>.#balance) {
      <span class="hljs-built_in">this</span>.#balance -= amount;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
  }
}
</code></pre>
<h2 id="heading-dynamic-import">Dynamic Import</h2>
<p>Dynamic Import enables loading modules asynchronously during runtime. This feature allows importing modules conditionally or based on user actions, improving the performance and user experience of web applications.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadModule</span>(<span class="hljs-params">moduleName</span>) </span>{
  <span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">`./modules/<span class="hljs-subst">${moduleName}</span>.js`</span>);
  <span class="hljs-built_in">module</span>.initialize();
}
</code></pre>
<h2 id="heading-bigint">BigInt</h2>
<p>BigInt is a new data type that allows working with large integers beyond the limits of the Number type. It is denoted by appending "n" to the end of an integer literal.</p>
<p>JavaScript <code>BigInt</code> variables are used to store big integer values that are too big to be represented by a normal JavaScript <code>Number</code>.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = BigInt(<span class="hljs-number">999999999999999</span>);
<span class="hljs-keyword">let</span> type = <span class="hljs-keyword">typeof</span> x; <span class="hljs-comment">// bigint</span>
</code></pre>
<h2 id="heading-promiseallsettled">Promise.allSettled()</h2>
<p><code>Promise.allSettled()</code> returns an array of all settled promises, whether resolved or rejected. This method helps in handling multiple promises concurrently and gracefully handling errors and exceptions.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> promises = [
  <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"Success"</span>),
  <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"Error"</span>)
];
<span class="hljs-built_in">Promise</span>.allSettled(promises).then(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(results);
});
</code></pre>
<p>String.prototype.matchAll()</p>
<p>String.prototype.matchAll() returns an iterator of all matches of a regular expression in a string. It enables iteration over all matches and extraction of captured groups and indices.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/[0-9]+/g</span>;
<span class="hljs-keyword">const</span> string = <span class="hljs-string">"I have 2 cats and 3 dogs"</span>;
<span class="hljs-keyword">const</span> matches = string.matchAll(regex);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> match <span class="hljs-keyword">of</span> matches) {
  <span class="hljs-built_in">console</span>.log(match);
}
</code></pre>
<h2 id="heading-logical-assignment-operators">Logical Assignment Operators</h2>
<p>Logical Assignment Operators combine logical and assignment operations, using a combination of a logical operator <code>(&amp;&amp;, ||)</code> and an assignment operator <code>(=)</code> to perform complex assignments and updates with fewer lines of code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">5</span>;
count &amp;&amp;= <span class="hljs-number">2</span>; <span class="hljs-comment">// count = 2</span>
count ||= <span class="hljs-number">7</span>; <span class="hljs-comment">// count = 2</span>
</code></pre>
<h3 id="heading-optional-catch-binding">Optional Catch Binding</h3>
<p>Optional Catch Binding is a new feature in JavaScript that allows you to omit the parameter in the catch block. This feature makes error handling more concise and efficient by reducing the amount of boilerplate code. Here's an example:</p>
<p>Without Optional Catch Binding Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// some code that may throw an error</span>
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.log(error);
}
</code></pre>
<p>With Optional Catch Binding:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// some code that may throw an error</span>
} <span class="hljs-keyword">catch</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'An error occurred'</span>);
}
</code></pre>
<p>In the second example, we don't need to specify the error parameter because we're not using it.</p>
<h2 id="heading-logical-nullish-assignment-operator">Logical Nullish Assignment Operator</h2>
<p>The Logical Nullish Assignment Operator is a new shorthand operator in JavaScript that combines the nullish coalescing operator (??) and the assignment operator (=). It assigns the value on the right-hand side to the variable on the left-hand side only if the variable is nullish (i.e., null or undefined). Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myVariable = <span class="hljs-literal">null</span>;
myVariable ??= <span class="hljs-string">'default value'</span>;

<span class="hljs-built_in">console</span>.log(myVariable); <span class="hljs-comment">// Output: 'default value'</span>
</code></pre>
<p>Well, folks there you have it - 10 juicy new features of JavaScript that are sure to knock your socks off! As a web developer, it's important to stay up to date with the latest advancements in the field, and these features are worth getting excited about.</p>
<p>Whether you're a seasoned pro or a newbie just starting, there's something here for everyone. The Nullish Coalescing Operator, Optional Chaining, Private Class Fields, Dynamic Import, BigInt, Promise.allSettled(), and Logical Assignment Operators all offer powerful new capabilities that can enhance your coding skills and productivity.</p>
<p>So why not take a deep dive into each of these features, and see how you can leverage them to build better, more efficient, and more secure web applications? And remember, these are just the tip of the iceberg when it comes to the exciting world of JavaScript - there's always more to learn and explore!</p>
<p>So, let's roll up our sleeves, fire up our text editors, and get coding! And as always, keep supporting us by liking, commenting, and sharing this blog.</p>
<p>Please comment down here do you want to make a blog on deep dive into each of these features to know more in detail.</p>
]]></content:encoded></item><item><title><![CDATA[React Hook Testing: Tips, Tricks, and Techniques for Jest and React Testing Library]]></title><description><![CDATA[The introduction of React Hooks has caused a significant shift in the way React components are written. This shift has resulted in increased reusability, composability, and improved testability. Nonetheless, testing React Hooks presents its own set o...]]></description><link>https://frontendgenius.com/react-hook-testing-tips-tricks-and-techniques-for-jest-and-react-testing-library</link><guid isPermaLink="true">https://frontendgenius.com/react-hook-testing-tips-tricks-and-techniques-for-jest-and-react-testing-library</guid><category><![CDATA[React]]></category><category><![CDATA[Jest]]></category><category><![CDATA[Testing Library]]></category><category><![CDATA[hooks]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Wed, 01 Mar 2023 11:57:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677396990445/bad0eb82-0e76-44d7-907c-8add03bcfe8a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The introduction of React Hooks has caused a significant shift in the way React components are written. This shift has resulted in increased reusability, composability, and improved testability. Nonetheless, testing React Hooks presents its own set of obstacles, particularly when it comes to mocking dependencies, handling asynchronous behavior, or dealing with edge cases.</p>
<p>In the following blog post, we'll delve into a variety of tips, tricks, and techniques for effectively testing React Hooks with Jest and React Testing Library. By providing practical examples, we aim to provide a better understanding of each concept, empowering you to write thorough and effective tests for your own React Hooks.</p>
<p>Let's get started!</p>
<h2 id="heading-what-are-react-hooks"><strong>What are React Hooks?</strong></h2>
<p>React Hooks provide a means to utilize state, lifecycle methods, and additional features of React, all without the need to write class components. Essentially, Hooks are functions that enable you to connect to React state and lifecycle features directly from functional components. This approach eliminates the need for higher-order components, rendering props, or duplicative code, making it possible to reuse stateful logic across various components with ease.</p>
<p>Some common React Hooks include:</p>
<ul>
<li><p><code>useState</code> for managing the state in functional components</p>
</li>
<li><p><code>useEffect</code> for managing side effects in functional components</p>
</li>
<li><p><code>useContext</code> for consuming context in functional components</p>
</li>
<li><p><code>useReducer</code> for managing complex states in functional components</p>
</li>
<li><p><code>useCallback</code> for memoizing functions in functional components</p>
</li>
<li><p><code>useMemo</code> for memoizing values in functional components</p>
</li>
<li><p><code>useRef</code> for accessing and modifying DOM elements in functional components</p>
</li>
<li><p><code>useLayoutEffect</code> for managing side effects before the component renders</p>
</li>
</ul>
<h2 id="heading-why-test-react-hooks"><strong>Why Test React Hooks?</strong></h2>
<p>Testing React Hooks is essential because they contain the business logic of your application. By testing your Hooks, you can ensure that they work as intended and that your application behaves as expected. Testing also helps you catch bugs and regressions early on, preventing them from reaching production and causing more significant problems.</p>
<p>Testing React Hooks provides developers with a valuable tool for improving their codebase. By creating comprehensive test suites for Hooks, developers can refactor their code with confidence, knowing that any regressions or errors will be caught by the tests. This approach enables developers to safely modify their code while ensuring that the intended functionality is preserved. Additionally, the act of creating tests for Hooks often prompts developers to think more deeply about the behavior and logic of their code, leading to further improvements and optimizations.</p>
<h2 id="heading-setting-up-the-testing-environment"><strong>Setting up the Testing Environment</strong></h2>
<p>Before proceeding with the specifics of testing React Hooks, it's essential to set up the testing environment. For our tests, we'll be using Jest, a widely-used JavaScript testing framework, and React Testing Library, a testing library specifically designed for testing React components. By utilizing these tools, we can effectively and efficiently test our React Hooks, ensuring their reliability and functionality.</p>
<p>Assuming you have a React project set up, you can install Jest and React Testing Library with the following commands:</p>
<pre><code class="lang-bash">npm install --save-dev jest @testing-library/react @testing-library/jest-dom
</code></pre>
<p>Next, let's create a test file for our Hooks. In this example, we will create a test file for a custom Hook called <code>useCounter</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { renderHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react-hooks'</span>;
<span class="hljs-keyword">import</span> useCounter <span class="hljs-keyword">from</span> <span class="hljs-string">'./useCounter'</span>;

describe(<span class="hljs-string">'useCounter'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should increment counter'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =&gt;</span> useCounter());

    expect(result.current.count).toBe(<span class="hljs-number">0</span>);

    act(<span class="hljs-function">() =&gt;</span> {
      result.current.increment();
    });

    expect(result.current.count).toBe(<span class="hljs-number">1</span>);
  });
});
</code></pre>
<p>In this test file, we import <code>renderHook</code> from React Testing Library, import our custom Hook <code>useCounter</code>, and create a test case that checks whether the <code>increment</code> function increments the counter. We use the <code>renderHook</code> function to render our Hook and access its state and functions.</p>
<h3 id="heading-mock-dependencies"><strong>Mock Dependencies</strong></h3>
<p>Testing React Hooks can be a challenging task when they have external dependencies, such as APIs or services. It becomes difficult to test Hooks in isolation without introducing errors or failing tests. Fortunately, Jest offers a solution to this problem by providing a mocking feature using <code>jest.mock</code>. This feature allows developers to replace dependencies with mock objects or functions, effectively simulating the behavior of the external dependencies in a controlled environment. By using <code>jest.mock</code>, developers can test their Hooks independently and with confidence, ensuring their reliability and functionality.</p>
<p>Let's say our <code>useCounter</code> The hook depends on a service that fetches the counter value from the server.</p>
<p>To mock the service dependency, we can use <code>jest.mock</code> and provide a fake implementation of the service. Here's an example:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { renderHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react-hooks'</span>;
<span class="hljs-keyword">import</span> useCounter <span class="hljs-keyword">from</span> <span class="hljs-string">'./useCounter'</span>;
<span class="hljs-keyword">import</span> counterService <span class="hljs-keyword">from</span> <span class="hljs-string">'./counterService'</span>;

jest.mock(<span class="hljs-string">'./counterService'</span>, <span class="hljs-function">() =&gt;</span> ({
  <span class="hljs-attr">getCounter</span>: jest.fn(),
}));

describe(<span class="hljs-string">'useCounter'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should increment counter'</span>, <span class="hljs-function">() =&gt;</span> {
    counterService.getCounter.mockResolvedValueOnce(<span class="hljs-number">0</span>);
    <span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =&gt;</span> useCounter());
    expect(result.current.count).toBe(<span class="hljs-number">0</span>);
    act(<span class="hljs-function">() =&gt;</span> {
      result.current.increment();
    });
    expect(result.current.count).toBe(<span class="hljs-number">1</span>);
  });
});
</code></pre>
<p>In this example, we use <code>jest.mock</code> to mock the <code>counterService</code> module and provide a fake implementation of the <code>getCounter</code> function using <code>jest.fn()</code>. We then use <code>counterService.getCounter.mockResolvedValueOnce(0)</code> to mock the value returned by the <code>getCounter</code> function.</p>
<p>By mocking the dependency, we can test our Hook in isolation without relying on external services. We can also test different scenarios by changing the mock implementation of the service.</p>
<h3 id="heading-test-asynchronous-behavior"><strong>Test Asynchronous Behavior</strong></h3>
<p>Another challenge of testing React Hooks is handling asynchronous behavior. When Hooks perform asynchronous operations like fetching data from an API or updating the DOM, it can be challenging to test them effectively.</p>
<p>React Testing Library provides a way to handle asynchronous behavior using the <code>waitFor</code> function. The <code>waitFor</code> the function waits for a condition to be true before continuing the test. We can use it to wait for the Hook to update its state or perform a side effect.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { renderHook, act } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react-hooks'</span>;
<span class="hljs-keyword">import</span> useFetch <span class="hljs-keyword">from</span> <span class="hljs-string">'./useFetch'</span>;

describe(<span class="hljs-string">'useFetch'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should fetch data'</span>, <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> { result, waitForNextUpdate } = renderHook(<span class="hljs-function">() =&gt;</span> useFetch(<span class="hljs-string">'/api/data'</span>));

    expect(result.current.loading).toBe(<span class="hljs-literal">true</span>);
    <span class="hljs-keyword">await</span> waitForNextUpdate();

    expect(result.current.data).toEqual({ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John Doe'</span> });
    expect(result.current.loading).toBe(<span class="hljs-literal">false</span>);
  });
});
</code></pre>
<p>In this example, we use the <code>renderHook</code> function to render our <code>useFetch</code> Hook and wait for the next update using <code>waitForNextUpdate</code>. We then assert that the loading state is true before the update and false after the update. We also assert that the data is correct after the update.</p>
<p>By using <code>waitFor</code> to handle asynchronous behavior, we can write more robust tests that cover different scenarios and edge cases.</p>
<h3 id="heading-test-edge-cases"><strong>Test Edge Cases</strong></h3>
<p>When testing React Hooks, it's essential to test edge cases and error scenarios. For example, what happens when the Hook receives invalid input or when an error occurs during an asynchronous operation?</p>
<p>To test edge cases, we can use Jest's <code>expect</code> function to test specific conditions and use <code>try-catch</code> blocks to catch errors. We can also use React Testing Library's <code>act</code> function to simulate user interactions and test different scenarios.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { renderHook, act } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react-hooks'</span>;
<span class="hljs-keyword">import</span> useInput <span class="hljs-keyword">from</span> <span class="hljs-string">'./useInput'</span>;

describe(<span class="hljs-string">'useInput'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should update input value'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =&gt;</span> useInput());

    expect(result.current.value).toBe(<span class="hljs-string">''</span>);

    act(<span class="hljs-function">() =&gt;</span> {
      result.current.onChange({ <span class="hljs-attr">target</span>: { <span class="hljs-attr">value</span>: <span class="hljs-string">'John Doe'</span> } });
    });

    expect(result.current.value).toBe(<span class="hljs-string">'John Doe'</span>);
  });

  it(<span class="hljs-string">'should return error for invalid input'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =&gt;</span> useInput());

    expect(result.current.error).toBeNull();

    act(<span class="hljs-function">() =&gt;</span> {
      result.current.onChange({ <span class="hljs-attr">target</span>: { <span class="hljs-attr">value</span>: <span class="hljs-string">'123'</span> } });
    });

    expect(result.current.error).toBe(<span class="hljs-string">'Input must be a string'</span>);
  });
});
});
</code></pre>
<p>In this example, we assert that the <code>error</code> state is null before we simulate the scenario. We then simulate the scenario by passing an invalid input value to the <code>onChange</code> function. We expect an error to be thrown, and the error message to be 'Input must be a string'.</p>
<p>By testing edge cases and error scenarios, we can ensure that our Hooks behave correctly in all scenarios, including unexpected ones.</p>
<p>Testing React Hooks is a crucial aspect of building reliable and maintainable React applications. In this blog post, we have explored various tips, tricks, and techniques for testing React Hooks using Jest and React Testing Library. We have discussed the process of setting up the testing environment, handling asynchronous behavior, and testing edge cases and error scenarios. By following these best practices, developers can ensure that their Hooks work as intended, catch bugs and regressions early on, and safely refactor and improve their codebase. Ultimately, incorporating testing practices into the development process leads to more stable and robust applications.</p>
<p>By following these best practices, you can write tests that cover all scenarios and edge cases and ensure that your Hooks behave correctly in different situations.</p>
]]></content:encoded></item><item><title><![CDATA[React Hooks - What's happening under the hood]]></title><description><![CDATA[React Hooks are a game changer in the world of React. They allow you to use state and other React features without writing a class component, making your code much easier and more efficient to write and maintain. But what is happening under the hood ...]]></description><link>https://frontendgenius.com/react-hooks-whats-happening-under-the-hood</link><guid isPermaLink="true">https://frontendgenius.com/react-hooks-whats-happening-under-the-hood</guid><category><![CDATA[React]]></category><category><![CDATA[hooks]]></category><category><![CDATA[react-state]]></category><category><![CDATA[useState]]></category><category><![CDATA[closure]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sat, 25 Feb 2023 05:17:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677085593582/0ba96849-e5ea-49a6-bb10-d0b3a94783e7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>React Hooks are a game changer in the world of React. They allow you to use state and other React features without writing a class component, making your code much easier and more efficient to write and maintain. But what is happening under the hood when you use React Hooks?</p>
<p>To understand this, let's take a look at a simple example. Suppose you have a functional component that displays a counter and a button to increment the counter. You can implement this using React Hooks as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this example, we are using the <code>useState</code> Hook to manage the state in our functional component. When the component is first rendered, useState returns an array with two elements: the current state value (0 in this case), and a function to update that state value (<code>setCount</code>).</p>
<p>When the user clicks the "Increment" button, the onClick handler calls setCount with the new count value. This updates the state value and triggers a re-render of the component with the new count value displayed on the screen.</p>
<p>But how does this work under the hood? When we call <code>useState</code>, React creates a closure around the state value and the setCount function. This closure is persistent across renders, so we can use the same useState Hook to manage the state across multiple renders of the component.</p>
<p>When we call setCount with a new count value, React updates the state value and triggers a re-render of the component. This is achieved using React's internal <code>updateQueue</code> and <code>fiber data</code> structures, which keep track of changes to the component's state and props.</p>
<p>The <code>useState</code> hook is just one example of how React Hooks work. There are many other Hooks available, such as <code>useEffect</code>, <code>useContext</code>, and <code>useRef</code>, which allow you to add functionality to your functional components without the need for class components.</p>
<h3 id="heading-lets-take-a-closer-look">Let's take a closer look!</h3>
<p>At its core, React Hooks utilize the hidden state of a component, which is stored inside a fiber. A fiber represents an entity that corresponds to a component instance. However, unlike class components, functional components do not create instances.</p>
<p>The React renderer grants access to the respective context, state, and other information that a hook needs. Moreover, it's the React renderer that calls the component function, allowing it to associate the component instance with hook functions that are called inside the component function.</p>
<p>To better understand how this works, consider the following code snippet:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">let</span> currentlyRenderedCompInstance;
<span class="hljs-keyword">const</span> compStates = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>(); <span class="hljs-comment">// maps component instances to their states</span>
<span class="hljs-keyword">const</span> compInstances = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>(); <span class="hljs-comment">// maps component functions to instances</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useState</span>(<span class="hljs-params">initialState</span>) </span>{
  <span class="hljs-keyword">if</span> (!compStates.has(currentlyRenderedCompInstance))
    compStates.set(currentlyRenderedCompInstance, initialState);

  <span class="hljs-keyword">return</span> [
    compStates.get(currentlyRenderedCompInstance), <span class="hljs-comment">// state</span>
    <span class="hljs-function"><span class="hljs-params">val</span> =&gt;</span> compStates.set(currentlyRenderedCompInstance, val) <span class="hljs-comment">// state setter</span>
  ];
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params">comp, props</span>) </span>{
  <span class="hljs-keyword">const</span> compInstanceToken = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'Renderer token for '</span> + comp.name);

  <span class="hljs-keyword">if</span> (!compInstances.has(comp))
    compInstances.set(comp, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>());

  compInstances.get(comp).add(compInstanceToken);

  currentlyRenderedCompInstance = compInstanceToken;

  <span class="hljs-keyword">return</span> { 
    <span class="hljs-attr">instance</span>: compInstanceToken,
    <span class="hljs-attr">children</span>: comp(props)
  };
}
</code></pre>
<p>As you can see, <code>useState</code> can access the currently rendered component instance token through <code>currentlyRenderedCompInstance</code>. Similarly, other built-in hooks can also access this token and maintain the state for the component instance.</p>
<p>React Hooks leverage the hidden state of a component, which is stored in a fiber. The React renderer grants hook access to relevant information and associates the component instance with hook functions. This allows for efficient state management and enhances the development experience.</p>
<p>In conclusion, React Hooks are a powerful tool for writing React components more simply and efficiently. <mark>They use closures to manage state</mark> and lifecycle methods in functional components, allowing you to write reusable logic and share stateful logic between components. Understanding how Hooks work under the hood can help you write better React code and take advantage of the full potential of this amazing library.</p>
<div class="hn-embed-widget" id="youtube"></div>]]></content:encoded></item><item><title><![CDATA[Why React Does Not Necessarily Need a Global State Manager]]></title><description><![CDATA[As React developers, we often hear about the need for a global state manager in our applications, but in some cases, using a global state manager may not be necessary. By pushing a state towards the leaf components and using a local state and props, ...]]></description><link>https://frontendgenius.com/why-react-does-not-necessarily-need-a-global-state-manager</link><guid isPermaLink="true">https://frontendgenius.com/why-react-does-not-necessarily-need-a-global-state-manager</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[React]]></category><category><![CDATA[React, useState, state management, hooks, components, JavaScript, front-end development, web development, code examples, step-by-step guide, user interfaces, programming, tutorial, web development tutorial, javascript development, react development, reactjs, state hook, state management in react, frontend development]]></category><category><![CDATA[Global State Management]]></category><category><![CDATA[React Development]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Wed, 22 Feb 2023 15:39:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677077943124/ad7296b0-6efb-4881-8e36-3b4530d4868b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As React developers, we often hear about the need for a global state manager in our applications, but in some cases, using a global state manager may not be necessary. By pushing a state towards the leaf components and using a local state and props, we can simplify our application's architecture and make it more efficient and maintainable. let us take a look at some real-world examples to understand this better.</p>
<p>In this article, we'll explore why React may not necessarily need a global state manager and discuss some alternatives that developers can use to manage state in their applications.</p>
<h3 id="heading-what-is-a-global-state-manager"><strong>What is a Global State Manager?</strong></h3>
<p>Before we dive into why React may not need a global state manager, let's first define what it is. A global state manager is a tool or library that allows developers to manage the state of an application in a centralized location.</p>
<p>In React, this is typically done with tools like Redux or MobX. These libraries provide a way for developers to store and manage data across their applications without having to pass data between components.</p>
<h3 id="heading-decentralizing-data">Decentralizing Data</h3>
<p>Consider an e-commerce website that has a product page with multiple sections, such as product details, related products, and reviews. We can store the data related to each section in the component that is responsible for rendering that section. For instance, we can store the product details in the Product Details component and the reviews in the Reviews component. here is an example of how we can implement this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductPage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [productDetails, setProductDetails] = useState({ <span class="hljs-comment">/* product details data */</span> });
  <span class="hljs-keyword">const</span> [relatedProducts, setRelatedProducts] = useState({ <span class="hljs-comment">/* related products data */</span> });
  <span class="hljs-keyword">const</span> [reviews, setReviews] = useState({ <span class="hljs-comment">/* reviews data */</span> });

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ProductDetails</span> <span class="hljs-attr">productDetails</span>=<span class="hljs-string">{productDetails}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">RelatedProducts</span> <span class="hljs-attr">relatedProducts</span>=<span class="hljs-string">{relatedProducts}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Reviews</span> <span class="hljs-attr">reviews</span>=<span class="hljs-string">{reviews}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this example, we store the data related to each section in its respective state variables and pass them as props to the corresponding child components. This way, we keep the data decentralized and ensure that only the required components receive the relevant data.</p>
<h3 id="heading-avoiding-unnecessary-complexity"><strong>Avoiding Unnecessary Complexity</strong></h3>
<p>Imagine a simple to-do list application that allows users to add, delete and mark tasks as complete. In such an application, using a global state manager may not be necessary. Instead, we can keep the state of the to-do list in the parent component and pass it as props to the child components. Here's an example of how we can implement this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoApp</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [todos, setTodos] = useState([]);

  <span class="hljs-keyword">const</span> addTodo = <span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> {
    setTodos([...todos, todo]);
  };

  <span class="hljs-keyword">const</span> deleteTodo = <span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> {
    setTodos(todos.filter(<span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> t !== todo));
  };

  <span class="hljs-keyword">const</span> completeTodo = <span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> updatedTodos = todos.map(<span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span>
      t === todo ? { ...t, <span class="hljs-attr">completed</span>: <span class="hljs-literal">true</span> } : t
    );
    setTodos(updatedTodos);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">TodoList</span> <span class="hljs-attr">todos</span>=<span class="hljs-string">{todos}</span> <span class="hljs-attr">onDelete</span>=<span class="hljs-string">{deleteTodo}</span> <span class="hljs-attr">onComplete</span>=<span class="hljs-string">{completeTodo}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">AddTodo</span> <span class="hljs-attr">onAdd</span>=<span class="hljs-string">{addTodo}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this example, we keep the state of the to-do list in the TodoApp component and pass it as props to the TodoList component, which renders the list of todos. We also pass callback functions onDelete and onComplete as props to the TodoList component, which are called when the user clicks the delete and complete buttons. This way, we avoid the unnecessary complexity that a global state manager like Redux can add to our application.</p>
<h3 id="heading-transporting-user-interaction">Transporting User Interaction</h3>
<p>When it comes to transporting user interaction between distant sibling trees or components in a React application, a global state manager may be necessary. For example, imagine a large form that is split into different sections, each with its own component, and the user must navigate between them. If we want to save the user's progress, we need a way to transport their interaction from one component to another.</p>
<p>In this case, we can use a global state manager to store the user's progress and make it accessible to all components. Let's take a look at an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create a new Redux store</span>
<span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">const</span> store = createStore(reducer);

<span class="hljs-comment">// Define a reducer function to update the store's state</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state = {}, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'UPDATE_FORM'</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">formData</span>: action.payload };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
}

<span class="hljs-comment">// Create an action to update the form data in the store</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateForm</span>(<span class="hljs-params">formData</span>) </span>{
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'UPDATE_FORM'</span>, <span class="hljs-attr">payload</span>: formData };
}

<span class="hljs-comment">// Dispatch the action when the user updates the form data</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleFormUpdate</span>(<span class="hljs-params">formData</span>) </span>{
  store.dispatch(updateForm(formData));
}

<span class="hljs-comment">// Access the form data in a different component</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">OtherComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> formData = useSelector(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.formData);
  <span class="hljs-comment">// Use the form data in the component</span>
}
</code></pre>
<p>In this example, we create a new Redux store with a reducer function that updates the state when the UPDATE_FORM action is dispatched. We define an updateForm action that takes the form data as its payload and dispatches it to the store. In a different component, we use the useSelector hook to access the form data from the store and use it in the component.</p>
<p>While this example uses Redux, other global state managers like MobX or Zustand can also be used to transport user interaction in a React application. However, as mentioned earlier, we should still consider whether or not a global state manager is necessary and whether we can avoid unnecessary complexity in our application's architecture.</p>
<h3 id="heading-alternatives-to-global-state-managers"><strong>Alternatives to Global State Managers</strong></h3>
<p>If you decide that a global state manager is not necessary for your React application, there are several alternatives that you can use to manage the state.</p>
<h4 id="heading-reacts-built-in-state-management">React's Built-in State Management</h4>
<p>React comes with its own built-in state management system, which can be used to manage the state in a component. This system allows developers to store and update data within a component without having to pass data between components.</p>
<p>While this system may not be suitable for more complex state management needs, it can be a good option for simpler applications.</p>
<h4 id="heading-context-api">Context API</h4>
<p>The Context API is another option for managing state in React applications. It provides a way for developers to share data between components without having to pass data down through props.</p>
<p>The Context API is built into React, so it doesn't require any additional libraries or tools to use. It can also be used in combination with other state management solutions, such as Redux or MobX.</p>
<p>But it should be used with caution, as it can also cause performance issues.</p>
<h4 id="heading-local-state-management-libraries">Local State Management Libraries</h4>
<p>There are several libraries available that provide local state management solutions for React applications. These libraries allow developers to manage the state within a component or a specific part of the application.</p>
<p>Some popular local state management libraries include Unstated, Recoil, and Zustand.</p>
<p>In conclusion, while global state managers can be useful in certain situations, they may not be necessary for all applications built with React. React's built-in state management system, the Context API, and local state management libraries can all be used as alternatives to global state managers.</p>
<div class="hn-embed-widget" id="youtube"></div>]]></content:encoded></item><item><title><![CDATA[Uncovering the Truth About Default Parameters in JavaScript Functions]]></title><description><![CDATA[If you're new to JavaScript or you're still trying to understand the mechanics of how function arguments and parameters work, this article is for you. With the release of ECMAScript 6 (ES6), also known as ES2015, new features were added to the langua...]]></description><link>https://frontendgenius.com/uncovering-the-truth-about-default-parameters-in-javascript-functions</link><guid isPermaLink="true">https://frontendgenius.com/uncovering-the-truth-about-default-parameters-in-javascript-functions</guid><category><![CDATA[Destructuring]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ES6]]></category><category><![CDATA[default parameter]]></category><category><![CDATA[rest parameter]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sat, 18 Feb 2023 08:12:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676623833114/0aa29f53-221c-49f2-9b59-d13be391fa2e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're new to JavaScript or you're still trying to understand the mechanics of how function arguments and parameters work, this article is for you. With the release of ECMAScript 6 (ES6), also known as ES2015, new features were added to the language to make it even more powerful and efficient. One of these new features is default parameters in JavaScript functions, which can help make your code cleaner and more organized. We'll dive into the details of how JavaScript handles function arguments and parameters, and why it does so.</p>
<h3 id="heading-understanding-the-relationship-between-arguments-and-parameters">Understanding the Relationship between Arguments and Parameters</h3>
<p>The first thing to understand is the difference between function arguments and parameters. When a function is defined, it can be designed to accept one or more parameters. These parameters are essentially placeholders for the values that the function expects to receive when it is called.</p>
<p>For example, if we have a function that accepts a single parameter called "a", we would define it like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">example</span>(<span class="hljs-params">a</span>) </span>{
  <span class="hljs-comment">// function code goes here</span>
}
</code></pre>
<p>When we call this function, we pass in an argument for the "a" parameter:</p>
<pre><code class="lang-javascript">example(<span class="hljs-number">42</span>);
</code></pre>
<p>In this case, the value 42 is the argument that we're passing to the function.</p>
<h3 id="heading-assigning-values-to-parameters">Assigning Values to Parameters</h3>
<p>When the function is called, the values of the arguments are assigned to the parameters. This means that if we have a function like the one in the previous example, and we call it with an argument of 42, the "a" parameter gets assigned the value of 42.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">example</span>(<span class="hljs-params">a</span>) </span>{
  <span class="hljs-built_in">console</span>.log(a);
}

example(<span class="hljs-number">42</span>); <span class="hljs-comment">// logs 42</span>
</code></pre>
<h3 id="heading-creating-a-new-scope">Creating a New Scope</h3>
<p>When you call a function without default parameter values, a new scope is created for the body of the function, and the parameters are created in that scope like top-level variables in the function.</p>
<p>However, when there are default parameter values, an additional scope is involved. This is because default parameter values are expressions, not just literals.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">example</span>(<span class="hljs-params">a = <span class="hljs-number">1</span>, b = a + <span class="hljs-number">1</span></span>) </span>{
  <span class="hljs-comment">// function code goes here</span>
}
</code></pre>
<p>In this example, the "a" parameter has a default value of 1, and the "b" parameter has a default value of "a + 1". When this function is called, a new scope is created for the function body and another scope is created for the parameter list.</p>
<p><strong>An example of the above code is when it transforms:-</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> a = <span class="hljs-built_in">arguments</span>.length &gt; <span class="hljs-number">0</span> &amp;&amp; <span class="hljs-built_in">arguments</span>[<span class="hljs-number">0</span>] !== <span class="hljs-literal">undefined</span> ? <span class="hljs-built_in">arguments</span>[<span class="hljs-number">0</span>] : <span class="hljs-number">1</span>;
  <span class="hljs-keyword">var</span> b =
    <span class="hljs-built_in">arguments</span>.length &gt; <span class="hljs-number">1</span> &amp;&amp; <span class="hljs-built_in">arguments</span>[<span class="hljs-number">1</span>] !== <span class="hljs-literal">undefined</span> ? <span class="hljs-built_in">arguments</span>[<span class="hljs-number">1</span>] : a + <span class="hljs-number">1</span>;
} <span class="hljs-comment">// function code goes here</span>
</code></pre>
<p>isn't it interesting right?</p>
<p>This is done to prevent expressions in the parameter list from referring to hoisted variables and functions declared in the function body.</p>
<h3 id="heading-using-parameters-in-an-expression">Using Parameters in an Expression</h3>
<p>One interesting thing about how JavaScript handles function parameters is that they're processed in source code order. This means that later parameters can refer to earlier parameters, but earlier parameters can't refer to later ones because those aren't initialized yet.</p>
<p>For example, you can define a function like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name, greeting, message = greeting + <span class="hljs-string">' '</span> + name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(message);
}

greet(<span class="hljs-string">"John"</span>, <span class="hljs-string">"Hello"</span>); <span class="hljs-comment">// logs "Hello John"</span>
</code></pre>
<p>In this example, the "message" parameter has a default value that includes both the "name" and "greeting" parameters. Since "greeting" is defined before "message" in the parameter list, it can be used in the expression that defines "message".</p>
<p><strong>An example of the above code is when it transforms:-</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name, greeting</span>) </span>{
  <span class="hljs-keyword">var</span> message =
    <span class="hljs-built_in">arguments</span>.length &gt; <span class="hljs-number">2</span> &amp;&amp; <span class="hljs-built_in">arguments</span>[<span class="hljs-number">2</span>] !== <span class="hljs-literal">undefined</span>
      ? <span class="hljs-built_in">arguments</span>[<span class="hljs-number">2</span>]
      : greeting + <span class="hljs-string">" "</span> + name;
  <span class="hljs-built_in">console</span>.log(message);
}
</code></pre>
<p>JavaScript's handling of function arguments and parameters can seem a bit complex at first, but understanding how it works is essential for writing effective and maintainable code. By keeping the relationship between arguments and parameters in mind, and being aware of how default parameters and scopes work, you can create more powerful and flexible functions in your JavaScript code.</p>
<p>If you enjoy reading my blog, please consider subscribing to my newsletter, leaving a comment, and liking my posts. By subscribing to my newsletter, you'll receive regular updates on my latest blog posts, as well as exclusive content and other exciting news. Leaving comments and liking my posts also helps to show support for my work and encourages me to keep creating valuable content. Thank you for your support and I look forward to continuing to provide you with informative and entertaining blog posts!</p>
<p>Thank You</p>
<div class="hn-embed-widget" id="youtube"></div>]]></content:encoded></item><item><title><![CDATA[Maximizing Cross-Browser Compatibility with Polyfill JavaScript Techniques]]></title><description><![CDATA[Introduction
Cross-Browser Compatibility: What it Means and Why it Matters
Cross-browser compatibility is the cornerstone of an effective website. It refers to a website's ability to function seamlessly across different web browsers, such as Chrome, ...]]></description><link>https://frontendgenius.com/maximizing-cross-browser-compatibility-with-polyfill-javascript-techniques</link><guid isPermaLink="true">https://frontendgenius.com/maximizing-cross-browser-compatibility-with-polyfill-javascript-techniques</guid><category><![CDATA[polyfills]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[tips and tricks]]></category><category><![CDATA[map]]></category><category><![CDATA[array methods]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Wed, 15 Feb 2023 06:47:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676451379176/b17ddfe6-a36a-456f-a0cc-4a0bf037233a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p><strong>Cross-Browser Compatibility: What it Means and Why it Matters</strong></p>
<p>Cross-browser compatibility is the cornerstone of an effective website. It refers to a website's ability to function seamlessly across different web browsers, such as Chrome, Firefox, Safari, and Internet Explorer. Because of the differences in rendering engines and functionalities between browsers, achieving cross-browser compatibility is a difficult task for developers. CSS implementation, JavaScript support, and HTML rendering are just some of the issues that make achieving cross-browser compatibility even more challenging. The problem is further compounded by the increase in mobile devices with various screen sizes and resolutions.</p>
<p><strong>Why is cross-browser compatibility important?</strong></p>
<p>A website that does not function correctly across different browsers can lead to a poor user experience, lost traffic, and lower search engine rankings. Users expect websites to function seamlessly, regardless of the browser they are using. If a website fails to meet this expectation, users are likely to abandon it and look for alternatives. This results in lost traffic and lower search engine rankings, making cross-browser compatibility a critical factor in website development.</p>
<p><strong>The Role of Polyfills in Achieving Cross-Browser Compatibility</strong></p>
<p>Fortunately, polyfills provide a fallback solution for browsers that do not support specific web technologies. These tools replicate the functionality of modern features, allowing developers to write modern code without worrying about compatibility concerns. Using polyfills, developers can ensure that their web applications function seamlessly across a broad range of browsers, including older ones with limited support for modern web technologies.</p>
<p>Polyfills are particularly useful for new web technologies such as HTML5 and CSS3. These technologies offer a range of new features that can enhance the functionality and aesthetics of a website. However, some of these features may not be supported by older browsers. With polyfills, developers can ensure that their web applications function seamlessly across different browsers, allowing them to take advantage of the latest web technologies without sacrificing cross-browser compatibility.</p>
<h3 id="heading-what-is-polyfill-javascript">What is Polyfill JavaScript</h3>
<p>As a web developer, you may have encountered the challenge of ensuring your website or web application works consistently across different browsers. This challenge can be attributed to the varying capabilities of different browsers, especially the older ones that do not natively support modern functionality. However, with the advent of polyfill, this challenge is now a thing of the past.</p>
<p><strong>What is Polyfill, and how does it work?</strong></p>
<p>Polyfill is a JavaScript technique that enables the provision of modern functionality to older browsers that do not natively support it. It works by detecting whether a browser supports a particular feature and, if not, providing a JavaScript alternative to emulate that feature. This ensures that the website or web application works consistently across different browsers, regardless of their capabilities.</p>
<p><strong>Examples of Features that can be Polyfilled</strong></p>
<p>Polyfills can be used to emulate various features, including new HTML5 elements such as <code>&lt;section&gt;</code>, <code>&lt;nav&gt;</code>, and <code>&lt;article&gt;</code>, CSS3 properties such as border-radius and box-shadow, and new JavaScript methods such as <code>Array.forEach()</code> and <a target="_blank" href="http://Array.map"><code>Array.map</code></a><code>()</code>. By using polyfills to emulate these features, developers can write modern code without worrying about browser support.</p>
<p><strong>Other Approaches to Cross-Browser Compatibility</strong></p>
<p>While polyfills are an effective approach to cross-browser compatibility, other approaches can also be used, including feature detection, graceful degradation, and vendor-specific prefixes.</p>
<p>Feature detection involves testing for the availability of a particular feature before using it, and providing a fallback if it is not available. This approach ensures that the website or web application degrades gracefully in the absence of a particular feature.</p>
<p>Graceful degradation involves designing a website or application with a baseline of functionality that works across all browsers and then enhancing the experience for users with modern browsers that support advanced features. This approach ensures that the website or web application works consistently across all browsers.</p>
<p><em>Vendor-specific prefixes involve using browser-specific prefixes for CSS properties that are not yet standardized, such as</em> <code>-webkit-border-radius</code><em>. This approach ensures that the website or web application is compatible with different browsers.</em></p>
<p><strong>Why Polyfills are the Most Effective Way to Ensure Cross-Browser Compatibility</strong></p>
<p>While these approaches have their own advantages, polyfills are often the most effective way to ensure consistent functionality across all browsers. They enable developers to take advantage of the latest web technologies without sacrificing compatibility with older browsers. With polyfills, developers can write modern code without worrying about browser support, ultimately leading to a better user experience.</p>
<h3 id="heading-why-use-polyfill-javascript">Why Use Polyfill JavaScript</h3>
<p>Using polyfills in web development has many benefits, including ensuring cross-browser compatibility, saving time and resources, and improving the user experience. With numerous case studies showcasing their effectiveness, it's clear that polyfills are a powerful tool that every web developer should consider using.</p>
<h3 id="heading-polyfilling-with-code-examples">Polyfilling with Code Examples</h3>
<p>Polyfilling is a technique used in web development to enable modern JavaScript features in older web browsers that do not support them. In this guide, we will walk you through the process of creating a polyfill for a specific feature, complete with code examples and explanations.</p>
<p><strong>Code examples and explanations of each step</strong></p>
<p>The first step in creating a polyfill is to identify the specific feature you want to add to older browsers. For this example, let's assume we want to add support for the "<code>Array.includes()</code>" method, which is not supported in Internet Explorer.</p>
<p>Before creating a polyfill, it's important to check if the feature is already supported in the user's browser. We can do this using a simple if statement:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-comment">// create polyfill</span>
}
</code></pre>
<p>This code checks if the "<code>Array.includes()</code>" method is not supported, and if it isn't, it will execute the code inside the curly braces.</p>
<p>Now that we know the feature we want to add and have checked if it's supported, we can create our polyfill. Here's an example of a polyfill for the "<code>Array.includes()</code>" method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.includes) {
  <span class="hljs-built_in">Array</span>.prototype.includes = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">searchElement <span class="hljs-regexp">/*, fromIndex*/</span></span>) </span>{
<span class="hljs-meta">    'use strict'</span>;
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span> == <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">'Array.prototype.includes called on null or undefined'</span>);
    }

    <span class="hljs-keyword">var</span> O = <span class="hljs-built_in">Object</span>(<span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">var</span> len = <span class="hljs-built_in">parseInt</span>(O.length, <span class="hljs-number">10</span>) || <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (len === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
    <span class="hljs-keyword">var</span> n = <span class="hljs-built_in">parseInt</span>(<span class="hljs-built_in">arguments</span>[<span class="hljs-number">1</span>], <span class="hljs-number">10</span>) || <span class="hljs-number">0</span>;
    <span class="hljs-keyword">var</span> k;
    <span class="hljs-keyword">if</span> (n &gt;= <span class="hljs-number">0</span>) {
      k = n;
    } <span class="hljs-keyword">else</span> {
      k = len + n;
      <span class="hljs-keyword">if</span> (k &lt; <span class="hljs-number">0</span>) {k = <span class="hljs-number">0</span>;}
    }
    <span class="hljs-keyword">var</span> currentElement;
    <span class="hljs-keyword">while</span> (k &lt; len) {
      currentElement = O[k];
      <span class="hljs-keyword">if</span> (searchElement === currentElement ||
         (searchElement !== searchElement &amp;&amp; currentElement !== currentElement)) {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
      }
      k++;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  };
}
</code></pre>
<p>This code creates a new "<code>Array.includes()</code>" method that will be used if the feature is not supported. It uses the same syntax and behavior as the native method, ensuring that the behavior is consistent across all browsers.</p>
<p><strong>Best practices for creating efficient and effective polyfills</strong></p>
<p>To create an efficient and effective polyfill, it's important to follow some best practices. These include:</p>
<ul>
<li><p>Only polyfill what's needed: Polyfill only the specific features that are required for your application. Adding unnecessary polyfills can increase the size of your code and slow down your application.</p>
</li>
<li><p>Use strict mode: Use strict mode to avoid common JavaScript pitfalls and to ensure that your polyfill behaves consistently across all browsers.</p>
</li>
<li><p>Test thoroughly: Test your polyfill in as many browsers and devices as possible to ensure that it works correctly and doesn't introduce any new bugs or issues.</p>
</li>
</ul>
<p>In conclusion, Polyfill is a powerful tool that can help developers to maximize cross-browser compatibility. By providing missing functionality to older browsers, Polyfill ensures that websites will work correctly regardless of which browser is used to access them. Whether you're a seasoned developer or just starting out, using Polyfill is an effective and cost-efficient way to ensure that your website is accessible to all users.</p>
<p>Thanks for reading</p>
<div class="hn-embed-widget" id="youtube"></div>]]></content:encoded></item><item><title><![CDATA[Mastering Callback Hell and Inversion of Control in JavaScript: Boost Your Skills with 5 Benefits]]></title><description><![CDATA[As a JavaScript developer, you might have encountered the problem of dealing with complex chains of asynchronous functions and ending up in a maze of callbacks, which is commonly referred to as "Callback Hell". In addition, managing the flow of execu...]]></description><link>https://frontendgenius.com/mastering-callback-hell-and-inversion-of-control-in-javascript-boost-your-skills-with-5-benefits</link><guid isPermaLink="true">https://frontendgenius.com/mastering-callback-hell-and-inversion-of-control-in-javascript-boost-your-skills-with-5-benefits</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[callback hell ]]></category><category><![CDATA[inversion of conrtol]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Mon, 13 Feb 2023 08:42:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676449496384/d7be9cb9-ec84-4b66-bf17-db96db5688e9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a JavaScript developer, you might have encountered the problem of dealing with complex chains of asynchronous functions and ending up in a maze of callbacks, which is commonly referred to as "Callback Hell". In addition, managing the flow of execution of your code can also become a challenge, known as the "Inversion of Control". But don't worry, in this blog post, we will dive into these concepts, understand the root causes, and learn how to overcome them with the help of real-world examples and hands-on coding. By the end of this post, you will not only have a better understanding of these concepts but also gain practical skills on how to improve the readability and maintainability of your code. So buckle up, and let's get started!</p>
<h3 id="heading-what-is-callback-hell">What is Callback Hell?</h3>
<p>Callback hell refers to a situation where the code becomes difficult to read and maintain due to excessive use of nested callback functions. This often happens when developers try to write asynchronous code by using multiple nested callback functions to handle dependencies. The code becomes overly complex and hard to follow, making it difficult to debug and maintain.</p>
<p>For example, consider a scenario where you are building an e-commerce website and you need to create an order, proceed to payment, and show an order summary page. To handle this flow, you need to use two backend APIs: "create order" and "proceed to payment." After the order is created, you proceed to payment, and once the payment is successful, you show an order summary page.</p>
<p>To handle this flow, you would write a callback function for the "proceed to payment" API and pass it along with the cart items to the "create order" API. The "create order" API would then create an order and call the callback function back, allowing you to handle the asynchronous operation.</p>
<p>However, if you need to add another step, such as showing an order summary page after the payment is successful, you would have to nest another callback function inside the first one. This can quickly lead to callback hell, making the code hard to read and maintain.</p>
<p>A callback is a function that is passed as an argument to another function and is executed after the first function is finished. In JavaScript, we often use callbacks to handle the asynchronous nature of the language. For example, let's say we want to fetch some data from an API and display it on the screen. We can use the fetch API to do this, and the code would look something like this:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error))
</code></pre>
<p>In this example, we use the <code>fetch</code> API to get data from the API, and then we use the <code>then</code> method to handle the response. We also use the <code>catch</code> method to handle any errors that might occur. This is a simple example, and we can easily understand what is happening. But, things get complicated when we start using multiple nested callbacks. Consider the following example:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> response.json().then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(data)
      <span class="hljs-keyword">return</span> data
    })
  })
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">'https://api.example.com/data/'</span> + data.id)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(data)
        <span class="hljs-keyword">return</span> data
      })
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error))
</code></pre>
<p>As we can see, the code has become hard to read, debug, and maintain due to multiple nested callbacks. This is what is referred to as Callback Hell.</p>
<h3 id="heading-inversion-of-control-to-the-rescue">Inversion of Control to the Rescue</h3>
<p>Callback hell is a common problem faced by many JavaScript developers. It leads to unreadable and unmanageable code, making it difficult to debug and maintain. However, there is a solution to this problem - Inversion of Control.</p>
<p>Inversion of Control is a concept that can help us avoid Callback Hell. It refers to the situation where the control of the flow of our program is taken away from us and handed over to a library or framework. In the case of JavaScript, this means that we let a library or framework handle the asynchronous flow of our program, and we simply provide the necessary callbacks to handle the results.</p>
<p>One such technique that helps us avoid Callback Hell is <code>async-await</code>. <code>async-await</code> is a syntax sugar that makes working with asynchronous code in JavaScript much easier.</p>
<p>Let's take the above example and re-write it using <code>async-await</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json()
    <span class="hljs-built_in">console</span>.log(data)
    <span class="hljs-keyword">const</span> response2 = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data/'</span> + data.id)
    <span class="hljs-keyword">const</span> data2
  }
  <span class="hljs-keyword">catch</span>(err) {
    <span class="hljs-built_in">console</span>.log(err)
  }
}
</code></pre>
<h3 id="heading-benefits-of-understanding-callback-hell-and-inversion-of-control">Benefits of Understanding Callback Hell and Inversion of Control:</h3>
<p><strong><em><mark>Improving Code Readability and Maintainability</mark></em></strong></p>
<p>With the help of a clear understanding of Callback Hell and Inversion of Control, you will be able to structure your code in a way that makes it easy to read and maintain.</p>
<p>This will result in fewer bugs and faster development time, making it easier for you to deliver high-quality code.</p>
<p><strong><em><mark>Enhancing Performance and Scalability</mark></em></strong></p>
<p>Callback Hell and Inversion of Control can cause performance issues and limit scalability, but with a proper understanding of these concepts, you can improve the overall performance of your code.</p>
<p>This will ensure that your code can handle increased traffic and demand, allowing you to keep up with the growing needs of your users.</p>
<p><strong><em><mark>Streamlining Collaboration and Team Work</mark></em></strong></p>
<p>When everyone on your team is on the same page regarding Callback Hell and Inversion of Control, collaboration, and teamwork become much smoother.</p>
<p>This will result in fewer misunderstandings and disagreements, allowing your team to work together more effectively and achieve your goals faster.</p>
<p><strong><em><mark>Boosting Your Confidence as a JavaScript Developer</mark></em></strong></p>
<p>Understanding Callback Hell and Inversion of Control will give you a deeper understanding of JavaScript, increasing your confidence as a developer.</p>
<p>This will enable you to tackle more complex projects and take on new challenges with ease, helping you to grow as a developer and advance your career.</p>
<p><strong><em><mark>Better Debugging and Enhanced Code Reusability</mark></em></strong></p>
<p>With cleaner and more readable code, debugging becomes easier, allowing you to identify and fix issues faster.</p>
<p>By using IoC, you can write reusable code that is easy to test and maintain, making it easier to reuse in different parts of your application.</p>
<h3 id="heading-ways-to-avoid-callback-hell-in-javascript">Ways to avoid Callback Hell in JavaScript</h3>
<p><mark>Using Promises:</mark></p>
<p>Promises are a pattern for handling asynchronous operations that were introduced in ECMAScript 6 (ES6). Promises allow you to simplify the way you handle callbacks and avoid deep nesting. You can chain multiple Promises together, making it easier to maintain and read your code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">"Data fetched successfully"</span>);
    }, <span class="hljs-number">2000</span>);
  });
};

fetchData()
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(error);
  });
</code></pre>
<p><mark>Using Async/Await:</mark></p>
<p>Async/Await is a modern and cleaner way of handling asynchronous operations in JavaScript. It is built on top of Promises and allows you to write asynchronous code that looks and behaves like synchronous code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">"Data fetched successfully"</span>);
    }, <span class="hljs-number">2000</span>);
  });
};

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  }
}

getData();
</code></pre>
<p><mark>Using async.js library:</mark></p>
<p>async.js is a popular library that provides a suite of functions for working with asynchronous code in JavaScript. It provides functions like <code>async.series</code>, <code>async.parallel</code>, and <code>async.waterfall</code> that make it easy to manage complex asynchronous flows.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> <span class="hljs-keyword">async</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">"async"</span>);

<span class="hljs-keyword">const</span> fetchData = <span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    callback(<span class="hljs-literal">null</span>, <span class="hljs-string">"Data fetched successfully"</span>);
  }, <span class="hljs-number">2000</span>);
};

<span class="hljs-keyword">async</span>.series([
  <span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> {
    fetchData(callback);
  }
], <span class="hljs-function">(<span class="hljs-params">error, results</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(results[<span class="hljs-number">0</span>]);
  }
});
</code></pre>
<p><mark>Modularizing Code:</mark></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    callback(<span class="hljs-literal">null</span>, <span class="hljs-string">"Data fetched successfully"</span>);
  }, <span class="hljs-number">2000</span>);
};

<span class="hljs-keyword">const</span> processData = <span class="hljs-function">(<span class="hljs-params">data, callback</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    callback(<span class="hljs-literal">null</span>, <span class="hljs-string">`Processed data: <span class="hljs-subst">${data}</span>`</span>);
  }, <span class="hljs-number">1000</span>);
};

<span class="hljs-keyword">const</span> logData = <span class="hljs-function">(<span class="hljs-params">data, callback</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);
 }
</code></pre>
<p>In conclusion, mastering callback hell and inversion of control in JavaScript is a critical step toward becoming a skilled and confident developer. With the 5 benefits outlined in this article, you can expect improved code quality, reduced development time, and increased productivity, understanding callback hell and inversion of control is essential for writing effective and maintainable asynchronous code in JavaScript. These concepts play a crucial role in improving the readability and maintainability of your code, making it easier to debug and enhance. With this knowledge, you can write cleaner and more efficient code that can handle complex dependencies in an application.</p>
<p>Thanks for reading</p>
<div class="hn-embed-widget" id="youtube"></div>]]></content:encoded></item><item><title><![CDATA[The Surprising Behavior of Arrow Functions and Class Methods in JavaScript: No Prototype Object Attached]]></title><description><![CDATA[JavaScript is a powerful and dynamic programming language that is widely used for web development. However, many developers are unaware of the behavior of arrow functions and class methods when it comes to the prototype object in JavaScript. In this ...]]></description><link>https://frontendgenius.com/the-surprising-behavior-of-arrow-functions-and-class-methods-in-javascript-no-prototype-object-attached</link><guid isPermaLink="true">https://frontendgenius.com/the-surprising-behavior-of-arrow-functions-and-class-methods-in-javascript-no-prototype-object-attached</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[arrow function]]></category><category><![CDATA[JavaScript, Arrow Functions, Class Methods, Prototype Object, Web Development, Programming Language, Efficient Code, Maintainable Code, Hidden Features, Understanding, Behavior, Development Tips.]]></category><category><![CDATA[Class Methods]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sun, 12 Feb 2023 08:31:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676449842941/c1eb43c9-6043-4e02-92d4-4ab526675cc9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript is a powerful and dynamic programming language that is widely used for web development. However, many developers are unaware of the behavior of arrow functions and class methods when it comes to the prototype object in JavaScript. In this blog, we'll explore why arrow functions and class methods do not have a prototype object attached to them and what this means for your code.</p>
<h3 id="heading-1-arrow-functions-and-prototype-objects">1. Arrow Functions and Prototype Objects</h3>
<p>In JavaScript, every function has a prototype object that is used to define the properties and methods that are available to all instances of the function. However, arrow functions do not have a prototype object attached to them. This means that you cannot add properties or methods to an arrow function that will be shared by all instances of the function.</p>
<p>Here's an example of a traditional function that has a prototype object:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676188858134/9a997d89-29f9-43cc-b49d-62085a20a369.png" alt class="image--center mx-auto" /></p>
<p>Here's the same example using an arrow function:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676196577229/05cb164c-96d5-4650-b86f-4689ee91e15c.png" alt class="image--center mx-auto" /></p>
<p>As you can see, trying to add a property to the prototype object of an arrow function results in a TypeError. This is because arrow functions do not have a prototype object attached to them.</p>
<h3 id="heading-2class-methods-and-prototype-objects">2.Class Methods and Prototype Objects</h3>
<p>Class methods in JavaScript behave similarly to arrow functions when it comes to prototype objects. Class methods do not have a prototype object attached to them, and you cannot add properties or methods to a class method that will be shared by all instances of the class.</p>
<p>Here's an example of a traditional class method that has a prototype object:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676189427633/bff097ce-f11d-4492-a91f-f8ca9793b577.png" alt="example of a traditional class method that has a prototype object" class="image--center mx-auto" /></p>
<p>Here's the same example using a class method:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676189614544/b1c1ca11-3abd-412c-a4dd-b55887ccdbb6.png" alt class="image--center mx-auto" /></p>
<p>As you can see, trying to add a property to the prototype object of a class method does not change the behavior of the method. The method defined within the class will always take precedence over the property defined on the prototype object.</p>
<p>Hence, arrow function are much lighter than function declaration and anonymous function expression with keyword function, because of no extra objects ( prototype ) creation with them.</p>
<p>Classes are synthetical sugar for prototype chain of pre ES-2015 Javascript, but do you know classes methods are more performant because they don't have .prototype too unlike the methods on the ConstructorFunc.prototype, hence using classes are extra performance implications.</p>
<p>In conclusion, arrow functions and class methods do not have a prototype object attached to them. This means that you cannot add properties or methods to these constructs that will be shared by all instances of the function or class. If you need to define properties or methods that will be shared by all instances of a function or class, you'll need to use a traditional function or class with a constructor.</p>
<p>arrow functions and class methods in JavaScript behave differently from traditional functions when it comes to prototype objects. Understanding the behavior of these constructs is important for writing efficient and maintainable code. If you have any questions or would like to dive deeper into this topic, feel free to leave a comment below. We'd love to hear from you and continue the conversation!</p>
]]></content:encoded></item><item><title><![CDATA[6 New Array Functions in ES6]]></title><description><![CDATA[ES6, also known as ECMAScript 2015, brought several new features to JavaScript, including new array functions. In this blog, we'll take a look at six of these new functions and how they can make your life easier when working with arrays in JavaScript...]]></description><link>https://frontendgenius.com/6-new-array-functions-in-es6</link><guid isPermaLink="true">https://frontendgenius.com/6-new-array-functions-in-es6</guid><category><![CDATA[arrays]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[array methods]]></category><category><![CDATA[ES6]]></category><category><![CDATA[filter in js]]></category><dc:creator><![CDATA[Bhushan Patil]]></dc:creator><pubDate>Sat, 11 Feb 2023 15:17:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675772850071/5f69160f-f757-4f06-8918-74617d086574.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>ES6, also known as ECMAScript 2015, brought several new features to JavaScript, including new array functions. In this blog, we'll take a look at six of these new functions and how they can make your life easier when working with arrays in JavaScript.</p>
<h3 id="heading-using-map"><strong>USING MAP()</strong></h3>
<p><strong><em>Definition and Usage</em></strong></p>
<p>The <code>map()</code> the method creates a new array with the results of calling a function for every array element.</p>
<p>The <code>map()</code> method calls the provided function once for each element in an array, in order.</p>
<p><strong>Note:</strong> <code>map()</code> does not execute the function for array elements without values.</p>
<p><strong>Note:</strong> this method does not change the original array.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676126676860/9a418672-6a3b-4a19-8501-612db099dd05.webp" alt="JavaScript map vs for loop" class="image--center mx-auto" /></p>
<h3 id="heading-using-foreach"><strong>USING FOREACH()</strong></h3>
<p><strong><em>Definition and Usage</em></strong></p>
<p>The <code>forEach()</code> method calls a function once for each element in an array, in order.</p>
<p><strong>Note:</strong> the function is not executed for array elements without values.</p>
<p><img src="https://miro.medium.com/max/468/1*oYeIEpkxakkL3mvfq0YApw.png" alt="JavaScript forEach vs for loop" class="image--center mx-auto" /></p>
<h3 id="heading-using-filter"><strong>USING FILTER()</strong></h3>
<p><strong><em>Definition and Usage</em></strong></p>
<p>The <code>filter()</code>the method creates an array filled with all array elements that pass a test (provided as a function).</p>
<p><strong>Note:</strong> <code>filter()</code> does not execute the function for array elements without values.</p>
<p><strong>Note:</strong> <code>filter()</code> does not change the original array.</p>
<p><img src="https://miro.medium.com/max/759/1*MTqDbNxzIBbJxnOYppHYgA.png" alt="JavaScript filter vs for loop" class="image--center mx-auto" /></p>
<h3 id="heading-using-reduce"><strong>USING REDUCE()</strong></h3>
<p><strong><em>Definition and Usage</em></strong></p>
<p>The <code>reduce()</code> the method reduces the array to a single value.</p>
<p>The <code>reduce()</code> the method executes a provided function for each value of the array (from left to right).</p>
<p>The return value of the function is stored in an accumulator (result/total).</p>
<p><strong>Note:</strong> <code>reduce()</code> does not execute the function for array elements without values.</p>
<p><strong>Note:</strong> this method does not change the original array.</p>
<p><img src="https://miro.medium.com/max/659/1*hKjkdywcXw23cfKv0BthAg.png" alt="JavaScript reduce vs for loop" class="image--center mx-auto" /></p>
<h3 id="heading-using-sort"><strong>USING SORT()</strong></h3>
<p><strong><em>Definition and Usage</em></strong></p>
<p>The <code>sort()</code> method sorts the items of an array.</p>
<p>The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).</p>
<p>By default, the <code>sort()</code> method sorts the values as strings in alphabetical and ascending order.</p>
<p><strong>Note:</strong> This method changes the original array.</p>
<p><img src="https://miro.medium.com/max/835/1*EUAc8_oldcU-SuXCXIWhEQ.png" alt="JavaScript sort vs for loop" class="image--center mx-auto" /></p>
<h3 id="heading-using-findindex">USING FINDINDEX()</h3>
<p><strong><em>Definition and Usage</em></strong></p>
<p>The <code>findIndex()</code> the method returns the index of the first element in an array that passes a test (provided as a function).</p>
<p>The <code>findIndex()</code> the method executes the function once for each element present in the array:</p>
<ul>
<li><p>If it finds an array element where the function returns a <em>true</em> value, <code>findIndex()</code> returns the index of that array element (and does not check the remaining values)</p>
</li>
<li><p>Otherwise, it returns -1</p>
</li>
</ul>
<p><strong>Note:</strong> <code>findIndex()</code> does not execute the function for array elements without values.</p>
<p><strong>Note:</strong> <code>findIndex()</code> does not change the original array.</p>
<p><img src="https://miro.medium.com/max/664/1*xRsIIvQEq34zXa6dM9zI8Q.png" alt="JavaScript findIndex vs for loop" class="image--center mx-auto" /></p>
<p>In conclusion, these six new array functions in ES6 provide a powerful and convenient set of tools for working with arrays in JavaScript. They allow you to perform common array operations with greater ease and make your code more concise and readable. Whether you're just starting out with JavaScript or are an experienced developer, it's worth taking some time to learn these functions and incorporate them into your workflow.</p>
<p>Thank you for reading!</p>
<div class="hn-embed-widget" id="youtube"></div>]]></content:encoded></item></channel></rss>