<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Satyendra Kannaujiya on Medium]]></title>
        <description><![CDATA[Stories by Satyendra Kannaujiya on Medium]]></description>
        <link>https://medium.com/@satyendra250896?source=rss-3a09033e9ae4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ca6edef_mxYcPWY5uw-wtQ.jpeg</url>
            <title>Stories by Satyendra Kannaujiya on Medium</title>
            <link>https://medium.com/@satyendra250896?source=rss-3a09033e9ae4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:10:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyendra250896/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrate one drive to your react app]]></title>
            <link>https://medium.datadriveninvestor.com/integrate-one-drive-to-your-react-app-4327aa7d4535?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4327aa7d4535</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sun, 14 May 2023 08:09:06 GMT</pubDate>
            <atom:updated>2023-05-16T02:57:09.206Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*k7Q7aJ5-OsseVheicuU3YQ.jpeg" /><figcaption>image source — <a href="https://www.veryfi.com/">https://www.veryfi.com/</a></figcaption></figure><p>To add the functionality of uploading files from One drive cloud store in your react application you can use One drive File picker by following below steps —</p><p><strong>App registration —</strong></p><p>Before begin file picker integration you should register your application on azure portal (<a href="https://portal.azure.com/">https://portal.azure.com</a>/) .</p><p>On azure portal under app registration section you can create register new application and and take note of tenant-id and application id.</p><p>Some important configuration of azure portal -</p><p>Platform —</p><p>Under platform section you must select SPA .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6BzXEvzP9xE0XzBIkow7g.png" /></figure><p>Implicit grant and hybrid flows —</p><p>For implicit grant and hybrid flows select both token types -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuzGl9cAyE44XQAaHPn6hw.png" /></figure><p>Supported account types -</p><p>For supported account type select organisational directory and personal microsoft account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-s5uXpVZdjcgJ9ExrRhdQ.png" /></figure><p>Also provide relevant permission in API permission section.</p><p>Azure configuration is done.</p><p>Create a component named as OneDrive and initialise app , here I am using msal for authentication .</p><pre>import React, {useEffect, useState} from &quot;react&quot;;<br><br>export const OneDrive = (props) =&gt; {<br>     const [app, setApp] = useState(null);<br>    const baseUrl = &quot;https://onedrive.live.com/picker&quot;;<br>    const authority = &quot;https://login.microsoftonline.com/consumers&quot;;<br>    const redirectUri = &quot;localhost:3000&quot; ; // your web url<br>    const clientId = &quot;&lt;your-client-id&gt;;<br>    useEffect(() =&gt; {<br>        const script = document.createElement(&quot;script&quot;);<br>        script.src = &quot;https://alcdn.msauth.net/browser/2.19.0/js/msal-browser.min.js&quot;;<br>        script.async = true;<br>        script.onload = apiLoaded;<br>        document.body.appendChild(script);<br>        return () =&gt; {<br>            document.body.removeChild(script);<br>        };<br>    }, []);<br><br>     const apiLoaded = () =&gt; {<br>        setApp(new msal.PublicClientApplication(msalParams));<br>    };<br>    <br>    return (<br>        &lt;span id=&quot;original-tab-id&quot;&gt;<br>           <br>            &lt;button onClick={(e) =&gt; {<br>                launchPicker(e); <br>            }}&gt;One drive&lt;/button&gt;<br>        &lt;/span&gt;<br>    ); <br>};</pre><p>Now write launch picker function to open drive picker in a pop up</p><pre><br><br>export const OneDrive = (props) =&gt; {<br>     const [app, setApp] = useState(null);<br>    const baseUrl = &quot;https://onedrive.live.com/picker&quot;;<br>    const authority = &quot;https://login.microsoftonline.com/consumers&quot;;<br>    const redirectUri = &quot;localhost:3000&quot; ; // your web url<br>    const clientId = &quot;&lt;your-client-id&gt;;<br>    useEffect(() =&gt; {<br>        const script = document.createElement(&quot;script&quot;);<br>        script.src = &quot;https://alcdn.msauth.net/browser/2.19.0/js/msal-browser.min.js&quot;;<br>        script.async = true;<br>        script.onload = apiLoaded;<br>        document.body.appendChild(script);<br>        return () =&gt; {<br>            document.body.removeChild(script);<br>        };<br>    }, []);<br><br>     const apiLoaded = () =&gt; {<br>        setApp(new msal.PublicClientApplication(msalParams));<br>    };<br><br> const params = {<br>        sdk: &quot;8.0&quot;,<br>        entry: {<br>            oneDrive: {<br>                files: {}<br>            }<br>        },<br>        authentication: {},<br>        messaging: {<br>            origin: &quot;localhost:3000&quot;,<br>            channelId: &quot;27&quot;<br>        },<br>        typesAndSources: {<br>            mode: &quot;files&quot;,<br>            pivots: {<br>                oneDrive: true,<br>                recent: true<br>            }<br>        }<br>    };<br><br>    let win = null;<br>    let port = null;<br><br>    function combine(...paths) {<br>        return paths<br>            .map(path =&gt; path.replace(/^[\\|/]/, &quot;&quot;).replace(/[\\|/]$/, &quot;&quot;))<br>            .join(&quot;/&quot;)<br>            .replace(/\\/g, &quot;/&quot;);<br>    }<br><br>    async function launchPicker(e) {<br><br>        e.preventDefault();<br><br>        win = window.open(&quot;&quot;, &quot;Picker&quot;, &quot;height=600,width=1200&quot;);<br><br>        const authToken = await getToken();<br><br>        const queryString = new URLSearchParams({<br>            filePicker: JSON.stringify(params)<br>        });<br><br>        const url = `${baseUrl}?${queryString}`;     <br><br>        const form = win.document.createElement(&quot;form&quot;);<br>        form.setAttribute(&quot;action&quot;, url);<br>        form.setAttribute(&quot;method&quot;, &quot;POST&quot;);<br>        win.document.body.append(form);<br><br>        const input = win.document.createElement(&quot;input&quot;);<br>        input.setAttribute(&quot;type&quot;, &quot;hidden&quot;);<br>        input.setAttribute(&quot;name&quot;, &quot;access_token&quot;);<br>        input.setAttribute(&quot;value&quot;, authToken);<br>        form.appendChild(input);<br><br>        form.submit();<br><br>        window.addEventListener(&quot;message&quot;, (event) =&gt; {<br><br>            if (event.source &amp;&amp; event.source === win) {<br><br>                const message = event.data;<br><br>                if (message.type === &quot;initialize&quot; &amp;&amp; message.channelId === params.messaging.channelId) {<br><br>                    port = event.ports[0];<br><br>                    port.addEventListener(&quot;message&quot;, messageListener);<br><br>                    port.start();<br><br>                    port.postMessage({<br>                        type: &quot;activate&quot;<br>                    });<br>                }<br>            }<br>        });<br>    }<br>    <br>    return (<br>        &lt;span id=&quot;original-tab-id&quot;&gt;<br>           <br>            &lt;button onClick={(e) =&gt; {<br>                launchPicker(e); <br>            }}&gt;One drive&lt;/button&gt;<br>        &lt;/span&gt;<br>    ); <br>};</pre><p>Now listen for the message event like — authenticate , close , pick etc</p><pre>import React, {useEffect, useState} from &quot;react&quot;;<br><br>export const OneDrive = (props) =&gt; {<br>     const [app, setApp] = useState(null);<br>    const baseUrl = &quot;https://onedrive.live.com/picker&quot;;<br>    const authority = &quot;https://login.microsoftonline.com/consumers&quot;;<br>    const redirectUri = &quot;localhost:3000&quot; ; // your web url<br>    const clientId = &quot;&lt;your-client-id&gt;;<br>    useEffect(() =&gt; {<br>        const script = document.createElement(&quot;script&quot;);<br>        script.src = &quot;https://alcdn.msauth.net/browser/2.19.0/js/msal-browser.min.js&quot;;<br>        script.async = true;<br>        script.onload = apiLoaded;<br>        document.body.appendChild(script);<br>        return () =&gt; {<br>            document.body.removeChild(script);<br>        };<br>    }, []);<br><br>     const apiLoaded = () =&gt; {<br>        setApp(new msal.PublicClientApplication(msalParams));<br>    };<br><br> const params = {<br>        sdk: &quot;8.0&quot;,<br>        entry: {<br>            oneDrive: {<br>                files: {}<br>            }<br>        },<br>        authentication: {},<br>        messaging: {<br>            origin: &quot;localhost:3000&quot;,<br>            channelId: &quot;27&quot;<br>        },<br>        typesAndSources: {<br>            mode: &quot;files&quot;,<br>            pivots: {<br>                oneDrive: true,<br>                recent: true<br>            }<br>        }<br>    };<br><br>    let win = null;<br>    let port = null;<br><br>    function combine(...paths) {<br>        return paths<br>            .map(path =&gt; path.replace(/^[\\|/]/, &quot;&quot;).replace(/[\\|/]$/, &quot;&quot;))<br>            .join(&quot;/&quot;)<br>            .replace(/\\/g, &quot;/&quot;);<br>    }<br><br>    async function launchPicker(e) {<br><br>        e.preventDefault();<br><br>        win = window.open(&quot;&quot;, &quot;Picker&quot;, &quot;height=600,width=1200&quot;);<br><br>        const authToken = await getToken();<br><br>        const queryString = new URLSearchParams({<br>            filePicker: JSON.stringify(params)<br>        });<br><br>        const url = `${baseUrl}?${queryString}`;     <br><br>        const form = win.document.createElement(&quot;form&quot;);<br>        form.setAttribute(&quot;action&quot;, url);<br>        form.setAttribute(&quot;method&quot;, &quot;POST&quot;);<br>        win.document.body.append(form);<br><br>        const input = win.document.createElement(&quot;input&quot;);<br>        input.setAttribute(&quot;type&quot;, &quot;hidden&quot;);<br>        input.setAttribute(&quot;name&quot;, &quot;access_token&quot;);<br>        input.setAttribute(&quot;value&quot;, authToken);<br>        form.appendChild(input);<br><br>        form.submit();<br><br>        window.addEventListener(&quot;message&quot;, (event) =&gt; {<br><br>            if (event.source &amp;&amp; event.source === win) {<br><br>                const message = event.data;<br><br>                if (message.type === &quot;initialize&quot; &amp;&amp; message.channelId === params.messaging.channelId) {<br><br>                    port = event.ports[0];<br><br>                    port.addEventListener(&quot;message&quot;, messageListener);<br><br>                    port.start();<br><br>                    port.postMessage({<br>                        type: &quot;activate&quot;<br>                    });<br>                }<br>            }<br>        });<br>    }<br>    <br>   async function messageListener(message) {<br>        switch (message.data.type) {<br><br>            case &quot;notification&quot;:<br>                console.log(`notification: ${message.data}`);<br>                break;<br><br>            case &quot;command&quot;:<br><br>                port.postMessage({<br>                    type: &quot;acknowledge&quot;,<br>                    id: message.data.id<br>                });<br><br>                const command = message.data.data;<br><br>                switch (command.command) {<br><br>                    case &quot;authenticate&quot;:<br><br>                        // getToken is from scripts/auth.js<br>                        const token = await getToken();<br><br>                        if (typeof token !== &quot;undefined&quot; &amp;&amp; token !== null) {<br><br>                            port.postMessage({<br>                                type: &quot;result&quot;,<br>                                id: message.data.id,<br>                                data: {<br>                                    result: &quot;token&quot;,<br>                                    token<br>                                }<br>                            });<br><br>                        } else {<br>                            console.error(`Could not get auth token for command: ${JSON.stringify(command)}`);<br>                        }<br><br>                        break;<br><br>                    case &quot;close&quot;:<br><br>                        win.close();<br>                        break;<br><br>                    case &quot;pick&quot;:<br><br>     <br>                        uploadFiles(command);<br><br>                        port.postMessage({<br>                            type: &quot;result&quot;,<br>                            id: message.data.id,<br>                            data: {<br>                                result: &quot;success&quot;<br>                            }<br>                        });<br><br>                        win.close();<br><br>                        break;<br><br>                    default:<br><br>                        console.warn(`Unsupported command: ${JSON.stringify(command)}`, 2);<br><br>                        port.postMessage({<br>                            result: &quot;error&quot;,<br>                            error: {<br>                                code: &quot;unsupportedCommand&quot;,<br>                                message: command.command<br>                            },<br>                            isExpected: true<br>                        });<br>                        break;<br>                }<br><br>                break;<br>        }<br>    }<br><br>  async function getToken() {<br>        let accessToken = &quot;&quot;;<br><br>        let authParams = { scopes: [&quot;OneDrive.ReadWrite&quot;] };<br>    <br>        try {<br>    <br>            // see if we have already the idtoken saved<br>            const resp = await app.acquireTokenSilent(authParams);<br>            accessToken = resp.accessToken;<br>    <br>        } catch (e) {<br>    <br>            // per examples we fall back to popup<br>            const resp = await app.loginPopup(authParams);<br>            app.setActiveAccount(resp.account);<br>    <br>            if (resp.idToken) {<br>    <br>                const resp2 = await app.acquireTokenSilent(authParams);<br>                accessToken = resp2.accessToken;<br>    <br>            }<br>        }<br>    <br>        return accessToken;<br>    }<br>    return (<br>        &lt;span id=&quot;original-tab-id&quot;&gt;<br>           <br>            &lt;button onClick={(e) =&gt; {<br>                launchPicker(e); <br>            }}&gt;One drive&lt;/button&gt;<br>        &lt;/span&gt;<br>    ); <br>};</pre><p>Now implement uploadFile function</p><pre>    const uploadFiles = (commandData) =&gt; {<br>        <br>        let data = commandData.items[0];<br>        let tokenObj = getToken();<br>      <br>        let url = `${data[&quot;@sharePoint.endpoint&quot;]}drives/${data.parentReference.driveId}/items/${data.id}`;<br>      <br>        tokenObj.then(token =&gt; {<br>            const headers = {<br>                &quot;Authorization&quot;: `Bearer ${token}`,<br>                &quot;Content-Type&quot;: &quot;image/jpeg&quot;<br>            };<br>            fetch(url, {<br>                method: &quot;GET&quot;,<br>                headers<br>            }).then(response =&gt; {<br>                const reader = response.body.getReader();<br>                const decoder = new TextDecoder(&quot;utf-8&quot;);<br>                let chunk = &quot;&quot;;<br>                return reader.read().then(function processResult(result) {<br>                    if (result.done) {<br>                        return JSON.parse(chunk);<br>                    }<br>                    chunk += decoder.decode(result.value, {stream: true});<br>                    return reader.read().then(processResult);<br>                });<br>            }).then(data =&gt; {<br>                processSelectedFile(data);<br>            }).catch(err =&gt; {<br>                console.log(&quot; some error occured &quot;,err);<br>            });<br>        });<br>       <br>    };</pre><p>Now implement processSelectedFile function</p><pre> const processSelectedFile = (fileObj) =&gt; {<br>        let link = fileObj[&quot;@content.downloadUrl&quot;];<br>    };</pre><p>Now in processSelectedFile you will get actual public url to download file and you use this in you image tag element.</p><p>Note : In mac full screen mode file picker will always open in new tab not in popup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*6wRq83xco_wFLf-sjJ7sLw.gif" /></figure><p><strong>Thanks for reading :)</strong></p><p>Subscribe to DDIntel <a href="https://ddintel.datadriveninvestor.com/">Here</a>.</p><p>Visit our website here: <a href="https://www.datadriveninvestor.com/">https://www.datadriveninvestor.com</a></p><p>Join our network here: <a href="https://datadriveninvestor.com/collaborate">https://datadriveninvestor.com/collaborate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4327aa7d4535" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/integrate-one-drive-to-your-react-app-4327aa7d4535">Integrate one drive to your react app</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy your MEAN stack app on Heroku and GoDaddy.]]></title>
            <link>https://medium.com/@satyendra250896/deploy-your-mean-stack-app-on-heroku-and-godaddy-d4494673037b?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4494673037b</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mean-stack]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 09:58:10 GMT</pubDate>
            <atom:updated>2020-06-07T03:25:34.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wymmUvfCa93hER3iB3Bing.png" /></figure><p>So now you have done with your development part using MEAN stack and want to deploy your application to a public domain, you came to the right place.</p><p>In this article, you will learn how to deploy your MEAN stack application to Heroku and then how to use a custom domain, I will use GoDaddy for a custom domain name.</p><p>Let start step by step —</p><h4>The directory structure of the project—</h4><pre>App-frontend  ----frontend code directory<br>    -- angular application <br>App-backend  ---  backend code directory<br>    -- nodejs app with express and mongodb.</pre><p>Here I am using two different folders one for frontend which is an angular application and running on port 4200 and second for a backend which is nodeJS application using expressJS and MongoDB database and running on port 3000.</p><p>Here frontend and backend both are running on a different port so the first task is to run the angular application through the NodeJS app.</p><p>For this, I have to do some changes in the application code —</p><h4>Changes in the angular app —</h4><pre>1. Remove the domain name from backend API because nodejs app use their own domain name on which it is deployed.<br>For example --</pre><pre>If API is  -- <a href="http://localhost:3000/api/blogapp">http://localhost:3000/api/blogapp</a><br>Change it. -- api/blogapp</pre><pre>2. Changes path of dist directory to App-backend/public <br>   In angular.json change outputPath to &quot;App-backend/public&quot;</pre><p>Now run the <em>ng-build </em>command, a public folder will be created in the App-backend folder.</p><h4>Changes in backend code —</h4><pre>1. Change the port number --<br>   const port = process.env.PORT || 8080</pre><pre>2. Now serve the static files of public folder using path module.<br>  const module = require(&#39;path&#39;);</pre><pre><br>  app.use(express.static(&#39;public&#39;));<br>  app.get(&#39;*&#39;,(req,res)=&gt;{</pre><pre>    res.sendFile(path.join(__dirname,&#39;public/index.html&#39;));<br>})</pre><pre>3. Add start script in package.json file.<br>    &quot;scripts&quot;: {<br>        &quot;start&quot; :&quot;node server.js&quot;<br>}</pre><p>Now Everything is set, restart your nodeJS application, and open localhost:&lt;port&gt;, you should see the application running.</p><p>If everything is fine till now you are ready to deploy your application on Heroku.</p><p>Before deploying to Heroku you need to configure your MongoDB database with <em>mlab</em> if you are using your local MongoDB server.</p><h4>Connect with mlab —</h4><p>This is pretty simple —</p><ol><li>Signup on <a href="https://mlab.com/home?newLogin=1">https://mlab.com/</a></li><li>Create a new database</li><li>Click on the created database and you will the DB connection string.</li><li>Click on the Users tab and create a user for the database.</li><li>Now use the DB connection string and replace username and password by the created user.</li></ol><h4>Deploy on Heroku —</h4><ol><li>Prerequisite for this npm,nodeJS, and git should be installed on your system.</li><li>Create an account on Heroku.</li><li>Download and install Heroku CLI.</li><li>Now go to the backend project directory and initialize git using common <em>git init</em>.</li><li>Login to Heroku — heroku login and log in using your Heroku credential.</li><li>Create a Heroku app — heroku create .This will give you a public URL where your application will be deployed.</li><li>Now commit all the code —</li></ol><pre>git add .   -- add all codes<br>git commit -am &quot;Deploying application to heroku&quot;<br>git push heroku master -- commit to heroku master branch</pre><p>Everything is set, now you can see your running app on a public domain of Heroku.</p><p>If your application is still not running you can use the command heroku logs to see the logs and fix the issues and again commit code.</p><h4>Custom domain using GoDaddy—</h4><p>The first step is to buy a domain name from any DNS provider, I am using GoDaddy.</p><ol><li>Go to the Heroku dashboard and click on the project and then click on add domain in the setting section.</li><li>Enter the domain name and click on save ( For adding domain name you need to add your credit card info, don’t worry you don’t charge until you use any of Heroku paid service for adding domain name it is free)</li><li>Not go to the godaddy.com and click on my product and then manage, Go below and click on manage DNS under the additional setting.</li><li>Now search for the record with type CNAME and name www then change the value with your Heroku URL.</li><li>Below records, there is the section name forwarding and domain name in forwarding so that if someone searches with the only domain name without using <a href="http://www/">http://www</a> it automatically redirects to your website.</li><li>That it is, Now your site is live with a custom domain name, enjoy.</li></ol><p>You can visit my website for more tech blog — <a href="http://www.codewithsatyendra.in/">codewithsatyendra.in</a></p><h4>Thanks for reading :)</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4494673037b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async/Await-make your asynchronous code more readable.]]></title>
            <link>https://medium.com/@satyendra250896/async-await-make-your-asynchronous-code-more-readable-64db7c38ccee?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/64db7c38ccee</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 12:01:54 GMT</pubDate>
            <atom:updated>2020-01-20T08:39:04.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Async/Await-make your asynchronous code more readable</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Oo1UcevZ2UBaQRL-6G9TyQ.png" /><figcaption><a href="https://khalilstemmler.com/">https://khalilstemmler.com/</a></figcaption></figure><p>In Javascript there are different way to write asynchronous code like using callbacks, promises and async/ await.</p><p>Async functions allow you to write asynchronous code in a very clear way —</p><p>Syntax —</p><pre>async function function_name(param1,param2,...,param_n){<br>          //function statement.</pre><pre>}</pre><p>An async function always returns a promise which is resolved with a value which it returns or rejected if the async function throws an error.</p><p>Let’s understand it with an example —</p><pre>async function add(num1,num2){<br>  return num1+num2;<br> }</pre><pre>const promiseObj1 = add(5,6);</pre><pre>promiseObj1.then(result=&gt;{<br>       console.log(&quot;result is &quot;+result); //result is 11<br>})</pre><p>In the above example add is an async function which returns the addition of two number but implicitly it returns a promise object which can be resolved using then method and get the result.</p><pre>async function substract(num1,num2){<br>          throw Error(&quot;Some error occured&quot;);<br>   }</pre><pre>const promiseObj2 = substract(10,2);</pre><pre>promiseObj2.then(result=&gt;{<br>       console.log(&quot;result is &quot;+ result);<br>   }).catch(err=&gt;{<br>        console.log(&quot;Error &quot;+err); //Error Error: Some error occured<br>   })</pre><p>In the above example subtract is an async function which throws an error, but in a similar way here also it returns a promise object and you can catch the error using the catch method.</p><h4>await —</h4><p>You can use the await keyword to wait for the output which may be anything (like - getting data from the database , calling the external APIs) and block the execution of other statements of function but it does not block the execution of calling function.</p><p>You can use await keyword only within an async function, if you use it outside of the async function it throws a syntax error.</p><p>Let&#39;s take an example and write it in two ways using promise and async/await —</p><p>Using Promise callbacks</p><pre>getResponseText(url){<br>     return fetch(url).then(response=&gt;{<br>            return response.getText().then(text=&gt;{<br>                      return text;<br>                  })<br>           })<br>    }<br>getResponseText();  // Return the response text.</pre><p>Using Async / Await</p><pre>async function getResponseText(url){<br>         const response = await fetch(url);<br>         const text = await response.getText();<br>         return text;<br>    }</pre><pre>getResponseText(); // Return the response text.</pre><p>In the above example, both functions are doing the same task and also have the same number line of code but the second one is cleaner and readable.</p><h4>Thanks for reading :)</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64db7c38ccee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Golang and how to install it.]]></title>
            <link>https://medium.datadriveninvestor.com/what-is-golang-and-how-to-install-it-34312c93c72?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/34312c93c72</guid>
            <category><![CDATA[webdesign-and-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 17:48:50 GMT</pubDate>
            <atom:updated>2019-11-18T10:33:54.432Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Golang and how to install it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*CdjOgfolLt_GNJYBzI-1QQ.jpeg" /><figcaption>Golang logo</figcaption></figure><p>Golang is a general-purpose compiled programming language, created by google developer.</p><p>Golang comes from the programming language like C++/Java. So it inherits some of the property from these languages like statically typed, object-oriented and many more. It is very easy to code and efficient in code compilation and execution.</p><p>Golang become so popular nowadays because of its some unmatched features —</p><h4>Strong and Statically typed language —</h4><p>Strong typed means the type of variable can not change over time. For example, if a variable is of integer type we can not assign boolean value in it over time.</p><p><a href="https://www.datadriveninvestor.com/2019/01/23/which-is-more-promising-data-science-or-software-engineering/">Which is More Promising: Data Science or Software Engineering? | Data Driven Investor</a></p><p>Statically typed means all of the variables have to be defined at the compile time.</p><h4>Simplicity —</h4><p>Go language is very simple, For example</p><p>How many loop keyword is there — only 1</p><p>How many keywords — 25 (50 in java and 48 in c++)</p><p>In the same way, there are many more features which makes go language very simple.</p><h4>Concurrency —</h4><p>When the load on software is increasing, there is a need to scale up the software by increasing the number of threads. The majority of programming language become slow while working with concurrency and multi-threading. This the where go become the most relevant option to support multithreading and concurrency both.</p><h4>Garbage Collected —</h4><p>Go language manage the memory by itself , you don’t have to manage memory by your self.</p><h4>In-Built Testing Framework —</h4><p>While working with programming language like java/javascript, we have seen we first choose a good testing framework and then start testing, while with golang there is an inbuilt testing tool where we can test our software.</p><h4>Installing Golang —</h4><p>To install Golang go to the official site - <a href="https://golang.org/">https://golang.org/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDrRVFmP6DFmcE0F-z_wng.png" /><figcaption><a href="https://golang.org/">https://golang.org/</a></figcaption></figure><p>Now click on Download Go button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eghQLVFOpJngbVTSDxdVFw.png" /><figcaption>Download page</figcaption></figure><p>On this page, you will see installer file for windows, mac and linux operating system.</p><p>For windows there is a executable file , download and install it , It is pretty straight forward.</p><p>To install on linux follow step by step —</p><h4>Step 1 —</h4><p>Download .tar.gz file by clicking on the given link.</p><h4>Step2 —</h4><p>Untar it in /usr/local directory by using below command.</p><pre>sudo tar -C /usr/local -xzf go1.13.4.linux-amd64.tar.gz</pre><p>This commond extract all the files and packages in /usr/local directory.</p><h4>Step3 —</h4><p>Now create a workspace for go in your home directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*haRzsl2Dw9BNl6uj0WlbMQ.png" /><figcaption>create workspace for go</figcaption></figure><p>Now add GOPATH in .bashprofile or .bashrc file.</p><pre>export GOPATH=$HOME/go<br>export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin</pre><p>Now execute .bashprofile or .bashrc file to apply changes immediately.</p><pre>./.bashprofile or ./.bashrc</pre><h4>Step4 —</h4><p>Now let&#39;s test the go is installed or not by writing a hello world program.</p><p>Before writing the code, first understand the directory structure of go in a very simpler way —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*BeVfqlKlk-kabtwUIrlj9Q.png" /><figcaption>directry structure of go</figcaption></figure><p>In go workspace there is a bin directory which contains bin which contains all the executable file, src folder contains project source code and pkg contain all the packages which we install.</p><p>Now let&#39;s write your first hello world program to check whether go is installed or not on your system.</p><p>In go folder create a folder src within that create hello folder and then file name hello.go</p><pre>cd go<br>mkdir src<br>cd src<br>midir hello<br>cd hello<br>touch hello.go</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*Xqe1pOQ0cyriRHxI-7blKQ.png" /><figcaption>simple program in go.</figcaption></figure><p>Now write above code in hello.go file and save.</p><p>To execute that file we need two step —</p><p>Firstly create executable file by using “go build” commond and then run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*I_QJOd3zdhDGy315HY5_DQ.png" /><figcaption>running hello world code.</figcaption></figure><p>You have successfully installed Golang on your system.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34312c93c72" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/what-is-golang-and-how-to-install-it-34312c93c72">What is Golang and how to install it.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing two way Data Binding without using any framework.]]></title>
            <link>https://medium.datadriveninvestor.com/implementing-two-way-data-binding-without-using-any-framework-703963d00a94?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/703963d00a94</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 18:19:33 GMT</pubDate>
            <atom:updated>2019-08-01T06:05:19.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*tmKpTjV33VoEJ1u6" /></a></figure><h3>Implementing two-way Data Binding without using any framework.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*sxu8s7f2CP4HkdADqsG5iA.png" /></figure><p>In any modern web application we have basically two-part first one is the front-end part to which user interacts with like seeing the information, filling the form , click the button ,etc and the other is back-end where all the business logic, data manipulation, authentication, authorization, session handling, file upload, and many more things are being done.</p><p>So when the user does some data manipulation on the front end part, the source data to be changed. For example, if we have a list of the employee details at the front-end if someone modifies the employee&#39;s details at the front end this should reflect at the data source and vice versa.</p><p><a href="https://www.datadriveninvestor.com/2019/02/21/best-coding-languages-to-learn-in-2019/">Best Coding Languages to Learn in 2019 | Data Driven Investor</a></p><h4>Data binding —</h4><p>Data binding is a way to bind the flow to data between the user interface and business logic.</p><p>There are basically two types of data binding —</p><ol><li>One-way data binding</li><li>Two-way data binding</li></ol><h4>One-way data binding —</h4><p>In one-way data binding on changing to the business logic, front-end will automatically change, but when we update the at the front end back end will not change automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*rSRM637ziCJAkQ7cPKfl3w.png" /><figcaption>one way data binding</figcaption></figure><h4>Two-way data binding —</h4><p>In two-way data binding changes are done on both side, when we modify the data at the back-end, front-end part will automatically update and vice-versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Nc0UaSNz4NjcpkgyKVyBNQ.png" /><figcaption>Two-way data binding</figcaption></figure><p>Now a day two-way data binding is one of the main features of modern front-end framework like Angular, React and Vue.</p><p>For example, in angular, we use <em>[(ngModel)] </em>for two way data binding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*NjLGJWb2vLmbVn4zaJFlhg.png" /></figure><p>Here when we start typing into the input box, the username will be updated into the username model and reflected back to the view.</p><blockquote>Can we implement this using vanilla Javascript ??</blockquote><p>The answer is yes, we can implement it easily using javascript and using event handling.</p><p>So first create a simple web page which contains two input box and will implement two-way data binding for the value of those inputs box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*vpy5qkOwKLE-sLncpyLupw.png" /><figcaption>index.html</figcaption></figure><ol><li>In the above code, I am using the <em>sg-model</em> attribute in the input field to bind the input field value. Here I will go through all the <em>sg-model</em> attribute and get the current input value and bound to the <em>scope </em>object in javascript code.</li><li>I am using an <em>sg-bind </em>attribute for the h4 tag, which will be used for the DOM manipulation when the input value is changed.</li></ol><p>Now first take all the input and h4 elements —</p><pre>//all the input elements<br>const inputElements = document.querySelectorAll(&#39;[sg-model]&#39;);</pre><pre>//all the h4 element</pre><pre>const inputBinds = document.querySelectorAll(&#39;[sg-bind]&#39;);</pre><p>Now create a function which will be called as soon as the page is loaded i.e <em>twoWayDataBinding.</em></p><pre>let scope = {};  //Initialize a global scope object.</pre><pre>function twoWayDataBinding(){<br>for(let elem of  inputElements) {</pre><pre>      if(elem.type === &#39;text&#39;){<br>           let propName = elem.getAttribute(&#39;sg-model&#39;);</pre><pre>            elem.addEventListener(&#39;keyup&#39;, e =&gt;{</pre><pre>            scope[propName] = elem.value;<br>      })<br>     updateDom(propName);<br>      }</pre><pre>   }</pre><pre>}</pre><ol><li>In the above function, I am iterating through the input elements and for each input elements, I am attaching an event listener <em>keyup.</em></li><li>For every input value, it will set the appropriate property of the scope object.</li><li>In the end, we will call <em>updateDom </em>function which will manipulate the view part.</li></ol><pre>function updateDom(propName){</pre><pre>    if(!scope.hasOwnProperty(propName)){</pre><pre>    let value;</pre><pre>    Object.defineProperty(scope,propName,{</pre><pre>           set:(newValue)=&gt;{</pre><pre>           value = newValue;</pre><pre>           for(let e1 of inputElements){</pre><pre>           if(e1.getAttribute(&#39;sg-model&#39;)=== propName){</pre><pre>           e1.value=newValue;</pre><pre>      }</pre><pre>   }</pre><pre>       for(let e2 of inputBinds){</pre><pre>       if(e2.getAttribute(&#39;sg-bind&#39;) === propName){</pre><pre>       if(!e2.type){</pre><pre>       e2.innerHTML=newValue;</pre><pre>       }</pre><pre>    }  </pre><pre>  }</pre><pre>},</pre><pre>  get(){</pre><pre>      return value;</pre><pre>     }</pre><pre>  })</pre><pre> }</pre><pre>}</pre><pre>twoWayDataBinding();</pre><pre>scope.name=&#39;satyendra&#39;;</pre><pre>scope.surname=&#39;kannaujiya&#39;;</pre><ol><li>In this function, I am checking if the scope object has that property or not.</li><li>If the property is available in the scope object then I am implementing the <em>getter </em>and <em>setter </em>on the scope object using <em>Object.defineProperty().</em></li><li>Here <em>setter</em> method will be invoked every time the property value of the scope object will be changed.</li></ol><p>Now you can run the code and you will get data binding is implemented.</p><p>I have implemented this in a very simple way, this can be done by other methods also.</p><h4>Thanks for reading :)</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=703963d00a94" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/implementing-two-way-data-binding-without-using-any-framework-703963d00a94">Implementing two way Data Binding without using any framework.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create custom element without using any framework.]]></title>
            <link>https://medium.datadriveninvestor.com/how-to-create-custom-element-without-using-any-framework-cb502f3795b0?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb502f3795b0</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sat, 02 Mar 2019 19:46:00 GMT</pubDate>
            <atom:updated>2019-03-29T14:48:38.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*PhBwIVIVpdjGcehE" /></a></figure><h3>How to create a custom element without using any framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNC6dKxk5A7HaeWgfi7pJA.png" /><figcaption>custom element example which we will build in the tutorial</figcaption></figure><p>When we write the User interface using HTML sometime it is not easy to handle complex HTML ( and associated styles and script ) and sometimes you have to rewrite the same code multiple time across the application which can turn page into a mess if you are not careful.</p><p>Custom element aim to solve such problem by providing the reusable web component with encapsulate functionality than can be reused wherever you like .</p><h4>What are custom element —</h4><p>Using custom element developer can create new HTML tag or can improve the existing HTML tags.Custom element is the way to modernizing HTML , if native HTML does not provide any custom feature you want , You can create custom element that does the same task.</p><p>For example if you want to display the details of user you can make a custom element named &lt;user-details&gt;&lt;/user-details&gt; and can reuse over the application.</p><blockquote><a href="http://go.datadriveninvestor.com/WebDevelopment1/matf">DDI Editor’s Pick — The Web Developer Bootcamp</a></blockquote><p>There are some point you should keep in mind while creating custom element</p><ol><li>The name of the custom element must contain a dash(-) so &lt;my-element&gt; , &lt;customer-profile&gt; , &lt;journey-details&gt; all are valid custom element name whereas &lt;myComponent&gt; , &lt;fancyButton&gt; are invalid custom element name.This requirement is necessary because HTML parser can distinguish custom element from regular elements.</li><li>You can not register the same tag more than once , if you try to do so will throw a DOM Exception.</li><li>Custom element can not be self closing because HTML only allow a few elements to be self closing , So always write a closing tag.</li></ol><p>The general approach for implementing a web components are —</p><ol><li>Create a class or function in which you will specify your web component functionality.</li><li>Define your custom element using customElement.define() which take two argument first is tag name and the second arguement is the class in which the functionality is defined and optionally, an options object containing an extends property, which specifies the built-in element your element inherits from if any.</li><li>If require attach a shadow DOM to the custom element using Element.attachShadow() method attach all child element and event listener etc to the shadow DOM using regular DOM methods.</li></ol><p>4. Use your custom element wherever you like on your page , just like you use regular element.</p><p>So the user details element can be define like this —</p><pre>customElements.define(&#39;user-details&#39;,UserDetails);</pre><p>In the above example first argument is the custom tag name and the second is class where functionality are defined.</p><h4>Custom element are of two types —</h4><ol><li>Autonomous Custom element — It is standalone and didn’t inherit from standard HTML elements.You use this on page by writing them similar to regular HTML element for example &lt;user-details&gt;&lt;/user-details&gt;.</li><li>Customized build-in element — It inherit from basic HTML elements to create customized version of existing element . They can be use by writing basic HTML element and specify the name of custom element using is attribute. for example &lt;button is=&#39;fancy-button&#39;&gt;&lt;/button&gt; here fancy-button is the custom element which will extend HTMLButtonElement .</li></ol><h4>Different life cycle hook of an element —</h4><p>There are different callback inside element class definition which call at different life cycle of the elements —</p><ol><li>connectedCallback<em> — </em>It get called when the element get attached to the documents DOM.</li><li>disconnectedCallback — It get invoked each time when the element is remove from the documents DOM.</li><li>adoptedCallback — It invoked each time when the custom element move to the new document.</li><li>attributeChangedCallback — It invoked each time when any of the attribute get added,removed or changed. The attribute for which we have to notice the changed is specified in the static get observedAttributes method.</li></ol><h4>Shadow DOM —</h4><p>It is very important to keep the markup structure, styles and behaviour of custom element hidden and separate from the other code of the page so that different part do not clash.for example there a child element in the custom element whose class name is same as the any element on the page then in this case if we style element on the basis of class name may clash with custom element styles but using shadow DOM we can avoid this.</p><p>Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree start with shadow root and then you can attach any element you want in same way as normal DOM.</p><p>Theory part is over now let’s create a custom element &lt;user-details&gt;&lt;/user-details&gt; .</p><p>Create two file named index.html and index.js .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5737e820b067a7da1ee9ffde54d7d44/href">https://medium.com/media/e5737e820b067a7da1ee9ffde54d7d44/href</a></iframe><p>Let’s understand the code —</p><p>Firstly there is a constructor which call the super which is necessary so that correct prototype chain established.</p><p>Now observedAttributes() method where we specify the attribute name for which we want to get noticed for attribute changed.</p><p>Now get and set for the attribute which simply return and set the attribute value respectively.</p><p>Now connectedCallback which called when the element attached to the documents DOM. In which we first create a shadow DOM and then the normal HTML element according to our need.Then we also attach style element to the shadow DOM and then at the end we append all the element to the shadow DOM tree.</p><p>Now attributeChangedCallback which takes three parameter attribute name , old value and new value.It invoked when any attribute get changed,removed or added to the element. We check for old value is not equal to new value to prevent overflow of recursion call stack.</p><p>At the end we define our custom element using customElements.define() method.</p><p>Now using above custom element into our index.html page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4d7e268d1ac39e1efb5611dd3f0721/href">https://medium.com/media/5a4d7e268d1ac39e1efb5611dd3f0721/href</a></iframe><p>Here we are passing the attribute value like regular HTML element .</p><p>you can get full code here — <a href="https://github.com/satyendrakannaujiya/WebComponent">Github link</a></p><p>Thanks for reading 😙.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.gridble.io%2Fform%2Fmtcaiuoghdz1628j&amp;dntp=1&amp;url=https%3A%2F%2Fwww.gridble.io%2Fform%2Fmtcaiuoghdz1628j&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gridble" width="700" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d3f864cdfdeb2c7218fee36a7303243/href">https://medium.com/media/5d3f864cdfdeb2c7218fee36a7303243/href</a></iframe><p><em>Editor’s Disclosure: The editors sometimes post affiliate links to useful resources. If you find them useful and make a purchase, we will earn some big bucks. No, I’m not talking about upsizing my fries kind of big. I’m talking about extra pepperoni on a large pizza kind of big. Thank you for your continued support, we will continue to work hard for the p̶e̶p̶p̶e̶r̶o̶n̶i̶ publication.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb502f3795b0" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/how-to-create-custom-element-without-using-any-framework-cb502f3795b0">How to create custom element without using any framework.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An introduction to Promises.]]></title>
            <link>https://medium.datadriveninvestor.com/an-introduction-to-promises-299f474392b5?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/299f474392b5</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sun, 17 Feb 2019 17:37:04 GMT</pubDate>
            <atom:updated>2019-02-20T14:48:32.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IQTDYPoKdP-3w8oZ" /></a></figure><h3>An introduction to Promises</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*dpnAH5O-2ik_zmfa02CM2w.jpeg" /></figure><p><em>In JavaScript Promises are the object which are basically use to handle asynchronous request </em>. JavaScript is a single threaded language means two portion of the code can not run at the same time they have to run one after another . But typically JavaScript is in the same queue as painting , updating styles and handling user action , activity in one of these delays the other.</p><p>Promises are the object which produces the output some time later in the future which may be possibly resolved value or failure value ( e.g network error).</p><p>Let fetch some data using fetch API which return promises —</p><pre>var promises = fetch(&quot;<a href="https://api.github.com/">https://api.github.com/</a>&quot;);</pre><pre>promises.then(function(res){</pre><pre>return res.json();  //Also return promise.</pre><pre>},function(error){<br>     console.log(&quot;Error occured&quot; + error);</pre><pre>  ).then(function(data){<br>  console.log(data);<br>})</pre><p>In the example above fetch API return promise and when the data are available we can access using then which contain two callback first one is for success and other is for handling errors, and res.json() also returning promise and we can access that using then again.</p><h4>States of the promise —</h4><p>A promise can be in one the following states —</p><ol><li>Fulfilled — Action has been completed successfully.</li><li>Rejected — Action has been failed</li><li>Pending — Action has not fulfilled not rejected.</li></ol><p>A promise is said to be settled once it is fulfilled or rejected.</p><h4>Some fact related to promise —</h4><ul><li>Callbacks will never be called before the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Run-to-completion">completion of the current run</a> of the JavaScript event loop.</li><li>Callbacks added with then even <em>after</em> the success or failure of the asynchronous operation, will be called.</li><li>Multiple callbacks may be added by calling then several times. Each callback is executed one after another, in the order in which they were inserted.</li><li>A promise can only succeed or fail once . It can not succeed or fail twice , neither it can be switch from success to failure nor vice-versa.</li><li>If a promise has succeed or failed and you later add a success or failure callback it will be ignored.</li><li>then() takes two arguments a callbacks for success case and another for the failure case and both are optional so you can add a callback only for the success case only.</li></ul><h4>Chaining —</h4><p>let’s understand with the below example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*7D6sj-tGUc2KkOReAiuAmA.png" /></figure><p>In the above example fetch return a promise which are resolved in the first then . Now what happen when the success callback or failure callback also return promise as in the above example res.json() also return promise, we can handle them by making chain of promise .</p><p>then() itself return a new promise different from the original .</p><h4>Error handling —</h4><p>then() contain two parameter which are callback functions first one is for success and the other is for failure . we can handle error by using this failure callback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*aq1cn7SivEbmKUzlvGo6Xg.png" /></figure><p>Now what happen if success callback function throw some error , The promise returned from .then() will be rejected, but there’s nothing there to catch the rejection. So to handle these type of situation we can use catch().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*cpokwGjw4rSZDP5yE0necA.png" /></figure><p>In the above example we are using catch() to handle errors.</p><h4>Creating your own promise —</h4><p>Till now we are using fetch API which return promise. You can create you own promise using promise constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*ZiSKPjCbtbjmnzKkYzk5SQ.png" /></figure><p>In the above example we are creating a promise using promise constructor which take a callback function and callback function contain two parameter resolve and reject .</p><p>If the action has been successfully completed resolve() will be called otherwise reject() will be called.</p><h4>Load an image using XMLHttpRequest and Promise —</h4><p>Create a getImage() function which use XMLHttpRequest to fetch data from the server and return promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*a2wO_i5-8f2tO9HYqCekBg.png" /><figcaption>using HMLHttpRequest to fetch data from server.</figcaption></figure><p>Now use getImage() function to get the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*7JcEQS1ziMnAyG_aMSPPZg.png" /><figcaption>calling the getImage.</figcaption></figure><p>You will get the following output —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mv3eq8k4hWEyeQqi3Qag9A.png" /><figcaption>Image is loaded .</figcaption></figure><p>Thanks for reading 😙.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.gridble.io%2Fform%2Forootd81tawa8ajg&amp;dntp=1&amp;url=https%3A%2F%2Fwww.gridble.io%2Fform%2Forootd81tawa8ajg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gridble" width="700" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e56b9f4bc5e533dd492934942bb43920/href">https://medium.com/media/e56b9f4bc5e533dd492934942bb43920/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=299f474392b5" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/an-introduction-to-promises-299f474392b5">An introduction to Promises.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Callback function in JavaScript.]]></title>
            <link>https://medium.datadriveninvestor.com/understand-callback-function-in-javascript-b2961cdc9bc7?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2961cdc9bc7</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sat, 09 Feb 2019 16:37:22 GMT</pubDate>
            <atom:updated>2019-02-11T06:38:13.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BfyvtJtQzye2amhF" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*SbXmsZBfAQiigTaLBVe63g.png" /></figure><p>The first thing you have to understand is that in JavaScript functions are the first class object which means like other object we can pass function as a argument to other to other function and we can assign function to a variable and also we can return a function from other function.</p><h4>What is callback function —</h4><p>Function which are passed as a argument to other function and can be called later after some time is known as callback function . The function which accept other function as a argument is called high order function which basically contain the logic when to call the callback function.</p><p>Let’s understand it with examples —</p><pre>function sum(num1,num2){<br>   return num1+num2</pre><pre>}</pre><pre>function calculate(num1,num2,sum){ //sum is the call back function</pre><pre>       return sum(num1,num2);</pre><pre> }<br>var result = calculate(5,6,sum);<br>console.log(result); // 11</pre><p>It is always better to check the type of callback function that if it is function or not. In the above example we are not checking the type of sum function.</p><pre>function sum(num1,num2){<br>   return num1+num2</pre><pre>}</pre><pre>function calculate(num1,num2,sum){ //sum is the call back function<br>    if(typeof sum === &#39;function&#39;){<br>          return sum(num1,num2);</pre><pre>   }</pre><pre>}<br>var result = calculate(5,6,sum);<br>console.log(result); // 11</pre><h4>Use of callback function —</h4><p>In the above example you see calculate function which does nothing that takes time , it simply call the callback function ( i.e sum) immediately , this type of operation are synchronous operation. But this does not happen always , for example when we request for data from server or external API we don’t know when our data will be served back.In these situation we have to wait for the response but we don’t want our application to be freeze.We want every functionality should work as it is and when we get data from the server it will reflect on the application.So Callbacks are very useful in this type of situation.</p><p>Let’s understand with example —</p><pre>function getDataFromServer(callback){</pre><pre>         setTimeout(function(){</pre><pre>             callback();<br>       },10000)<br>}</pre><pre>function personDetails(){</pre><pre>console.log(&quot;PersonDetails are available to use &quot;);<br>}</pre><pre>getDataFromServer(personDetails);  //PersonDetails are available to use</pre><p>Here I am demonstrating server request using setTimeout function which simply execute a function after specified time.</p><p>In the above example getDataFromServer execute callback function after 1 s , So when the data are available we can callback function to perform the task which depend on that data.</p><h4>this within callback function —</h4><p>this is a special keyword inside each function and the value of this depends on how the function was called not on how or where it was defined.</p><p>When callback function are using this object we have to modify how we call the callback function otherwise it will point to window object if passed in global function.</p><pre>var student = {</pre><pre>age:22,<br>   fullName:&#39;Not Set&#39;,<br>   setFullName : function(firstName,lastName){<br>      this.fullName = firstName+&#39; &#39;+lastName;<br>   }<br>}</pre><pre>function userInput(firstName,lastName,callback){</pre><pre>callback(firstName,lastName);<br>}</pre><pre>userInput(&#39;satyendra&#39;,&#39;kannaujiya&#39;,student.setFullName);</pre><pre>console.log(student.fullName); //Not Set<br>console.log(window.fullName); //satyendra kannaujiya</pre><p>In the above example callback function will not set the fullnName of object student because userInput is a global function and value of this in global scope is window .</p><p>We can use call or apply to preserve this.The first parameter of the call and apply is the value of this or the calling object.</p><pre>var student = {</pre><pre>age:22,<br>   fullName:&#39;Not Set&#39;,<br>   setFullName : function(firstName,lastName){<br>      this.fullName = firstName+&#39; &#39;+lastName;<br>   }<br>}</pre><pre>function userInput(firstName,lastName,callback, object){</pre><pre>callback.call(object,firstName,lastName)<br>}</pre><pre>userInput(&#39;satyendra&#39;,&#39;kannaujiya&#39;,student.setFullName, student);</pre><pre>console.log(student.fullName); //satyendra kannaujiya</pre><pre>console.log(window.fullName); //undefined</pre><h4>Thanks for reading . ☺️</h4><h4>Related Stories from DDI:</h4><ul><li><a href="https://www.datadriveninvestor.com/2019/01/23/which-is-more-promising-data-science-or-software-engineering/">Which is More Promising: Data Science or Software Engineering? | Data Driven Investor</a></li><li><a href="https://www.datadriveninvestor.com/2019/02/07/8-skills-you-need-to-become-a-data-scientist/">8 Skills You Need to Become a Data Scientist | Data Driven Investor</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2961cdc9bc7" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/understand-callback-function-in-javascript-b2961cdc9bc7">Understand Callback function in JavaScript.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript for Beginners(06):Everything about Arrays]]></title>
            <link>https://medium.datadriveninvestor.com/javascript-for-beginners-06-everything-about-arrays-a8c1058fd681?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c1058fd681</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 17:40:29 GMT</pubDate>
            <atom:updated>2019-01-28T14:21:33.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*re5ObHSnsz3pzLkS" /></a></figure><h3>JavaScript for Beginners(06): Everything about Arrays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*yQiY31KE0BkhzxXfE_CHLw.jpeg" /></figure><p>Every programming language provides data types to store the value of variable and data structure are required to manage the data in an efficient way.</p><p>In JavaScript, there are two types of data type —</p><h4>Primitive data type —</h4><ul><li>Boolean</li><li>Number</li><li>String</li><li>Null</li><li>Undefined</li><li>Symbol object</li></ul><h4>Nonprimitive data type —</h4><p>In JavaScript everything except above primitive data type objects.</p><p>Objects provide are a way to store data in a key-value format, that’s is fine.</p><p>But when we want to store a collection of data in an ordered manner, just by using object it is not convenient, because it does not provide a method to store data in an ordered manner.</p><p>To solve these problems, there exists a data structure <em>Array </em>which stores data in an ordered manner.</p><p>JavaScript Array is a high level object which is used in the construction of arrays.</p><h4>Creating an Array —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*JvBpHUEVRsTNJtX2GifI5w.png" /></figure><h4>Accessing an array item —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*6KGiKWaGaIypSTq3esvBmA.png" /></figure><h4>Iterating over the array —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*NFe_9HyxUNz1vpXlGS3R7g.png" /></figure><h4>Add at the end of array —</h4><p>We can use push method to add at the end of the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*XwPN1vAS7dPiRv-dySyJEQ.png" /></figure><h4>Delete an element from the end of array —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*93q-OOwRubQzbX89h4J1mA.png" /></figure><h4>Add in the front of array —</h4><p>We can use unshift method of the array to add an element at the front of the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*1l2wO5LIK78WtsdWZ9bZBg.png" /></figure><h4>Remove from the front of array —</h4><p>For removing array from the array we can use shift method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*GGDX0cVrWqPRoHmNpkHbnw.png" /></figure><h4>Find index of an item —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*2kUh9kknODjkOHFvNAjJ2g.png" /></figure><h4>Some of the Important method —</h4><p>There are some of the very useful method in an array which is very frequently used.</p><h4>Find —</h4><p>Find method return the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*g0gf0A722CJRs3yGoJff4Q.png" /></figure><h4>Sort —</h4><p>sort method sort the provided array in place on the basis of provided compare function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*m6GxDWCj77jfcrnw0skQQA.png" /></figure><ul><li>If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).</li><li>If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.</li><li>If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).</li><li>compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.</li></ul><h4>Some —</h4><p>The <strong>some()</strong> method tests whether at least one element in the array passes the test implemented by the provided function.</p><p>It returns true if the callback function returns truthy value for an element from the array otherwise false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*YBmsIbneD-7DUbu6epLd9w.png" /></figure><h4>Slice —</h4><p>The <strong>slice()</strong> method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*BkiCPUc7OWtc3ViBV2bCzw.png" /></figure><h4>Splice —</h4><p>The <strong>splice()</strong> method changes the contents of an array by removing or replacing existing elements and/or adding new elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*4pZ1QLUOXAsC_ZBNE-SRkg.png" /></figure><h4>Map —</h4><p>The <strong>map()</strong> method creates a new array with the results of calling a provided function on every element in the calling array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*CVFYXC0UnZTL5QuJj_gcBQ.png" /></figure><h4>Filter —</h4><p>The <strong>filter()</strong> method creates a new array with all elements that pass the test implemented by the provided function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*5SqRbnFHoe181TRwcN-TEg.png" /></figure><p>If no element will satisfy the test condition empty array will be returned.</p><h4>Reduce —</h4><p>reduce() method is used to apply a function on each element of the array to produce a single output.</p><p>Here is the syntax of the reduce function</p><pre>let res = arr.reduce(callback);</pre><pre>//You can also provide a initial value</pre><pre>let result = arr.reduce(callback,initialValue);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*j4gMddTFG6BKAXbC2TWuDQ.png" /></figure><h4>Thanks for reading :)</h4><p>This article is the part of the series article for JavaScript for beginners —</p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-01-getting-started-56a4e55f43bf">JavaScript for Beginners(01): Getting started.</a></p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-02-dom-manipulation-crash-course-12194e195e2">JavaScript for Beginners(02): DOM Manipulation Crash Course</a></p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-03-understand-hoisting-in-javascript-4d0df03e60cc">JavaScript for Beginners(03): Understand Hoisting in JavaScript.</a></p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-04-function-in-javascript-dcc6ca18b3f8">JavaScript for Beginners(04): Everything about JavaScript function</a>.</p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-05-object-oriented-programming-made-simple-dd5dee141e12">JavaScript for Begniners(05): Object-Oriented Programming Made Simple.</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c1058fd681" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/javascript-for-beginners-06-everything-about-arrays-a8c1058fd681">JavaScript for Beginners(06):Everything about Arrays</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript For Beginners(05):Object-Oriented Programming Made Simple.]]></title>
            <link>https://medium.datadriveninvestor.com/javascript-for-beginners-05-object-oriented-programming-made-simple-dd5dee141e12?source=rss-3a09033e9ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd5dee141e12</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Satyendra Kannaujiya]]></dc:creator>
            <pubDate>Sat, 19 Jan 2019 19:28:26 GMT</pubDate>
            <atom:updated>2019-01-20T05:52:08.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*g4oLvAAjlmHxTyYM" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBssM_be40Ua5y6dXeCs5w.jpeg" /></figure><p>Object-oriented programming is a programming paradigm which is basically centered around objects rather than function, or you can understand like object-oriented programming is not a programming language or any tool, It is just a style of programming to solve a real-life problem.</p><p>Before Object-oriented programming, we have procedural programming in which we divide a program into a set of function and data store in the set of variables and the function operate on that variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*vKgCgTOc2iy-L98l8jPwQQ.png" /><figcaption>Function and variable in Procedural Programming</figcaption></figure><p>Often this technique is very simple and straight forward but makes code very complex because the code becomes full of different function and interdependency of function makes it more complex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*AQ-ErzrIaQ9CLe7KnhdjKA.png" /><figcaption>Interdependency of function which lead to problem in procedural programming.</figcaption></figure><p>There are many languages who support object-oriented programming paradigm like — C#,Java,Ruby,Python,JavaScript and many more.</p><p>Now let’s start with object creation, There are many ways to create an object in JavaScript</p><p>1.Object Literals</p><pre>Object Literals</pre><pre>var Person = {<br>    name : &#39;Rakesh yadav&#39;,<br>    age : 23,<br>    address: {<br>       city: Varanasi,<br>       State: Uttar Pradesh,<br>       Country: India</pre><pre>}</pre><pre>}<br>We can invoke the above object property and method using . operator</pre><pre>console.log(Person.name);</pre><p>2. Using Object Prototype</p><pre>function Student(){<br>      }<br>  Student.prototype.name=&#39;Rakesh Yadav&#39;;<br>  Student.prototype.age=23;</pre><pre>var stu1 = new Student();<br>console.log(stu1.name); //Rakesh yadav</pre><p>3. Using Constructor function</p><pre>function Student(name,age){<br>    this.name =  name;<br>    this.age  = age;</pre><pre>}</pre><pre>var student1 = new Student(&#39;Rakesh yadav&#39;,23);</pre><pre>console.log(&#39;Name of student is &#39; + student1.name);</pre><p>There are mainly 4 core concept in object-oriented programming which are —</p><ol><li>Encapsulation</li><li>Abstraction</li><li>Inheritance</li><li>Polymorphism</li></ol><h4>Encapsulation —</h4><p>In Object-oriented programming, we combined a group of related variable and function that operate on them into an object this is what we called as encapsulation. Here we refer these variable as property and functions as method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*1SZfNijzdLuJw4hwAwZ0-A.png" /><figcaption>Encapsulation</figcaption></figure><p>Let&#39;s take a real-life example of a car , here Car is an object with properties like — make, model, color and method like — start, stop and move.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*wWCJbZl9Zez86P5KwjexSg.png" /><figcaption>Car object with property and method.</figcaption></figure><p>Now let’s take an example —</p><p>Below is the code we are calculating the wage of the employee, here firstly we declare the variable and a method which calculate the wage of the employee. This is basically procedural way of doing .</p><pre>let baseSalery = 30000;<br>let overtime = 10;<br>let rate = 20;</pre><pre>function getWage(baseSalery,overtime,rate){<br>    return basesalery + (overtime * rate);</pre><pre> }<br></pre><p>We can apply object-oriented concept encapsulation to bind related variable and property in a single unit below are the implementation.</p><pre>let employee = {</pre><pre>      baseSalery: 30000,<br>      overtime: 10,<br>      rate:  20,<br>      getWage: function(){</pre><pre>            return this.baseSalery + (this.overtime*this.rate);</pre><pre>      }</pre><pre>};</pre><pre>employee.getWage();</pre><p>This is the object-oriented way where we combined variables and method in an object which is known as encapsulation.</p><h4>Abstraction —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBssM_be40Ua5y6dXeCs5w.jpeg" /><figcaption>Electricity board</figcaption></figure><p>Let’s think of an electricity board as an object, this electricity board has a complex logic inside and there are only a few buttons are outside that you interact with, For any action, you simply switch the button and you don’t care what happens inside, all the complexity are hidden from you. This is abstraction in practice.</p><p>We can the same technique in our object , we can some of the property and method from the outside.Abstraction made interface simpler and It also reduces the impact of change.</p><p>Let’s take a example of circle object which includes some of the property and methods —</p><pre>function Circle(radius){</pre><pre>   this.radius = radius;<br>   this.defaultLocation = {x: 0,y: 0};<br>   this.computeOptimumLocation = function(){</pre><pre>    //....<br>   };<br>   this.draw = function(){</pre><pre>      this.computeOptimumLocation();<br>      console.log(&#39;draw&#39;);</pre><pre>   };</pre><pre>}<br>const circle = new Circle();</pre><p>Here we can see some of the methods like computeOptimumLocation and defaultLocation object are risky if they are visible to all the all the object we create. So we can hide that so that outsider can’t change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*tcDg5gqbFWcXHA9YOHT8qQ.png" /><figcaption>Abstraction says show only essential and hide th details</figcaption></figure><p>We can make the object, method, and property to not accessible from the outside world by making its local variable, we do the below —</p><pre>function Circle(radius){</pre><pre>   this.radius = radius;<br>   let defaultLocation = {x: 0,y: 0};<br>   let computeOptimumLocation = function(){</pre><pre>    //....<br>   };<br>   this.draw = function(){</pre><pre>this.computeOptimumLocation();<br>      console.log(&#39;draw&#39;);</pre><pre>};</pre><pre>}<br>const circle = new Circle();</pre><pre>Here object circle can not access object defaultLocation  and method computeOptimumLocation.</pre><h4>Inheritance —</h4><p>Inheritance is a mechanism that allows you to remove redundant code. Lets take example of some HTML Element like — Textbox , Selectbox , Checkbox etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*PDt79cV2q2eEee9BZxaoZQ.png" /><figcaption>HTML Element</figcaption></figure><p>All these element have few thing in common property like hidden, innerHTML and method like — click(), focus() .</p><p>So instead of redefining all the method and property for every type of HTML element we can define once in a Generic object call it as HTMLElement object and help other objects inherit property and method of this object. So in this way inheritance help us to remove redundant code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*MnWRFBu9uaupMxgmvShEWA.png" /><figcaption>Inheritance.</figcaption></figure><p>In JavaScript inheritance are on based on a prototype , so let’s first understand what is Prototype —</p><p>Prototypes are the mechanism by which JavaScript objects inherit features from one another.</p><pre>function Student() {<br>                this.name = &#39;John&#39;;<br>                this.gender = &#39;Male&#39;;<br>}<br><br>var studObj1 = new Student();<br>studObj1.age = 15;<br>alert(studObj1.age); // 15<br><br>var studObj2 = new Student();<br>alert(studObj2.age); // undefined</pre><p>As you can see in the above example, age property is attached to studObj1 instance. However, studObj2 instance will not have age property because it is defined only on studObj1 instance.</p><p>So what to do if we want to add new properties at a later stage to a function which will be shared across all the instances?</p><p>The answer is <strong>Prototype</strong>.</p><p>A prototype is an object that is associated with every functions and object by default in JavaScript, where function’s prototype property is accessible and modifiable and object’s prototype property is not visible.</p><p>Every function includes a prototype object by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*3gqJy3eXzxe0AyYFjhf5-A.png" /><figcaption>Prototype in JavaScript</figcaption></figure><p>The prototype object is a special type of enumerable object to which additional properties can be attached to it which will be shared across all the instances of its constructor function.</p><p>So, use prototype property of a function in the above example in order to have age properties across all the objects as shown below.</p><pre>function Student() {<br>                this.name = &#39;John&#39;;<br>                this.gender = &#39;M&#39;;<br>}<br><br>Student.prototype.age = 15;<br><br>var studObj1 = new Student();<br>alert(studObj1.age); // 15<br><br>var studObj2 = new Student();<br>alert(studObj2.age); // 15</pre><p>So to achieve inheritance in JavaScript we will prototypal inheritance —</p><p>let’s take an example —</p><pre>function Person(firstName, lastName) {<br>    this.FirstName = firstName || &quot;unknown&quot;;<br>    this.LastName = lastName || &quot;unknown&quot;;<br>};<br><br>Person.prototype.getFullName = function () {<br>    return this.FirstName + &quot; &quot; + this.LastName;<br>}</pre><p>Above we have created Person function with two parameters and we also added getFullName method as a prototype object.</p><p>Now, we want to create Student class that inherits from Person class so that we don’t have to redefine FirstName, LastName and getFullName() method in Student class. The following is a Student class that inherits Person class.</p><pre>function Person(firstName, lastName) {<br>    this.FirstName = firstName || &quot;unknown&quot;;<br>    this.LastName = lastName || &quot;unknown&quot;;            <br>}<br><br>Person.prototype.getFullName = function () {<br>    return this.FirstName + &quot; &quot; + this.LastName;<br>}<br>function Student(firstName, lastName, schoolName, grade)<br>{<br>    Person.call(this, firstName, lastName);<br><br>    this.SchoolName = schoolName || &quot;unknown&quot;;<br>    this.Grade = grade || 0;<br>}<br>//Student.prototype = Person.prototype;<br>Student.prototype = new Person();<br>Student.prototype.constructor = Student;<br><br>var std = new Student(&quot;James&quot;,&quot;Bond&quot;, &quot;XYZ&quot;, 10);<br>            <br>alert(std.getFullName()); // James Bond<br>alert(std instanceof Student); // true<br>alert(std instanceof Person); // true</pre><p>In this way we can implement inheritance in JavaScript .</p><h4>Polymorphism —</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*XG7aTmd_O10xEJ-8XTqcOQ.png" /><figcaption>Polymorphism</figcaption></figure><p>In general object-oriented programming, polymorphism is a concept where we can perform a single action in a different way depending on the data type or the no of arguments.</p><p>You can understand polymorphism by taking yourself as an example because your behaviour depends on the situation like if you are in classroom you will behave like a student , if you are at home you will behave like son/daughter, So here for a single action there are different form this is what we call polymorphism.</p><pre>var shape = function (){};<br>	shape.prototype.draw = function(){<br>		return &quot;i am generic shape&quot;;<br>	}<br>	//circle<br>	var circle = function(){}<br>	circle.prototype = Object.create(shape.prototype);<br>	circle.prototype.draw= function(){<br>		return &quot;i am a circle&quot;;<br>	}<br>	//triangle<br>	var triangle = function (){}<br>	triangle.prototype = Object.create(shape.prototype);<br>	triangle.prototype.draw= function(size){<br>		return &quot;this is triangle&quot;;<br>	}<br>	//printing shapes<br>	var shapes = [new shape(), new circle(), new triangle(23)];<br>	shapes.forEach (function (shapeList){<br>		console.log(shapeList.draw());<br>	});</pre><p>Here both the circle and triangle function inherit shape function and override the draw method.</p><h3>Note —</h3><p>These are not the only ways you can implement object-oriented programming in JavaScript, this is very flexible in this regard.</p><h3>Thanks for the reading:)</h3><p>if you like this article please 👏.</p><p>This article is the part of series article for JavaScript for begniner —</p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-01-getting-started-56a4e55f43bf">JavaScript for Beginners(01):Getting started.</a></p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-02-dom-manipulation-crash-course-12194e195e2">JavaScript for Beginners(02): DOM Manipulation Crash Course</a></p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-03-understand-hoisting-in-javascript-4d0df03e60cc">JavaScript for Beginners(03): Understand Hoisting in JavaScript.</a></p><p><a href="https://medium.com/datadriveninvestor/javascript-for-beginners-04-function-in-javascript-dcc6ca18b3f8">JavaScript for Beginners(04):Everything about JavaScript function</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd5dee141e12" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/javascript-for-beginners-05-object-oriented-programming-made-simple-dd5dee141e12">JavaScript For Beginners(05):Object-Oriented Programming Made Simple.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>