|
Jayant Singh Parmar Oodles

Jayant Singh Parmar (Frontend-Sr. Lead- Frontend Development)

Experience:7+ yrs

Jayant has more than 5+ years of industry experience as a frontend developer. He has good knowledge of technologies like Angular, reactJS, HTML, CSS, javascript etc. He is proficient in building complex UI designs, implentation of complex logics on frontend, API integrations, development and deployments and have been part of successfully delivering services on various client projects like Virgin Media, Hp1t and Jabburr He is a quick learner and keen to learn new technologies.

Jayant Singh Parmar Oodles
Jayant Singh Parmar
(Sr. Lead- Frontend Development)

Jayant has more than 5+ years of industry experience as a frontend developer. He has good knowledge of technologies like Angular, reactJS, HTML, CSS, javascript etc. He is proficient in building complex UI designs, implentation of complex logics on frontend, API integrations, development and deployments and have been part of successfully delivering services on various client projects like Virgin Media, Hp1t and Jabburr He is a quick learner and keen to learn new technologies.

LanguageLanguages

DotENGLISH

Fluent

DotHINDI

Fluent

DotURDU

Fluent

Skills
Skills

DotAngular/AngularJS

80%

DotReact Native

80%

DotHTML, CSS

80%

DotJavascript

80%
ExpWork Experience / Trainings / Internship

Feb 2018-Present

Lead Frontend Development

Gurgaon


Oodles Technologies

Gurgaon

Feb 2018-Present

EducationEducation

2007-2010

Dot

University of Lucknow

Bachelor of Science-Computer Science

Top Blog Posts
Creating a REST api in C plus plus

This blog consists of the following parts:

  1. Tool required for the setup

  2. Steps involved in the setup

  3. Points to remember

  4. Creating a basic cutelyst application


 

  1. Tools required for the setup : Following tools are required for the setup

  • Cutelyst Framework - source - https://github.com/cutelyst/cutelyst
  • CMake - for Windows x64 platform - https://cmake.org/download/
  • Qt 5.6 or higher - https://www.qt.io/download (Qt 5.12.0 in my case)
  • Visual Studio 2017 Community.
  • Microsoft Visual C++ compiler (MSVC 2017 32bit in my case)

Note: I assume that Visual Studio, Qt and CMake are already set up on your computer.

 

  1. Steps involved in the setup

  • Download the cutelyst source from the GitHub link provided above and unzip it to the following location “C:\cutelyst-2.7.0”
  • Create a folder named cutelyst_build in the same location “C:\cutelyst_build”

  • Now open CMake-GUI.

Note: Open CMake-GUI with admin rights to avoid errors due to access permissions

  • Provide source(C:\cutelyst-2.7.0) and build(C:\cutelyst_build) paths.??
  • Now click on the Configure button and select MS Visual Studio 2017 as a generator and select “Use native compilers” and then click OK.
  • At this, you will get some errors but don’t worry just look for the red values, update them and then again click on Configure button

Note: The possible errors at this point may be regarding the paths of  Qt5 and Cutelyst2Qt5. Just update the following entries in the CMake as mentioned below.

Qt5_DIR => “C:\Qt\5.12.0\msvc2017\lib\cmake\Qt5”

Cutelyst2Qt5_DIR => “C:\cutelyst_build\Cutelyst\Debug”

Create a folder named cutelyst in “C:\Program Files(x86)” and then click on Configure, you will see “Configuration done” in the output window in the CMake-GUI.

 

  • Click on Generate button and you will see “Generating done” message in the CMake-GUI output window.
  • Now open Qt 5.12.0 (MSVC 2017 - 32bit) command prompt with admin rights and navigate to your cutelyst build folder “C:\cutelyst_build”  and run the following command

        cmake -- build. --config Release

                 Once build is finished then run the following command

        cmake -- build. --target INSTALL --config Release

                 That’s it, cutelyst installation is done.

 

  1. Points to remember

  • Install all the required tools before starting the installation.
  • Open all the tools with admin rights to avoid errors regarding access permissions.
  • Source and build paths should not contain any spaces
  • Make sure you select the appropriate Qt version and C++ compiler.

Qt 5.12.0 and MSVC 2017(32bit) in my case

  • Same version(as of C++ compiler) of Visual Studio should be installed on your computer prior to installation

 

  1. Creating a basic cutelyst application

  • Before creating an application add the following path variable to your system settings “C:\Program Files (x86)\cutelyst\bin”
  • In the MSVC command prompt navigate to your desired location(say C:\Cutelyst_Apps) and run the following command cutelyst2 --create-app Hello

A folder Hello will be created inside the Cutelyst_App folder.

  • Navigate to “C:\Cutelyst_Apps\Hello\build” and run the following command

                  cmake --build . --config Debug

                  Now the libraries will be generated inside the following path

                  “C:\Cutelyst_Apps\Hello\build\src\Debug”

                  Note: If you can't find the build folder you can create it manually

 

  • Navigate to “C:\Cutelyst_Apps\Hello” and run the following command

cutelyst2 -r --server --app-file .\build\src\Debug\Hello.dll

 

  • Test the application by running the url “localhost:3000” in your web browser. You will see the message “Welcome to Cutelyst!” in your web browser.

That’s it, cutelyst app created successfully.

 
Custom PDF viewer using javascript

Hi everyone, in this blog, we will learn how to show a PDF document on a web page. We will not only load a PDF file into a web page but also create pagination if it is a multi-page PDF document and also display an error message if a PDF file not found. In this little project, we will use pdf.js to create our custom pdf view interface and pagination using javascript. We will be using modern syntaxes such as arrow functions and promises. So we will keep it very very simple, we will create our script, our HTML, and a little bit of CSS for the file navigation part and showing error messages. So let's get started and create a project structure as listed below.

PDF_viewer (project root)

  • index.html
  • docs
    • sample.pdf
  • css
    • style.css
  • js
    • main.js

and that should be for our structure.

We will also use font-awesome so you can quickly grab the CDN.

Now head over to your index.html and add the following code.

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <meta http-equiv="X-UA-Compatible" content="ie=edge" />
            <link
            rel="stylesheet"
            href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
            integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
            crossorigin="anonymous"
            />
            <link rel="stylesheet" href="css/style.css" />
            <title>PDF Viewer</title>
        </head>
        <body>
            <div class="top-bar">
            <button class="btn" id="prev-page">
                <i class="fas fa-arrow-circle-left"></i> Prev Page
            </button>
            <button class="btn" id="next-page">
                Next Page <i class="fas fa-arrow-circle-right"></i>
            </button>
            <span class="page-info">
                Page <span id="page-num"></span> of <span id="page-count"></span>
            </span>
            </div>

            <canvas id="pdf-render"></canvas>

            <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
            <script src="js/main.js"></script>
        </body>
        </html>
    

At this point, we have not added any CSS. We will do that last. So let's jump into our main.js and add the following code.

        const url = '../docs/pdf.pdf';

        let pdfDoc = null,
            pageNum = 1,
            ageIsRendering = false,
            pageNumIsPending = null;
            
        const scale = 1.5,
            canvas = document.querySelector('#pdf-render'),
            ctx = canvas.getContext('2d');
            
        // Render the page
        const renderPage = num => {
            pageIsRendering = true;
            
            // Get page
            pdfDoc.getPage(num).then(page => {
                // Set scale
                const viewport = page.getViewport({ scale });
                canvas.height = viewport.height;
                canvas.width = viewport.width;
            
                const renderCtx = {
                  canvasContext: ctx,
                  viewport
                };
            
                page.render(renderCtx).promise.then(() => {
                  pageIsRendering = false;
            
                  if (pageNumIsPending !== null) {
                    renderPage(pageNumIsPending);
                    pageNumIsPending = null;
                  }
                });
            
                // Output current page
                document.querySelector('#page-num').textContent = num;
            });
        };
            
        // Check for pages rendering
        const queueRenderPage = num => {
            if (pageIsRendering) {
                pageNumIsPending = num;
            } else {
                renderPage(num);
            }
        };
            
        // Show Prev Page
        const showPrevPage = () => {
            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            queueRenderPage(pageNum);
        };
            
        // Show Next Page
        const showNextPage = () => {
            if (pageNum >= pdfDoc.numPages) {
                return;
            }
            pageNum++;
            queueRenderPage(pageNum);
        };
            
        // Get Document
        pdfjsLib
            .getDocument(url)
            .promise.then(pdfDoc_ => {
                pdfDoc = pdfDoc_;
            
                document.querySelector('#page-count').textContent = pdfDoc.numPages;
            
                renderPage(pageNum);
            })
            .catch(err => {
                // Display error
                const div = document.createElement('div');
                div.className = 'error';
                div.appendChild(document.createTextNode(err.message));
                document.querySelector('body').insertBefore(div, canvas);
                // Remove top bar
                document.querySelector('.top-bar').style.display = 'none';
            });
            
        // Button Events
        document.querySelector('#prev-page').addEventListener('click', showPrevPage);
        document.querySelector('#next-page').addEventListener('click', showNextPage);            
    

So at this point, everything will be working well. Now we will move on to our styling, so let's head over to your style.css and add the following rules.

            * {
                margin: 0;
                padding: 0;
              }
              
              .top-bar {
                background: #333;
                color: #fff;
                padding: 1rem;
              }
              
              .btn {
                background: coral;
                color: #fff;
                border: none;
                outline: none;
                cursor: pointer;
                padding: 0.7rem 2rem;
              }
              
              .btn:hover {
                opacity: 0.9;
              }
              
              .page-info {
                margin-left: 1rem;
              }
              
              .error {
                background: orangered;
                color: #fff;
                padding: 1rem;
              }    
    

So from now on, if you have to include a pdf on your website or on your application, you can embed it however you want and have a UI of whatever kind you want which comes in really handy. So that's it for now, I hope you find it useful to implement in a real website or application. 

 

Custom Styled Javascript Console Logging

Are you in the mood for a lightweight and fun project? We are going to build a custom-styled console logging class that you can use in place of console.log()! We’re going to add some color and variation to our consoles. This should take no more than ten minutes. To make things simpler, we can use CodeSandbox. It’s especially good for quick projects like this. We’ll be using the Vanilla template, which utilizes Parcel to give us features like bundling, importing, ES6 classes, etc.

I like to outline what my code should look like before I get started. Something like:

        import CustomLogging from './CustomLogging';        const custom = new CustomLogging;        const error = new CustomLogging('error');        error.setBodyStyle({ color: 'red', size: '2rem' });        // the output        console.log('Regular log.');        custom.log('Hello there!');        error.log('Something bad happened!');            

In the console tab (at the bottom of CodeSandbox), this outputs:

We’re going to use an ES6 class to deliver this functionality. Because of Parcel, we can import/export this class to be used as a “package” of sorts. At it’s core this project will utilize the %c feature in the regular console.log() method.

First, clear the initial code in index.js so we’re starting fresh. Be sure to save as you go.Create a new CustomLogging.js file in the src directory. Here’s a basic outline:

        class CustomLogging {            log() {              console.log("Hey, good lookin`!");            }        }                  export default CustomLogging;            

You’ll notice that this isn’t dynamic - we’re simply trying to make sure it works. To get this to be logged to the console, head over to the index.js file where you’ll import the class, instantiate it, and then call the log() method.

        import CustomLogging from './CustomLogging';        const custom = new CustomLogging;                    custom.log();            

Now let’s pass in any message we want and begin some styling:

        class CustomLogging {            log(body = "" // defaults to empty string) {                  console.log(                    `%c${body}`, // everything after the %c is styled                    `color: green; font-weight: bold; font-size: 2rem;`                  );            }        }                      export default CustomLogging;            

which is fired by: 

        custom.log('May the Force be with you.');            

Let’s create a constructor to set defaults. We’ll then add a method to modify the styling on the fly:

        class CustomLogging {            constructor() {                // choose whatever defaults you'd like!                this.body = {                    color: "#008f68",                    size: "1rem"                  };            }                          setBodyStyle({ color, size }) {                // this will only set a value that is passed-in                if (color !== undefined) this.body.color = color;                if (size !== undefined) this.body.size = size;            }                          log(body = "") {                // adds dynamic styling via the template literals                console.log(                    `%c${body}`,                    `color: ${this.body.color}; font-weight: bold; font-size: ${                      this.body.size                    };                    text-shadow: 0 0 5px rgba(0,0,0,0.2);`                );            }        }                      export default CustomLogging;          

And again, we’ll use it:

        custom.setBodyStyle({ color: 'red' });        custom.log('Anger, fear, aggression; the dark side of the Force are they.');          

Lastly, we’ll add a title into the constructor so that different instances can display their label:

        class CustomLogging {            constructor(title) {                this.title = {                    body: title || "---",                    color: "darkgrey",                    size: "1rem"                };                              this.body = {                    color: "#008f68",                    size: "1rem"                };            }                          setTitleStyle({ color, size }) {                if (color !== undefined) this.title.color = color;                if (size !== undefined) this.title.size = size;            }                          setBodyStyle({ color, size }) {                if (color !== undefined) this.body.color = color;                if (size !== undefined) this.body.size = size;            }                          log(body = "") {                // the second line is now the body because the first references the content after the first %c for the title                console.log(                    `%c${this.title.body} | %c${body}`,                    `color: ${this.title.color}; font-weight: bold; font-size: ${                      this.title.size                    };`,                    `color: ${this.body.color}; font-weight: bold; font-size: ${                      this.body.size                    }; text-shadow: 0 0 5px rgba(0,0,0,0.2);`                );            }        }                      export default CustomLogging;      

Invoke it with:

        import CustomLogging from './CustomLogging';        const custom = new CustomLogging;        const error = new CustomLogging('error');        error.setBodyStyle({ color: 'red', size: '2rem' });                    console.log('Regular log..');        custom.log('Hello there!');        error.log('Something bad happened!');      

We did it! Your console should now match the example at the top of the post. Pat yourself on the back, show a friend, or do whatever floats your boat.

 

Understanding Webpack

Hi everyone, this blog is my attempt to document how webpack can help us. We use Webpack to bundle our own products, as well as using it with some of our framework examples. Although there are alternatives to Webpack, it is still very popular and with version 2.2 recently released I believe it will remain so for quite a while yet.

Webpack is a module bundler. It takes disparate dependencies, creates modules for them and bundles the entire network up into manageable output files. This is especially useful for Single Page Applications (SPAs), which is the defacto standard for Web Applications today.

Let’s assume we have an application that can perform two simple mathematical tasks — sum and multiply. We decide to split these functions into separate files for easier maintenance:

        <html>
        <head>
            <script src="src/sum.js"></script>
            <script src="src/multiply.js"></script>
            <script src="src/index.js"></script>
        </head>
        </html>
    
        var totalMultiply = multiply(5, 3);
        var totalSum = sum(5, 3);
        console.log('Product of 5 and 3 = ' + totalMultiply);
        console.log('Sum of 5 and 3 = ' + totalSum);        
    
        var multiply = function (a, b) {
            var total = 0;
            for (var i = 0; i < b; i++) {
                total = sum(a, total);
            }
            return total;
        };        
    
        var sum = function (a, b) {
            return a + b;
        };        
    

The output of this would be:

Product of 5 and 3 = 15

Sum of 5 and 3 = 8

From the above code you can see that both multiply.js and index.js depend on sum.js.If we get the order wrong in index.html our application won’t work. If index.js is included before either of the other dependencies or if sum.js is included after multiply.js we will get errors. Finally, by using global variables, we risk other code overwriting our variables, causing hard to find bugs. Webpack can convert these dependencies into modules?—?they will have a much tighter scope (which is safer). Additionally, by converting our dependencies into Modules, Webpack can manage our dependencies for us?—?Webpack will pull in the dependant Modules at the right time, in the correct scope (we’ll see this in more detail later).

Making Dependencies Available, And Linking Them:

For our initial setup, we’ll use the CommonJS module syntax. There are other options (AMD, ES2015) but for now we’ll use CommonJS and later move to ES2015.CommonJS uses module.exports to export - or make available - functions or variables to other code. It uses require to then pull in these exported values.

        <html>:
        <head>:
            <script src="./dist/bundle.js">:</script>:
        </head>:
        </html>:        
    
        var multiply = require('./multiply');
        var sum = require('./sum');
        var totalMultiply = multiply(5, 3);
        var totalSum = sum(5, 3);
        console.log('Product of 5 and 3 = ' + totalMultiply);
        console.log('Sum of 5 and 3 = ' + totalSum);        
    
        var sum = require('./sum');
        var multiply = function (a, b) {
            var total = 0;
            for (var i = 0; i < b; i++) {
                total = sum(a, total);
            }
            return total;
        };
        module.exports = multiply;        
    
        var sum = function (a, b) {
            return a + b;
        };
        module.exports = sum;        
    

Notice that we’ve made both sum and multiply available to other code and we've pulled in these exported functions in both multiple.js and index.js.Notice too that our index.html now only needs to pull in a single file — bundle.js.This is great! We now no longer have to worry about dependency order. We can expose what we want and keep other code effectively private. We also reduce web calls from 3 (sum.js, multiply.js and index.js) to a single call — this will help speed loading times.

Webpack Initial Configuration:

For the above to work, we need to do some initial Webpack configuration as shown below:

        var path = require('path');
        module.exports = {
            entry: './src/index.js',
            output: {
                path: path.resolve(__dirname, './dist/),
                filename: 'bundle.js
            }
        }        
    

At a minimum, we need to tell Webpack what our application entry point is and what the resulting output should be.

entry: This is the main entry point of our application. This is where our initial loading and application logic will be. Webpack uses this as a starting point for its dependency tree walking. It will build up a dependency graph and create modules as necessary.

output.path: An absolute path for the resulting bundle. To make this cross platform and easy to use, we use a built-in Node.js function (path). This will help us to dynamically create an absolute path, relative to where we are.

output.filename: The filename of the resulting bundle. This can be anything, but by convention it's called 'bundle.js'

Note: __dirname is a Node.js utility variable - it is the directory name of the current file.

 

Looking at bundle.js

Looking at the resulting bundle.js can be very instructional (prettified and commented for easier navigation):

        // the webpack bootstrap
        (function (modules) {
            // The module cache
            var installedModules = {};
            // The require function
            function __webpack_require__(moduleId) {
                // Check if module is in cache
                // Create a new module (and put it into the cache)
                // Execute the module function
                // Flag the module as loaded
                // Return the exports of the module
            }


            // expose the modules object (__webpack_modules__)
            // expose the module cache
            // Load entry module and return exports
            return __webpack_require__(0);
        })
        /************************************************************************/
        ([
            // index.js - our application logic
            /* 0 */
            function (module, exports, __webpack_require__) {
                var multiply = __webpack_require__(1);
                var sum = __webpack_require__(2);
                var totalMultiply = multiply(5, 3);
                var totalSum = sum(5, 3);
                console.log('Product of 5 and 3 = ' + totalMultiply);
                console.log('Sum of 5 and 3 = ' + totalSum);
            },
            // multiply.js
            /* 1 */
            function (module, exports, __webpack_require__) {
                var sum = __webpack_require__(2);
                var multiply = function (a, b) {
                    var total = 0;
                    for (var i = 0; i < b; i++) {
                        total = sum(a, total);
                    }
                    return total;
                };
                module.exports = multiply;
            },
            // sum.js
            /* 2 */
            function (module, exports) {
                var sum = function (a, b) {
                    return a + b;
                };
                module.exports = sum;
            }
        ]);        
    

From this you can see that Webpack wraps each of our files into a module and passes them into the Webpack bootstrap as an array of Modules. For each module, it adds them to the Webpack, executes them and makes them available to other modules. It executes __webpack_require__(0) which looking at the array of modules is our index.js. The result is the output we started with, but with far easier dependency management and less web traffic! Brilliant!

Pros and Cons Of Using Web Development Frameworks

Hi everyone, in this blog, I am going to talk about the pros & cons of using a web development framework, that includes UI frameworks as well as front-end & back-end frameworks. So basically there are three types of frameworks in web development that can be categorized as shown below:

Types of frameworks:

  1. UI/CSS Frameworks: Bootstrap, Materialize, Bulma etc.
  2. Front End Javascript Frameworks: Angular, React, Vue etc.
  3. Backend Frameworks: Laravel, Express, Django etc.

So I will start off with some of the pros of using a UI/CSS framework like bootstrap. 

UI/CSS Framework PROS

  1. Faster Development & Prototyping: You get a faster UI development if you use something like bootstrap rather than writing your own CSS and what I really like about these frameworks is the prototyping aspect. So if you are focused on a product, then using something like bootstrap will allow you to don't have to spend much time on the UI and you can focus on the product, which happens in the real world.
  2. Responsive By Default: These frameworks are responsive by default, the grid system that they come with because they use mobile first approach so they look good on mobile devices. So you usually don't have to write a lot of media queries for responsiveness.
  3. Browser Compatibility: These frameworks are well tested on all of the modern browsers.
  4. Familiar To Other Developers:  Basically most of the developers are aware of the core classes of a popular UI framework like bootstrap. So it's easier to work on with a team. 
  5. Javascript Widgets/Plugins: Javascript widgets & plugins like modal, carousels, accordions etc. are available.
  6. Documentation & Support: Most of the documentation of these frameworks, is really good and it has some really good examples and a lot of times you can just copy and paste and change it to your liking.

UI/CSS Framework CONS

  1. Stops developers from learning CSS: It is not actually a con for the framework, it's just kind of an unfortunate side-effect, so a lot of people just learn the very basics of CSS and start using frameworks and when it comes to something like creating a custom theme, they are lost.
  2. Less Customization:  If you want your website to really different, you probably have to create your own UI and write your own custom CSS and you can't do it easily while using a framework.
  3. Many sites look the same: If you don't customize it enough, then yes. You can easily spot a bootstrap site if you are just using all the default classes with all the default colors
  4. Lots of overriding styles: One of the disadvantages of customization is sometimes it overrides style and I really don't like to do that because it feels messy to override styles and put the !important flag and stuff like that. What I would suggest is to download the source code and use SASS to.customise the variables to change the look and feel complete. 
  5. Dependence of jQuery for certain things: These frameworks have some dependence on jquery for certain things like modals, carousels etc.
JavaScript Higher Order Functions and Arrays

Hi everyone, in this blog, I am going to do something different that may not be enough for filling visually into the browser but it will really up your vanilla javascript game. So what I should do is talk about some of the higher order array methods as well as writing them in a shorter and more elegant way using ES6 arrow functions. So we will be working with the functions like forEach( ), filter( ), map( ), sort( ), and reduce( ). A lot of developers who are new to javascript are confused by them. Hopefully, this blog will clear it up for you and you can see what these methods actually do. I am not going to do anything too advanced but I will explain how they actually work. So learning these functions will really help you to be a better programmer.

Alright like I said this is not going to be like a project where we build something in the UI. We are just going to use the browser's console for our output. So if you want to follow along, all you have to do is create the following files.

  • index.html: Basic head, body tags and a h1 and a link to our main javascript file.
  • main.js: Our main javascript file.
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
        </head>
        <body>
            <h1>JavaScript higher order functions and arrays</h1>
            <h3>Note:
                <span style="color: red">Open your browser's console to see the output</span>
            </h3>
            <script src="main.js"></script>
        </body>
        </html>
    

In our main.js file we two arrays, one is "companies" which has just a bunch of objects and the second one is a simple array with numbers called "ages".

        const companies = [
            { name: "Company One", category: "Finance", start: 1981, end: 2004 },
            { name: "Company Two", category: "Retail", start: 1992, end: 2008 },
            { name: "Company Three", category: "Auto", start: 1999, end: 2007 },
            { name: "Company Four", category: "Retail", start: 1989, end: 2010 },
            { name: "Company Five", category: "Technology", start: 2009, end: 2014 },
            { name: "Company Six", category: "Finance", start: 1987, end: 2010 },
            { name: "Company Seven", category: "Auto", start: 1986, end: 1996 },
            { name: "Company Eight", category: "Technology", start: 2011, end: 2016 },
            { name: "Company Nine", category: "Retail", start: 1981, end: 1989 }
        ];
        
        const ages = [33, 12, 20, 16, 5, 54, 21, 44, 61, 13, 15, 45, 25, 64, 32];
    

The methods we are going to look at are as follows.

  1. forEach( ): It is actually a easy and a better way to loop through an array rather than using a for loop. It dosn't return anything but it's a much nicer and elegant way to loop through the data. I will also be comparing it with a basic for loop so you can see the difference. I have also attached the screenshots of output obtained form the browser's console.So let's take the following example.
            // Basic for loop
            console.log('----------Output of for loop-----------');
            for (let index = 0; index < companies.length; index++) {
                console.log('Companies', companies[index]);
            }
    
    

    Now let's use forEach loop.

            // 1. forEach(): Loops thorugh an array
            // ES5 Version
            console.log('----------Output of forEach()-----------');
            companies.forEach(function(company){
                console.log('Companies', company);
            });
                
            // ES6 Version
            companies.forEach((company) => {
                console.log('Companies', company);
            });
        

  2. filter( ): What filter does it actually allows us to filter the things out from an array. So let's say we want all the ages that are greater than or equal to 21, from the ages array.
            // 2. filter(): Filter things out of an array
            // Get 21 or older
            console.log('----------Output of filter()-----------');
            // ES5 Version
            const canDrink = ages.filter(function(age){
                if (age >= 21) {
                    return true
                }
            });
            console.log('21 or older', canDrink);
                
            //ES6 Version
            const canDrink = ages.filter(age => age >= 21);
            console.log('21 or older', canDrink);
        

    Let's take another example in which we will filter all the retail companies from the companies array. 

            // Fiter the retail companies
            // ES5 Version
            const retailCompanies = companies.filter(function (company) {
                if (company.category === 'Retail')
                    return true;
            });
            console.log('Retail Companies', retailCompanies);
                
            // ES6 Version
            const retailCompanies = companies.filter(company => company.category === 'Retail');
            console.log('Retail Companies', retailCompanies);
        

    Now let's filter the companies that started in the 80s

            // Get companies that started in 80s 
            const eightiesCompanies = companies.filter(company => (company.start >= 1980 && company.start < 1990));
            console.log('Companies started in 80s', eightiesCompanies);
        

    Let's take another exmple and filter out the companies that lasted for 10 years or more

            // Get companies that lasted for 10 years or more
            const lastedTenYears = companies.filter(company => (company.end - company.start >= 10));
            console.log('Companies lasted for 10 years or more', lastedTenYears);            
        

     

  3. map( ): Map works a little bit differently, instead of just filtering things out it creates a new array from the current array. So let's just grab all of the company names and put them into their own array.
            // 3. map(): Creates a new array from the current array
            // console.log('----------Output of map()-----------');
            // Create a new array of company names
            // ES5 Version
            const companyNames = companies.map(function(company){
                return company.name;
            });
            console.log('Company Names', companyNames);
                
            // ES6 Version
            const companyNames = companies.map(company => company.name);
            console.log('Company Names', companyNames);   
        

    Now let's create an array of strings and each string will be formatted like "Company Name [Start Year - End Year]"

            // Create an array of template strings like "Comapany Name [Start Year - End Year]"
            const testMap = companies.map(company => `${company.name} [${company.start} - ${company.end}]`);
            console.log('Template String', testMap);  
        

    Let's do one more example with map, let's use the ages array. So what we will do here is take each one and get the square root of each number

            // Create an array of sqaure roots of all ages
            const agesSquareRoots = ages.map(age => Math.sqrt(age));
            console.log('Square roots of ages', agesSquareRoots);  
        

  4. sort( ): It works similar to rest of these functions. So here we will sort the companies by start year.
            // 4. sort(): Sorts an array
            // console.log('----------Output of sort()-----------');
            // Sort the companies by the start year
            // ES5 Version
            const sortedCompanies = companies.sort(function(c1, c2){
                if (c1.start > c2.start) {
                    return 1;
                } else {
                    return -1;
                }
            });
            console.log('Companies sort by the start year', sortedCompanies);
                
            // ES6 Version
            const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1: -1));
            console.log('Companies sorted by the start year', sortedCompanies);  
        

    Let's do one more example with sort( ), let's sort the ages so we just have simple numbers array and we have to sort it from lowest to highest.

            // Sort ages
            const sortedAges = ages.sort((a, b) => a - b);
            console.log('Sorted Ages', sortedAges); 
        

  5. reduce( ): It can be used for a lot of things and it can get quite complicated but I am going to keep it simple. So let's add all of the ages together from the ages array. First I will do it with a for loop so you can see the difference. 
            // 5. reduce(): 
            console.log('----------Output of reduce()-----------');
            // Get sum of all ages
            // Using basic for loop
            let ageSum = 0;
            for (let index = 0; index < ages.length; index++) {
                ageSum += ages[index];
            }
            console.log('Sum of ages = ', ageSum);
                
            // ES5 Version
            const ageSum = ages.reduce(function(total, age) {
                return total + age;
            }, 0);
            console.log('Sum of ages = ', ageSum);
                
            // ES6 Version
            const ageSum = ages.reduce((total, age) => total + age, 0);
            console.log('Sum of ages = ', ageSum); 
        

    Let's do another example with reduce( ), let's get total years for all companies

            // Get total years for all comapnies
            // ES5 Version
            const totalYears = companies.reduce(function(total, company) {
                return total + (company.end - company.start);
            }, 0);
            console.log('Total years for all companies', totalYears);
                
            // ES6 Version
            const totalYears = companies.reduce((total, company) => total + (company.end - company.start), 0);
            console.log('Total years for all companies = ', totalYears); 
        

 

Now you can use any of these functions together to do certain things. I am going to give you an example how to combine these methods. What we will do is first use map( ) to multiply all ages by 2, next we will filter the ages that are greater than or equal to 40, then we will sort them from lowest to highest and at last we use reduce( ) to get the sum.

        // Combine Methods
        console.log('----------Output of combined methods-----------');
        const combined = ages
            .map(age => age * 2)          // multiply all ages by 2
            .filter(age => age >= 40)     // filter all ages greater than or equal to 40
            .sort((a, b) => a - b)        // sort all ages in ascending order
            .reduce((a, b) => a + b, 0);  // get sum of all ages
        console.log(combined);
    

Alright that is going to be it, what I would suggest for you is to maybe create your onw dataset and try to pluck things out, manipulate it, create new arrays from your own arrays, sort them and just try to do things on your own because you are not going to learn so much from just reading blogs. You have to experiment with your own things or maybe even use some kind of external APIs and see what you can do using these higher order functions.

You can download the source code here

Drag and Drop Using Pure Javascript

In this blog, we are going to look at javascript drag and drop events and for that, we are going to create a small application with a little HTML, CSS and javascript. In this application we are going to be able to grab an image and when we hover over any of the empty boxes it gets a little bit darker and it gets a different kind of border and we can drop it in any of these boxes. Now obviously this by itself is not really a full application but I am going to show you how to implement this type of UI so you could use it in anything where you want this kind of effect.

Alright so let's go ahead and get started. I am using VS Code, you can use whatever you like. So I am having a very basic project setup where I have three following files.

  • index.html : Main HTML page
  • style.css : Main stylesheet
  • main.js : Main javascript file

So for creating our HTML boilerplate, I am using emmet which is a very good VS Code extension. I highly recommend emmet if you use VS Code because it provides an ultrafast HTML & CSS workflow. HTML for this project is going to be very simple, I have five boxes(div) and each has a CSS class "empty" and one box is filled(with image) has a CSS class "filled"  and is placed inside an empty box and for that I am adding the following markup to our index.html file.

        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <meta http-equiv="X-UA-Compatible" content="ie=edge">
                <title>Drag & Drop Using Pure Javascript</title>
                <link rel="stylesheet" href="style.css">
            </head>
            <body>
                <div class="empty">
                    <div class="fill" draggable="true"> </div>
                </div>
                <div class="empty"></div>
                <div class="empty"></div>
                <div class="empty"></div>
                <div class="empty"></div>
                <script src="main.js"></script>
            </body>
        </html>
    

I have set the HTML-5 property "draggable" to true on the div having the "fill" class otherwise we will not be able to drag it and that's it for our HTML. So next we will move on to our style.css and add the following code to it. 

        body {
            background: darksalmon;
        }
          
        .fill {
            background-image: url('https://source.unsplash.com/random/150x150');
            position: relative;
            height: 150px;
            width: 150px;
            top: 5px;
            left: 5px;
            cursor: pointer;
        }
          
        .hold {
            border: solid 5px #ccc;
        }
          
        .empty {
            display: inline-block;
            height: 160px;
            width: 160px;
            margin: 10px;
            border: solid 3px salmon;
            background: white;
        }
          
        .hovered {
            background: #f4f4f4;
            border-style: dashed;
        }
    

For the "fill" class I am using an image as background and for that, I am using an API from  unsplash.com which give you a random image every time you reload the page.

Alright, now we can start on the javascript. Basically, we have two elements to work with the filled box and the empty ones. First of all, we have to declare two variables as shown below.

        const fill = document.querySelector('.fill');
        const empties = document.querySelectorAll('.empty');
    

I have created two variables "fill" and "empties" for the filled and empty boxes(div) respectively. Now we will add the event listeners for both variables.

        // Fill listeners
        fill.addEventListener('dragstart', dragStart);
        fill.addEventListener('dragend', dragEnd);

        // Loop through empty boxes and add listeners
        for (const empty of empties) {
            empty.addEventListener('dragover', dragOver);
            empty.addEventListener('dragenter', dragEnter);
            empty.addEventListener('dragleave', dragLeave);
            empty.addEventListener('drop', dragDrop);
        }
    

Now we will add the drag functions to handle the events for the "fill" variable. 

        // Drag Functions
        function dragStart() {
            this.className += ' hold';
            setTimeout(() => (this.className = 'invisible'), 0);
        }

        function dragEnd() {
            this.className = 'fill';
        }
    

dragStart( ) : called when we grab the image(filled box) and drag it.

dragEnd( ): called when we leave the image(filled box).

Now we will add the drag functions for the "empties" variable. 

        function dragOver(e) {
            e.preventDefault();
        }

        function dragEnter(e) {
            e.preventDefault();
            this.className += ' hovered';
        }

        function dragLeave() {
            this.className = 'empty';
        }

        function dragDrop() {
            this.className = 'empty';
            this.append(fill);
        }
    

Now our main.js file should look like as shown below. 

        const fill = document.querySelector('.fill');
        const empties = document.querySelectorAll('.empty');

        // Fill listeners
        fill.addEventListener('dragstart', dragStart);
        fill.addEventListener('dragend', dragEnd);

        // Loop through empty boxes and add listeners
        for (const empty of empties) {
            empty.addEventListener('dragover', dragOver);
            empty.addEventListener('dragenter', dragEnter);
            empty.addEventListener('dragleave', dragLeave);
            empty.addEventListener('drop', dragDrop);
        }

        // Drag Functions
        function dragStart() {
            this.className += ' hold';
            setTimeout(() => (this.className = 'invisible'), 0);
        }

        function dragEnd() {
            this.className = 'fill';
        }

        function dragOver(e) {
            e.preventDefault();
        }

        function dragEnter(e) {
            e.preventDefault();
            this.className += ' hovered';
        }

        function dragLeave() {
            this.className = 'empty';
        }

        function dragDrop() {
            this.className = 'empty';
            this.append(fill);
        }
    

Now you can try it, just reload the page and grab the image and as you hover over the boxes you will see the hover effect and when you drop, the image will be placed inside another box. You can also check it under the elements tab in your browser's developer console. So basically we are moving in around the DOM and this all is possible with the drag events and HTML-5 draggable property.

Hopefully, this explains drag and drop to you guys. Obviously, this is not a real application but you can use it in the UI of your application. For reference you can download the source code here.  

Simple Spinners Using Pure CSS

In this blog we are goin to create simple spinners using pure css and a little bit of javascript and for that we will be having a pretty basic project setup. We will be having three files index.html(our main html page), main.css(our main style sheet) and main.js(main javascript file). In our HTML page we will be having an h1 and a paragraph but if we reload the page we can see a little spinner in the middle of the screen, it is going to stay there for 4 seconds and then it will load the paragraph.

What we are going to focus on is to building the spinner on pure css. We are not using any css frameworks on GIFs. We are actually going to create three different versions. It is goig to be very easy, quick and painless. So lets head over to our VS Code or any other editor of your choice. Our HTML markup is very simple, you can use emmet to create out HTML boilerplate and edit it as given below.

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>CSS Spinners</title>                
            <link rel="stylesheet" href="style.css">
        </head>
        <body>
            <div class="main">
                <h1>Spinners using pure css</h1>
                <p>
                    Lorem ipsum dolor sit amet consectetur adipisicing elit. 
                    Facere assumenda recusandae quos quidem ducimus quod quae quia vitae nisi illum, 
                    ipsum fugiat iure nam sequi? Molestias quam totam a veniam.
                </p>
            </div>
            <script src="main.js"></script>
        </body>
        </html>            

You can open this HTML using live server which I would highly recommend if you use VS Code. Now we will head over to our main.css and add the following piece of code.

        /* Spinner 1 */
        .spinner-1:before {
            content: "";
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            left: 50%;
            width: 60px;
            height: 60px;
            margin-top: -30px;
            margin-left: -30px;
            border-radius: 50%;
            border: 3px solid lightgray;
            border-top-color: #cc000f;
            animation: spinner 0.7s linear infinite;
        }            

        @keyframes spinner {
            to {
              transform: rotate(360deg);
            }
        }
    

Similarly you create the remaining two types of spinners by adding the following code to your css file

        /* Spinner 2 */
        .spinner-2:before {
            content: "";
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            left: 50%;
            width: 60px;
            height: 60px;
            margin-top: -30px;
            margin-left: -30px;
            border-radius: 50%;
            border: 2px solid transparent;
            border-top-color: #cc000f;
            border-bottom-color: #cc000f;
            animation: spinner 0.7s ease infinite;
        }
            
        /* Spinner 3 */
        .spinner-3:before {
            content: "";
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            left: 50%;
            width: 60px;
            height: 60px;
            margin-top: -30px;
            margin-left: -30px;
            border-radius: 50%;
            border-top: 2px solid #cc000f;
            border-right: 2px solid transparent;
            animation: spinner 0.7s linear infinite;
        }
    

Now we will head over to our javascript file(main.js) and add the following script.

        document.querySelector(".main p").style.display = "none";
        document.querySelector(".main").classList.add("spinner-2");
            
        // Mimic Server Request
        setTimeout(() => {
            document.querySelector(".main").classList.remove("spinner-2");
            document.querySelector(".main p").style.display = "block";
        }, 4000);
    

The above script displays the spinner first and after 4 seconds the it displays the paragraph just like an actual server request. For complete code I have attached the project zip file.

Banner

Don't just hire talent,
But build your dream team

Our experience in providing the best talents in accordance with diverse industry demands sets us apart from the rest. Hire a dedicated team of experts to build & scale your project, achieve delivery excellence, and maximize your returns. Rest assured, we will help you start and launch your project, your way – with full trust and transparency!