<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mavis</title>
    <description>The latest articles on DEV Community by Mavis (@mavis_chen).</description>
    <link>https://dev.to/mavis_chen</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1004224%2F9afa54cc-84a9-47dd-a559-7843e2ddf19a.jpeg</url>
      <title>DEV Community: Mavis</title>
      <link>https://dev.to/mavis_chen</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mavis_chen"/>
    <language>en</language>
    <item>
      <title>Auth0 in React and Node</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Mon, 27 Feb 2023 04:15:45 +0000</pubDate>
      <link>https://dev.to/mavis_chen/auth0-in-react-and-node-38o0</link>
      <guid>https://dev.to/mavis_chen/auth0-in-react-and-node-38o0</guid>
      <description>&lt;p&gt;I recently implemented Auth0 in my personal side project. If you're interested in learning how to implement it in React and Node, feel free to take a look.&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/xychenxy" rel="noopener noreferrer"&gt;
        xychenxy
      &lt;/a&gt; / &lt;a href="https://github.com/xychenxy/pirate-shopping" rel="noopener noreferrer"&gt;
        pirate-shopping
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;pirate-shopping&lt;/h1&gt;

&lt;/div&gt;
&lt;p&gt;The pirate shopping project is one of my side projects that allows me to keep adding some tech to advance my skillset.&lt;/p&gt;
&lt;br&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;To do list breakdown&lt;/h2&gt;

&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Deploy to AWS instead of Netlify, &lt;a href="https://www.pirate-in-melbourne.com/" rel="nofollow noopener noreferrer"&gt;https://www.pirate-in-melbourne.com/&lt;/a&gt; [Done]&lt;/li&gt;
&lt;li&gt;Setup github actions, to push docker images to AWS ECR [Done]&lt;/li&gt;
&lt;li&gt;Auth0 [Done]&lt;/li&gt;
&lt;/ul&gt;
&lt;br&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Tech&lt;/h2&gt;

&lt;/div&gt;
&lt;div class="markdown-heading"&gt;
&lt;h3 class="heading-element"&gt;Front-end&lt;/h3&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;React 18&lt;/code&gt;, &lt;code&gt;vite&lt;/code&gt;, &lt;code&gt;TypeScript&lt;/code&gt;, &lt;code&gt;Redux&lt;/code&gt;, &lt;code&gt;Hooks&lt;/code&gt;, &lt;code&gt;Firebase&lt;/code&gt;, &lt;code&gt;Auth0 Login&lt;/code&gt;, &lt;code&gt;CSS-in-JS&lt;/code&gt;&lt;/p&gt;
&lt;div class="markdown-heading"&gt;
&lt;h3 class="heading-element"&gt;Backend&lt;/h3&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;Node/Express framework&lt;/code&gt;&lt;/p&gt;
&lt;div class="markdown-heading"&gt;
&lt;h3 class="heading-element"&gt;Others&lt;/h3&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;AWS&lt;/code&gt;, &lt;code&gt;Docker&lt;/code&gt;, &lt;code&gt;GitHub Action&lt;/code&gt;, &lt;code&gt;Netlify&lt;/code&gt;&lt;/p&gt;
&lt;br&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;How to run it&lt;/h2&gt;

&lt;/div&gt;
&lt;p&gt;Please make sure &lt;strong&gt;docker&lt;/strong&gt; have already installed.&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;./run_docker.sh dev|prod&lt;/code&gt;&lt;/p&gt;
&lt;div class="markdown-heading"&gt;
&lt;h2 class="heading-element"&gt;Production&lt;/h2&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;docker build . -t xychenxy/pirate-shopping&lt;/code&gt;
&lt;code&gt;docker run -it -p 5000:5000 -e "NODE_ENV=production" xychenxy/pirate-shopping&lt;/code&gt;&lt;/p&gt;
&lt;/div&gt;



&lt;/div&gt;
&lt;br&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/xychenxy/pirate-shopping" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;OAuth 2.0&lt;/strong&gt; is the industry-standard protocol for authorization. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. Ref from &lt;a href="https://oauth.net/2/" rel="noopener noreferrer"&gt;https://oauth.net/2/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Auth0&lt;/strong&gt; is a software product that implement the OAuth 2.0 protocol. &lt;/p&gt;
&lt;/blockquote&gt;



&lt;h3&gt;
  
  
  The flow
&lt;/h3&gt;

&lt;p&gt;The graph below illustrates that the client will receive two types of tokens (access and refresh) from the Authorization Server. The access token serves to protect the client's resources, while the refresh token enables the client to obtain new access and refresh tokens.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhp7e6jv1jojzboss13nm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhp7e6jv1jojzboss13nm.png" alt="A pie chart showing 40% responded "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's see how to implement auth0 in react and node
&lt;/h3&gt;

&lt;h4&gt;
  
  
  React side
&lt;/h4&gt;

&lt;p&gt;In react codebase, install @auth0/auth0-react&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;Auth0Provider&lt;/span&gt;
    &lt;span class="nx"&gt;domain&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;meta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;VITE_AUTH0_DOMAIN&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nx"&gt;clientId&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;meta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;VITE_AUTH0_CLIENT_ID&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nx"&gt;authorizationParams&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{{&lt;/span&gt;
        &lt;span class="na"&gt;redirect_uri&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;window&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;location&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;origin&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;audience&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;meta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;VITE_AUTH0_AUDIENCE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}}&lt;/span&gt;
    &lt;span class="nx"&gt;onRedirectCallback&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;onRedirectCallback&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="c1"&gt;// scope="read:current_user"&lt;/span&gt;
&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;children&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/Auth0Provider&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You also can use &lt;code&gt;getAccessTokenSilently()&lt;/code&gt; to get new access token, see below example. &lt;/p&gt;

&lt;p&gt;For some protected resources requests, make sure adding Bearer token into your request&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="nx"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nl"&gt;Authorization&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;`Bearer token`&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; 


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fetchAccessToken&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;newAccessToken&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getAccessTokenSilently&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
                &lt;span class="na"&gt;authorizationParams&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="na"&gt;audience&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;meta&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;VITE_AUTH0_AUDIENCE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="na"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;read:current_user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="p"&gt;});&lt;/span&gt;

            &lt;span class="nx"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;token&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;newAccessToken&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;};&lt;/span&gt;
        &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;isAuthenticated&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;fetchAccessToken&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="na"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;error&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;getAccessTokenSilently&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;isAuthenticated&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  Node side
&lt;/h4&gt;

&lt;p&gt;In node codebase, &lt;code&gt;express-jwt&lt;/code&gt; and &lt;code&gt;jwks-rsa&lt;/code&gt; are useful to do the jwt check with auth0:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;jwtCheck&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;jwt&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="na"&gt;secret&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;jwks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;expressJwtSecret&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="na"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;rateLimit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;jwksRequestsPerMinute&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;jwksUri&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;`https://&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;auth0_domain&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/.well-known/jwks.json`&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}),&lt;/span&gt;
    &lt;span class="na"&gt;audience&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;audience&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;issuer&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;`https://&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;auth0_domain&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;/`&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;algorithms&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;RS256&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Sometimes, if you want to get user info, it's not a good idea to put user info in your request, we can do it in this way:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;p&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;userInfo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;axios&lt;/span&gt;&lt;br&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;&lt;code&gt;https://&amp;lt;/span&amp;gt;&amp;lt;span class="p"&amp;gt;${&amp;lt;/span&amp;gt;&amp;lt;span class="nx"&amp;gt;process&amp;lt;/span&amp;gt;&amp;lt;span class="p"&amp;gt;.&amp;lt;/span&amp;gt;&amp;lt;span class="nx"&amp;gt;env&amp;lt;/span&amp;gt;&amp;lt;span class="p"&amp;gt;.&amp;lt;/span&amp;gt;&amp;lt;span class="nx"&amp;gt;auth0_domain&amp;lt;/span&amp;gt;&amp;lt;span class="p"&amp;gt;}&amp;lt;/span&amp;gt;&amp;lt;span class="s2"&amp;gt;/userinfo&lt;/code&gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
        &lt;span class="na"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
            &lt;span class="na"&gt;Authorization&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;authorization&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;br&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;&lt;br&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;&lt;br&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;br&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Summary&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;Auth0 is a great product that allows us to implement authentication process quickly. Why not give it a try?&lt;/p&gt;

</description>
      <category>auth0</category>
      <category>react</category>
      <category>node</category>
    </item>
    <item>
      <title>React Virtual DOM and DOM Diff</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Fri, 10 Feb 2023 00:34:00 +0000</pubDate>
      <link>https://dev.to/mavis_chen/react-virtual-dom-and-dom-diff-18f9</link>
      <guid>https://dev.to/mavis_chen/react-virtual-dom-and-dom-diff-18f9</guid>
      <description>&lt;p&gt;Virtual DOM works by using JS objects to simulate the nodes of the DOM. At the early stage of building React, Facebook introduced virtual DOM in consideration of factors such as improving code abstraction ability, avoiding artificial DOM operation and reducing the overall risk of code.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  How it works?
&lt;/h3&gt;

&lt;p&gt;The process likes that use &lt;strong&gt;createElement&lt;/strong&gt; to build &lt;strong&gt;virtual dom&lt;/strong&gt;, and it return a plain object that describes its tag type, props properties, children, and so on. These Plain objects form a virtual DOM tree through a tree structure.&lt;br&gt;
 &lt;br&gt;
&lt;strong&gt;render&lt;/strong&gt; function converts virtual dom into real dom, and mount real dom, like &lt;code&gt;document.getElementById("root").appendChild(realDom)&lt;/code&gt;.&lt;br&gt;
 &lt;br&gt;
When the status changes, There's &lt;strong&gt;diff&lt;/strong&gt; functions to compare the difference of the virtual DOM tree before and after the change. Let's have a look below two graphs. There's four different places.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F68gvprpyjodfb5g3v0ex.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F68gvprpyjodfb5g3v0ex.png" alt="A pie chart showing 40% responded " width="800" height="531"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4uu8cx4q0h9ubyj69a6h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4uu8cx4q0h9ubyj69a6h.png" alt="A pie chart showing 40% responded " width="800" height="530"&gt;&lt;/a&gt;&lt;br&gt;
The &lt;strong&gt;diff&lt;/strong&gt; function returns an object, includes all different nodes information, we can call it &lt;strong&gt;patches&lt;/strong&gt;.&lt;br&gt;
 &lt;br&gt;
&lt;strong&gt;doPatch&lt;/strong&gt; function bases on patches objects, will patch one by one on real dom.&lt;/p&gt;


&lt;h4&gt;
  
  
  Code snap examples
&lt;/h4&gt;
&lt;h5&gt;
  
  
  How createElement looks like?
&lt;/h5&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Element {
    constructor(type, props, children) {
        this.type = type;
        this.props = props;
        this.children = children;
    }
}

function createElement(type, props, children) {
    return new Element(type, props, children);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;More definitions about React.createElement &lt;/p&gt;
&lt;div class="crayons-card c-embed text-styles text-styles--secondary"&gt;
      &lt;div class="c-embed__cover"&gt;
        &lt;a href="https://react.dev/reference/react/createElement" class="c-link s:max-w-50 align-middle" rel="noopener noreferrer"&gt;
          &lt;img alt="" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Freact.dev%2Fimages%2Fog-reference.png" height="420" class="m-0" width="800"&gt;
        &lt;/a&gt;
      &lt;/div&gt;
    &lt;div class="c-embed__body"&gt;
      &lt;h2 class="fs-xl lh-tight"&gt;
        &lt;a href="https://react.dev/reference/react/createElement" rel="noopener noreferrer" class="c-link"&gt;
          createElement – React
        &lt;/a&gt;
      &lt;/h2&gt;
      &lt;div class="color-secondary fs-s flex items-center"&gt;
          &lt;img alt="favicon" class="c-embed__favicon m-0 mr-2 radius-0" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Freact.dev%2Ffavicon-32x32.png" width="32" height="32"&gt;
        react.dev
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;


&lt;h5&gt;
  
  
  How virtual dom looks like?
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const oldVDom = createElement(
    "ul",
    {
        class: "ul",
        style: "width: 400px; height: 400px; background-color: pink;",
    },
    [
        createElement(
            "li",
            {
                class: "li-wrap",
                "data-index": 0,
            },
            [
                createElement(
                    "p",
                    {
                        class: "text",
                    },
                    ["The first tag"]
                ),
            ]
        ),
        createElement(
            "li",
            {
                class: "li-wrap",
                "data-index": 1,
            },
            [
                createElement(
                    "p",
                    {
                        class: "text",
                    },
                    [
                        createElement(
                            "span",
                            {
                                class: "span",
                            },
                            ["The second li tag, will be removed later on."]
                        ),
                    ]
                ),
            ]
        ),
        createElement(
            "li",
            {
                class: "li-wrap",
                "data-index": 2,
            },
            ["The third tag"]
        ),
    ]
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  How real dom looks like?
&lt;/h5&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9sfnbliqzh52lbbji14r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9sfnbliqzh52lbbji14r.png" alt="A pie chart showing 40% responded " width="800" height="212"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h5&gt;
  
  
  How render function looks like?
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function render(vDom) {
    // destructure virtual dom
    const { type, props, children } = vDom;
    // transform type
    const el = document.createElement(type);
    // transform all props
    for (let key in props) {
        // transform different attributes
        setAttrs(el, key, props[key]);
    }

    children.map((c) =&amp;gt; {
        // recursive, if child is Element, then call render function again
        // break condition is if child is not Element
        c = c instanceof Element ? render(c) : document.createTextNode(c);
        el.appendChild(c);
    });

    return el;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  How to mount real dom?
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function renderDom(rDom, rootEl) {
    rootEl.appendChild(rDom);
}
renderDom(rDom, document.getElementById("root"));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  How patches look like?
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const patches = {
    0: [
        {
            type: "ATTR",
            attrs: {
                class: "ul-wrap",
            },
        },
    ],
    3: [
        {
            type: "TEXT",
            text: "Update the first tag",
        },
    ],
    6: [
        {
            type: "REMOVE",
            index: 6,
        },
    ],
    7: [
        {
            type: "REPLACE",
            newNode: newNode,
        },
    ],
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  How domDiff look like?
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let patches = {};
let vnIndex = 0;

function domDiff(oldVDom, newVDom) {
    let index = 0;
    vNodeWalk(oldVDom, newVDom, index);
    return patches;
}

function vNodeWalk(oldNode, newNode, index) {
    let vnPatch = [];

    /**
     * node can be
     *  Element {type:'', props:{}, children: []}
     *  text string
     *  null
     */
    if (!newNode) {
        // item was removed
        vnPatch.push({
            type: REMOVE,
            index,
        });
    } else if (typeof oldNode === "string" &amp;amp;&amp;amp; typeof oldNode === "string") {
        // text change
        if (oldNode != newNode) {
            vnPatch.push({
                type: TEXT,
                text: newNode,
            });
        }
    } else if (oldNode.type === newNode.type) {
        const attrPatch = attrsWalk(oldNode.props, newNode.props);

        if (Object.keys(attrPatch).length &amp;gt; 0) {
            vnPatch.push({
                type: ATTR,
                attrs: attrPatch,
            });
        }

        childrenWalk(oldNode.children, newNode.children);
    } else {
        vnPatch.push({
            type: REPLACE,
            newNode,
        });
    }

    if (vnPatch.length &amp;gt; 0) {
        patches[index] = vnPatch;
    }
}

function childrenWalk(oldChildren, newChildren) {
    oldChildren.map((child, index) =&amp;gt; {
        vNodeWalk(child, newChildren[index], ++vnIndex);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  How doPatch looks like?
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let finalPatches = {};
let rnIndex = 0;

function doPatch(rDom, patches) {
    finalPatches = patches;
    rNodeWalk(rDom);
}

function rNodeWalk(rNode) {
    const rnPatch = finalPatches[rnIndex++];
    const childNodes = rNode.childNodes;

    [...childNodes].map((child) =&amp;gt; {
        rNodeWalk(child);
    });

    if (rnPatch) {
        patchAction(rNode, rnPatch);
    }
}

function patchAction(rNode, rnPatch) {
    rnPatch.map((patch) =&amp;gt; {
        switch (patch.type) {
            case ATTR:
                for (let key in patch.attrs) {
                    const value = patch.attrs[key];
                    if (value) {
                        setAttrs(rNode, key, value);
                    } else {
                        rNode.removeAttribute(key);
                    }
                }
                break;
            case TEXT:
                rNode.textContent = patch.text;
                break;
            case REPLACE:
                const newNode =
                    patch.newNode instanceof Element
                        ? render(patch.newNode)
                        : document.createTextNode(patch.newNode);
                rNode.parentNode.replaceChild(newNode, rNode);
                break;
            case REMOVE:
                rNode.parentNode.removeChild(rNode);
                break;
            default:
                break;
        }
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>motivation</category>
    </item>
    <item>
      <title>Closures In JavaScript</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Wed, 08 Feb 2023 04:23:47 +0000</pubDate>
      <link>https://dev.to/mavis_chen/closures-in-javascript-5f16</link>
      <guid>https://dev.to/mavis_chen/closures-in-javascript-5f16</guid>
      <description>&lt;h3&gt;
  
  
  Definition from MDN
&lt;/h3&gt;

&lt;p&gt;A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.&lt;/p&gt;

&lt;h4&gt;
  
  
  Playground
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sayHi = () =&amp;gt; {
    const name = 'Nic'
    function sayIt(){console.log(`Hi, ${name}`)}
    return sayIt
}
const sayWhat = sayHi()
sayWhat() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In above case, what happen when call &lt;code&gt;sayWhat()&lt;/code&gt;, the result is  &lt;code&gt;Hi, Nic&lt;/code&gt;.&lt;br&gt;
If a function return something which have some references to this function scope variables, then the variables will be moved to &lt;code&gt;closure box&lt;/code&gt; instead of collecting by garbage. &lt;br&gt;
As &lt;code&gt;sayHi&lt;/code&gt; contain &lt;code&gt;sayIt&lt;/code&gt;, and &lt;code&gt;sayIt&lt;/code&gt; is executed when  &lt;code&gt;sayWhat&lt;/code&gt; was called. Then the variable &lt;code&gt;name&lt;/code&gt; in the &lt;code&gt;sayHi&lt;/code&gt; will be removed to closure box as it's used in &lt;code&gt;sayIt&lt;/code&gt;. when &lt;code&gt;sayIt&lt;/code&gt; is executed, it will look for the &lt;code&gt;name&lt;/code&gt; in its scope first, if cannot find it, then go to outer closure box to search. That's how closure works.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sayHi = () =&amp;gt; {
    setTimeout(() =&amp;gt; {console.log(name)}, 4000)
    const name = 'Oodie'
}
sayHi() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In above case, what happen when call &lt;code&gt;sayHi()&lt;/code&gt;, the result is  &lt;code&gt;Oodie&lt;/code&gt;. The explanation is the same as above. &lt;/p&gt;
&lt;h3&gt;
  
  
  What's the benefit from closures
&lt;/h3&gt;
&lt;h4&gt;
  
  
  Memory Efficient
&lt;/h4&gt;

&lt;p&gt;In below case, every time we call &lt;strong&gt;heavyDuty&lt;/strong&gt; function, we need to create a memory to store bigArray, as we call it many times, so it's kind of waste our memory. You may say, we can create big array outside of &lt;code&gt;heavyDuty&lt;/code&gt; function. But that will pollute the global scope. That's why we apply closure here.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function heavyDuty(index){
    const bigArray = new Array(10000).fill('I am a big array')
    console.log('created!')
    return bigArray[index]
}
heavyDuty(8888) // created
heavyDuty(8888) // created
heavyDuty(8888) // created
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Let apply &lt;strong&gt;closure&lt;/strong&gt; to above case. We only need to create big array one time. And we can use it anywhere and anytime.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function heavyDutyWithClosure(){
    const bigArray = new Array(10000).fill('silly')
    console.log('created!')
    return function(index){
            // bigArray will always refer to outside bigArray
            return bigArray[index]
        }
}
const getHeavyDuty = heavyDutyWithClosure()
getHeavyDuty(8888)() // created
getHeavyDuty(8888)()
getHeavyDuty(8888)() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Encapsulation
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const makeNuclearButton = () =&amp;gt; {
    let timeWithoutDesctruction = 0;
    const passTime = () =&amp;gt; timeWithoutDesctruction++;
    const totalPeaceTime = () =&amp;gt; timeWithoutDesctruction++;
    const launch = () =&amp;gt; {
        timeWithoutDesctruction = -1;
        return "boom";
    };
    setInterval(passTime, 1000);

    return {
        launch: launch,
        totalPeaceTime: totalPeaceTime,
    };
};
const ohno = makeNuclearButton();
console.log(ohno.totalPeaceTime()); // 0
// after 10 second, execute this
console.log(ohno.totalPeaceTime()); // 10
// after 2 second, execute this
console.log(ohno.totalPeaceTime()); // 12, as setInterval is working
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In above case, you can not change timeWithoutDesctruction, but can get it.&lt;br&gt;
what if we don't want you to get launch function? just remove it from return object.&lt;/p&gt;
&lt;h4&gt;
  
  
  Exercise
&lt;/h4&gt;

&lt;p&gt;Try to convert them by using closures.&lt;br&gt;
Q1&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let view
function initialize(){
    view = 'boom'
    console.log('view has been set!')
}
initialize() // view has been set!
initialize() // view has been set!
initialize() // view has been set!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Result&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let view
function initialize(){
    let called = 0
    return function(){
        if(called &amp;gt; 0){
            return;
        }else{
            view = 'boom'
            console.log('view has been set!')
            called++
        }
    }

}
const startOnce = initialize() 
startOnce() // view has been set!
startOnce()
startOnce()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Q2&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1,2,3,4]
for(var i=0; i&amp;lt;array.length; i++){
    setTimeout(function(){console.log('I am at index ' + i)}, 3000)
}
// I am at index 4
// I am at index 4
// I am at index 4
// I am at index 4, as var do not have block scope
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Result&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// easy way to fix them by keyword let
const array = [1,2,3,4]
for(let i=0; i&amp;lt;array.length; i++){
    setTimeout(function(){console.log('I am at index ' + i)}, 3000)
}
// I am at index 0
// I am at index 1
// I am at index 2
// I am at index 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// easy way to fix them by keyword let
const array = [1,2,3,4]
for(var i=0; i&amp;lt;array.length; i++){
    setTimeout(function(){console.log('I am at index ' + i)}, 3000)
}
// I am at index 0
// I am at index 1
// I am at index 2
// I am at index 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// let fix it by using IIFE
const array = [1,2,3,4]
for(var i=0; i&amp;lt;array.length; i++){
  (function(closureI){setTimeout(function() {console.log(closureI)})})(i)
}
// I am at index 0
// I am at index 1
// I am at index 2
// I am at index 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Learn more about the IIFE&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="/mavis_chen" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jwF6bV4I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--P_6WfbIB--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/1004224/9afa54cc-84a9-47dd-a559-7843e2ddf19a.jpeg" alt="mavis_chen"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/mavis_chen/javascript-function-types-47p4" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;JavaScript Function Types&lt;/h2&gt;
      &lt;h3&gt;Mavis ・ Feb 6 ・ 1 min read&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Higher Order Function in JavaScript</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Wed, 08 Feb 2023 02:50:52 +0000</pubDate>
      <link>https://dev.to/mavis_chen/higher-order-function-in-javascript-2omo</link>
      <guid>https://dev.to/mavis_chen/higher-order-function-in-javascript-2omo</guid>
      <description>&lt;p&gt;&lt;strong&gt;Higher Order Function&lt;/strong&gt; (HOF) is a function that can take a function as an argument or a function that return another function.&lt;/p&gt;

&lt;p&gt;Array.map is HOF, in below case, map receive an arrow function as an argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['cat', 'dog', 'bird'].map(animal =&amp;gt; `Hi, ${animal}`)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Let's have a look another example
&lt;/h5&gt;

&lt;p&gt;This function take &lt;code&gt;num1&lt;/code&gt; as an argument, then return a function &lt;code&gt;function (num2) {return num1 * num2}&lt;/code&gt;. So it's HOF.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiplyBy = function (num1){
        return function (num2) {
            return num1 * num2
        }
}
const multiplyByTwo = multiplyBy(2)
const multiplyByFive = multiplyBy(5)
multiplyByTwo(5) // 10
multiplyByFive(5) // 25
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's convert above method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiplyBy = num1 =&amp;gt; num2 =&amp;gt;  num1 * num2
multiplyBy(2)(5) // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>web3</category>
      <category>announcement</category>
      <category>community</category>
      <category>devto</category>
    </item>
    <item>
      <title>Types in JavaScript</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Wed, 08 Feb 2023 02:00:55 +0000</pubDate>
      <link>https://dev.to/mavis_chen/types-in-javascript-4p1b</link>
      <guid>https://dev.to/mavis_chen/types-in-javascript-4p1b</guid>
      <description>&lt;h4&gt;
  
  
  Primitive types
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typeof 5 // number
typeof true // boolean
typeof 'wow' // string
typeof undefined // undefined
typeof null // object
typeof Symbol('just me') // symbol since es6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Non-Primitive types
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typeof {} // object
typeof [] // object
typeof function(){} // functio
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Playground
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Primitive is pass by value&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In below case, variable a have an address refer to somewhere that memory hold value 5.&lt;br&gt;
&lt;code&gt;let b = a&lt;/code&gt; means it will copy &lt;strong&gt;value 5&lt;/strong&gt;, and create a new memory for it to store, then b refer to this new memory location.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjtl4rplmxygsormz4210.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjtl4rplmxygsormz4210.png" alt="A pie chart showing 40% responded " width="800" height="524"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let a = 5
let b = a
console.log(a) // 5
console.log(b) // 5
b = 10
console.log(a) // 5
console.log(b) // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Non-Primitive is pass by reference&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;code&gt;obj2 = obj1&lt;/code&gt; means  obj2 will refer to obj1 address.&lt;br&gt;
so that obj1 and obj2 point to the same location where object store in memory&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnw4myd1l9hs1tvklll30.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnw4myd1l9hs1tvklll30.png" alt="A pie chart showing 40% responded " width="800" height="399"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let obj1 = {name:'hui', password:'123'}
let obj2 = obj1
obj2.password = '456'
console.log(obj1) // 456
console.log(obj1) // 456
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>devto</category>
      <category>announcement</category>
      <category>cryptocurrency</category>
      <category>blockchain</category>
    </item>
    <item>
      <title>Call, Apply, Bind in JavaScript</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Wed, 08 Feb 2023 00:27:41 +0000</pubDate>
      <link>https://dev.to/mavis_chen/call-apply-bind-in-javascript-aom</link>
      <guid>https://dev.to/mavis_chen/call-apply-bind-in-javascript-aom</guid>
      <description>&lt;h3&gt;
  
  
  Definitions
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Call&lt;/strong&gt; method is used to change the context of the invoke function. In other words, to change the keyword &lt;code&gt;this&lt;/code&gt; inside the function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Apply&lt;/strong&gt; method is similar to Call, the only different is that Apply method can receive an array as argument.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bind&lt;/strong&gt; method will return a new function - bind function. The keyword &lt;code&gt;this&lt;/code&gt; will refer to the first argument.&lt;/p&gt;

&lt;h3&gt;
  
  
  Examples
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Call
&lt;/h4&gt;

&lt;p&gt;In below case, archer only have two properties, name and health. He want to use heal() method to manager him health for temporary. So he don't need to create a new heal function, he can use &lt;code&gt;call&lt;/code&gt; method to borrow &lt;code&gt;heal()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const wizard = {
    name: 'Merlin',
    health: 50,
    heal(){
        return this.health = 100
    }
}
const archer = {
    name :'Robin',
    health: 30
}
console.log('1', archer) // {name: 'Robin', health: 30}
wizard.heal.call(archer) // this in heal() point to archer
console.log('2', archer) // {name: 'Robin', health: 100}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const wizard = {
    name: 'Merlin',
    health: 50,
    heal(num1, num2){
        return this.health += num1 + num2
    }
}
const archer = {
    name :'Robin',
    health: 30
}
console.log('1', archer) // {name: 'Robin', health: 30}
wizard.heal.call(archer, 50, 30) // this in heal() point to archer
console.log('2', archer) // {name: 'Robin', health: 110}
wizard.heal.call(archer, 50, 30, 100) // only take the first two


wizard.heal.call(archer, 50) // if only put 1 parameter
console.log('2', archer) // {name: 'Robin', health: NaN}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Apply
&lt;/h4&gt;

&lt;p&gt;Similar to &lt;code&gt;Call&lt;/code&gt;, the only different is that receive an array as argument&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const wizard = {
    name: 'Merlin',
    health: 50,
    heal(num1, num2){
        return this.health += num1 + num2
    }
}
const archer = {
    name :'Robin',
    health: 30
}
console.log('1', archer) // {name: 'Robin', health: 30}
wizard.heal.apply(archer, [50, 30]) // this in heal() point to archer
console.log('2', archer) // {name: 'Robin', health: 110}

wizard.heal.apply(archer, 50) // type error, only accept array
wizard.heal.apply(archer, [50,50,50]) // only pick the first two
wizard.heal.apply(archer, [50]) // NaN, at least 2 parameter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Bind
&lt;/h4&gt;

&lt;p&gt;fun fact, archer wants to borrow a &lt;code&gt;heal()&lt;/code&gt; from wizard, but he want to use it later on. So he can use &lt;code&gt;bind&lt;/code&gt; method, as &lt;code&gt;bind method&lt;/code&gt; will return a new function, he can use it whenever he wants.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const wizard = {
    name: 'Merlin',
    health: 50,
    heal(num1, num2){
        return this.health += num1 + num2
    }
}
const archer = {
    name :'Robin',
    health: 30
}
console.log('1', archer) // {name: 'Robin', health: 30}
// bind will return a function
const healArcher = wizard.heal.bind(archer, 50, 30) 
healArcher() // {name: 'Robin', health: 110}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Summary
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;ol&gt;
&lt;li&gt;call and apply are useful for borrowing methods from an object&lt;/li&gt;
&lt;li&gt;bind is useful for call function later on&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;this&lt;/code&gt; always refer to who want to borrow or bind other function&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

</description>
      <category>announcement</category>
      <category>devto</category>
      <category>web3</category>
    </item>
    <item>
      <title>Function scope vs Block scope</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Tue, 07 Feb 2023 11:33:24 +0000</pubDate>
      <link>https://dev.to/mavis_chen/function-scope-vs-block-scope-197e</link>
      <guid>https://dev.to/mavis_chen/function-scope-vs-block-scope-197e</guid>
      <description>&lt;h4&gt;
  
  
  Function Scope
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;When declare a variable inside a function, it only can be used inside this function, and can not be used outside this function.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  Block Scope
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;When declare a variable inside a {}, it can not be used outside the block.&lt;br&gt;
keyword &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; was introduced since ES6, and provide &lt;strong&gt;Block Scope&lt;/strong&gt; fro JavaScript.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5&gt;
  
  
  Example
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if ( 5 &amp;gt; 4 ) {
    var secrete = '123'
}
console.log(secrete) // 123, as js do not have block scope

function a () {
    var aSecrete = '123'
}
console.log(aSecrete) // Reference error
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function loop(){
    for(var i = 0; i &amp;lt; 5; i++){
        console.log(i)
    }
    console.log('final', i) // i got hoisted
}
loop() // 0, 1, 2, 3, 4, 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function loop(){
    for(let i = 0; i &amp;lt; 5; i++){
        console.log(i)
    }
    console.log('final', i)
}
loop() // Reference Error, i is not defined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>web3</category>
      <category>blockchain</category>
      <category>announcement</category>
      <category>devto</category>
    </item>
    <item>
      <title>this keyword quiz</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Tue, 07 Feb 2023 05:20:38 +0000</pubDate>
      <link>https://dev.to/mavis_chen/this-keyword-quiz-1p0e</link>
      <guid>https://dev.to/mavis_chen/this-keyword-quiz-1p0e</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;In most cases, the value of this&lt;br&gt;
 is determined by how a function is called (runtime binding).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5&gt;
  
  
  Let's have a look some examples
&lt;/h5&gt;

&lt;h6&gt;
  
  
  Q1
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function a(){
  function b(){
    console.log(this) // window
    function c(){
      "use strict";
      console.log(this) // undefined
    }
    c()
  }
  b()
}
a()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a function with strict mode, &lt;code&gt;this&lt;/code&gt; is &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;h6&gt;
  
  
  Q2
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var name = 'A'

function special(){
  console.log(this.name)
}

var girl = {
  name:'B',
  detail: function(){
    console.log(this.name)
  },
  woman: {
    name: 'C',
    detail: function(){
      console.log(this.name)
    }
  },
  special: special
}
girl.detail() // b
girl.woman.detail() // c
girl.special() // b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;girl.detail()&lt;/code&gt;, in detail function, this point to girl object&lt;br&gt;
&lt;code&gt;girl.woman.detail()&lt;/code&gt;, in detail function, this point to woman object&lt;br&gt;
&lt;code&gt;girl.special()&lt;/code&gt;, in special function, this point to girl.&lt;/p&gt;

&lt;h6&gt;
  
  
  Q3
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var name = 'red'

function a(){
  var name = 'white'
  console.log(this.name)
}
function d(i){
  return i()
}
var b = {
  name:'yellow',
  detail: function(){
    console.log(this.name)
  },
  bibi: function(){
    console.log(this.name + 'bibi is called.')
    return function(){
      console.log(this.name)
    }
  }
}
b.detail() // yellow, b call detail function, so 
var c = b.detail
c() // red

b.a = a
a() // red
b.a() // yellow

var e = b.bibi() // yellow bibi is called.
d(b.detail) // red
e() // red
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;b.detail()&lt;/code&gt;, b call detail function, so in detail function scope, this points to object b.&lt;br&gt;
&lt;code&gt;var c = b.detail&lt;/code&gt;, assign detail function to variable c&lt;br&gt;
&lt;code&gt;c()&lt;/code&gt;, in this function, this point to window&lt;br&gt;
&lt;code&gt;var e = b.bibi()&lt;/code&gt;, b.bibi() means execute bibi function, and return a new function to var e.&lt;/p&gt;

&lt;h6&gt;
  
  
  Q4
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
    name: 'xiu',
    sing() {
        return 'lalalal ' + this.name
    },
    singAgain(){
        return this.sing() + this.name
    }
}
obj.sing() // lalalal xiu
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Q5
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function importantPerson(){console.log(this.name)}
const name = 'sunny'
const obj1 = {
    name:'xiu',
    importantPerson:importantPerson
}
const obj2 = {
    name:'gou',
    importantPerson:importantPerson
}
importantPerson() //sunny
obj1.importantPerson() // xiu
obj2.importantPerson() // gou
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Q6
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const a = function(){
    console.log(this) // window
    const b = function(){
        console.log(this) // window
        const c = {
            hi: function(){
                console.log(this) 
            }
        }
        c.hi() // object c, as c call hi function
    }
    b()
}
a()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Q7
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
    name: 'xiu',
    sing() {
           console.log('a', this) // obj
           var anotherFunc = function(){
              console.log('b', this) // window
           }
       anotherFunc()
        }
}
obj.sing()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Q8
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
    name: 'xiu',
    sing() {
           console.log('a', this) // obj
           var anotherFunc = () =&amp;gt; {
              console.log('b', this) // obj
           }
       anotherFunc()
        }
}
obj.sing()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in arrow function, they don't have &lt;code&gt;this&lt;/code&gt; keyword, they inherit it from their parent.&lt;/p&gt;

&lt;h6&gt;
  
  
  Q9
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
    name: 'xiu',
    hobbies: ['coding','sleeping'],
    show() {
        this.hobbies.map((hobby) =&amp;gt; {
           console.log(`${this.name} loves ${hobby}`)})
    },
    showAgain() {
         this.hobbies.map(function(hobby){
           console.log(`${this.name} loves ${hobby}`)
    })}
}
obj.show()
obj.showAgain()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;obj.show()&lt;/code&gt;, as it's arrow function in show(), so this point to obj&lt;br&gt;
&lt;code&gt;obj.showAgain()&lt;/code&gt;, this point to window,&lt;/p&gt;

&lt;h6&gt;
  
  
  Q10
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let f = function(){
    console.log('1',this) \\ window
    const say = () =&amp;gt; {
        console.log('2',this)
    }
    say() \\ window
}
f()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Q11
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const a = {
  say(){
    console.log('a',this)
    const b = function(){
      console.log('b', this)
      const f = () =&amp;gt; {
        console.log('f',this)
      }
      f()
    }
    b()
    const d = () =&amp;gt; {
      console.log('d', this)
    }
    d()
  },
}
a.say()

// a: a
// b: window
// f: window
// d: a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Hoisting quiz</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Mon, 06 Feb 2023 12:42:09 +0000</pubDate>
      <link>https://dev.to/mavis_chen/hoisting-quiz-l50</link>
      <guid>https://dev.to/mavis_chen/hoisting-quiz-l50</guid>
      <description>&lt;p&gt;There are some fun hoisting quiz here, and I will keep adding more. Not only focusing the result, but also trying to understand why. Here's article may help you understand &lt;code&gt;Execution Context&lt;/code&gt; and &lt;code&gt;Hoisting&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__link"&gt;
  &lt;a href="/mavis_chen" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jwF6bV4I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--P_6WfbIB--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/1004224/9afa54cc-84a9-47dd-a559-7843e2ddf19a.jpeg" alt="mavis_chen"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="/mavis_chen/execution-context-in-javascript-gic" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Execution Context in JavaScript&lt;/h2&gt;
      &lt;h3&gt;Mavis ・ Feb 7 ・ 3 min read&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


&lt;p&gt;Q1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('1')
console.log(teddy)
var teddy = 'bear'
function sing() {console.log('ohhh la la')}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
1&lt;br&gt;
undefined&lt;/p&gt;

&lt;p&gt;Q2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('1')
console.log(teddy)
console.log(sing())
var teddy = 'bear'
function sing() {console.log('ohhh la la')}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
1&lt;br&gt;
undefined&lt;br&gt;
ohhh la la // as function declaration are hoisted&lt;br&gt;
undefined // ignore, as there's 2 console.log()&lt;/p&gt;

&lt;p&gt;Q3&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('1')
console.log(teddy)
console.log(sing())
var teddy = 'bear'
(function sing() {console.log('ohhh la la')})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
1&lt;br&gt;
undefined&lt;br&gt;
ReferenceError: sing is not defined // as it see bracket then fn, JavaScript engine doesn't hoist it.&lt;/p&gt;

&lt;p&gt;Q4&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('1')
console.log(teddy)
let teddy = 'bear' // change it to let or const
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
1&lt;br&gt;
ReferenceError: teddy is not defined // keyword let | const do not hoist&lt;/p&gt;

&lt;p&gt;Q5&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(sing())
console.log(sing2)

// function expression
var sing2 = function() {console.log('uhhh la la')}

// function declaration
function sing() {console.log('ohhh la la')}

console.log(sing2())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
ohhh la la&lt;br&gt;
undefined //as it see var, so sing2 is undefined&lt;br&gt;
uhhh la la&lt;/p&gt;

&lt;p&gt;Q6&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(sing())
console.log(sing2())

// function expression
var sing2 = function() {console.log('uhhh la la')}

// function declaration
function sing() {console.log('ohhh la la')}

console.log(sing2())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
ohhh la la&lt;br&gt;
undefined //as it see var, so sing2 is undefined&lt;br&gt;
TypeError: sing2 is not a function // sing2 is undefined&lt;/p&gt;

&lt;p&gt;Q7&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var one = 1 // hoisting it to undefined
var one = 2 // ignore it, as one have already hoisted
console.log(one)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
2&lt;/p&gt;

&lt;p&gt;Q8&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(a) 
console.log(a())
a()
function a() {console.log('hi')}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
ƒ a() {console.log('hi')}&lt;br&gt;
hi&lt;br&gt;
undefined&lt;br&gt;
hi&lt;/p&gt;

&lt;p&gt;Q9&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a()
function a() {console.log('hi')}
a()
function a() {console.log('bye')}
a()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
bye // same as var, rewrite content&lt;br&gt;
bye&lt;br&gt;
bye&lt;/p&gt;

&lt;p&gt;Q10&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var favouriteFood = 'grapes'

var foodThoughts = function () {
    console.log('Original favourite food: ' + favouriteFood)
    var favouriteFood = 'sushi'
    console.log("new favourite food: " + favouriteFood)
}

foodThoughts()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
Original favourite food: undefined&lt;br&gt;
Original favourite food: sushi&lt;/p&gt;

&lt;p&gt;Explain&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;creating execution context
hoisting favouriteFood and foodThoughts, all of them are undefined&lt;/li&gt;
&lt;li&gt;execution phrase, favouriteFood is grapes, foodThoughts is equal to a function, then creating a new execution context for it.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;New execution context repeat above in foodThoughts&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;creating execution context
hoisting favouriteFood is undefined&lt;/li&gt;
&lt;li&gt;execution phrase
first is undefined, second is sushi&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Q11&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var favouriteFood = 'grapes'
var foodThoughts = function () {
    console.log('Original favourite food: ' + favouriteFood)
    console.log("new favourite food: " + favouriteFood)
}

foodThoughts()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;======= result ======= &lt;br&gt;
Original favourite food: grapes&lt;br&gt;
Original favourite food: grapes&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>JavaScript Function Types</title>
      <dc:creator>Mavis</dc:creator>
      <pubDate>Mon, 06 Feb 2023 12:06:23 +0000</pubDate>
      <link>https://dev.to/mavis_chen/javascript-function-types-47p4</link>
      <guid>https://dev.to/mavis_chen/javascript-function-types-47p4</guid>
      <description>&lt;ul&gt;
&lt;li&gt;Function declaration&lt;/li&gt;
&lt;li&gt;Function expression&lt;/li&gt;
&lt;li&gt;Arrow function&lt;/li&gt;
&lt;li&gt;Immediately Invoked Function Expression (IIFE)&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Function declaration
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;It starts with keyword function. () is the grouping operator.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function name(){}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Function expression
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;It's used in statements, like assigning a function to a variable.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const great = function () {...}
great()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Arrow function
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;It's introduced since ES6, and used to shorten the code&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const great = () =&amp;gt; {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Immediately Invoked Function Expression (IIFE)
&lt;/h4&gt;

&lt;blockquote&gt;
&lt;p&gt;An IIEF is a JavaScript function that runs as soon as it is defined.&lt;br&gt;
IIFE contains two major parts&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The first is the anonymous functions with lexical scope enclosed within the Grouping Operator. This can avoid polluting the global scope&lt;/li&gt;
&lt;li&gt;The second part creates the immediately invoked function expression (), the JavaScript engine will directly interpret the function
&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(function(){})()
(()=&amp;gt;{})()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
  </channel>
</rss>
