Artificial Intelligence

Artificial intelligence (AI) is the broad branch of computer science. The goal of AI is to create systems that can function intelligently and independently. AI is the simulation of human intelligence processes by machines, especially computer systems. In computer science, artificial intelligence (AI), sometimes called machine intelligence, is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans. It is a fact that chatbots perform tasks on the concept of Artificial Intelligence (AI) and machine learning. The traditional goals of AI research include reasoning, knowledge representation, planning, learning, natural language processing, perception and the ability to move and manipulate objects. There are two ways AI works i.e. symbolic based and data based in which we need to feed a lot of information before it can learn. Particular applications of AI include expert systems, speech recognition and machine vision. Much of speech recognition is statistically based hence it is known as statistical learning. Humans can see with their eyes and process what they see, whereas this is a field of computer vision. Computer vision falls under the symbolic way for computers to process information. It  does image processing which is even though not related to AI but is required for computer vision. It does pattern recognition as well. Machines are better at pattern recognition because they can use more data and dimensions of data. We can replicate the structure and function of human brain we might be able to get cognitive capabilities in machines. It is also a field of neural networks and deep learning and we use those to learn complex things. If we get a network to scan images from left to right and top to bottom the convolution neural network work. The CNN is used to recognize objects in a scene. This is how computer recognition fits in and object recognition is accomplished through AI. AI can be categorized as either weak or strong. Weak AI, also known as narrow AI, is an AI system that is designed and trained for a particular task. Virtual personal assistants, such as Apple’s Siri, are a form of weak AI. Strong AI, also known as artificial general intelligence, is an AI system with generalized human cognitive abilities. In AI, we can get the neural network to remember the limited past.

An Intro into webpack

Among various module bundlers, webpack turns out to be the most popular and powerful one due to its many features like improved performance and load time, to name a few! If you’re not familiar with it, I hope this blog will get you started with this powerful tool.

So, What exactly is a webpack?

A webpack is a powerful module bundler for JavaScript applications that packages all the modules in your application into one or more bundles (often, just one) and serves it to the browser. However, Webpack is more than just a module bundler. With the help of loaders and plugins, it can optimize, transform and minify all types of files before serving them as one bundle to the browser. 

It takes in various assets, such as JavaScript, HTML, CSS, Fonts, and Images and then transforms these assets into a format that’s convenient to consume through a browser. And I think this is fair enough to go ahead with webpack.

Understanding core concepts:

There are 4 key concepts in webpack that will cover an overall view of webpack and it’s configuration. Let’s get started.

  1. Entry Point:

An entry point indicates which module, the webpack should use to begin building out its internal dependency graph. webpack will figure out the entry point’s dependencies. By default, its value is ./src/index.js, but you can specify a different (or multiple entry points) by configuring the entry property in the webpack configuration.

Include the following in the webpack.config.js file

module.exports = {
  entry: './path/to/my/entry/file.js'
  1. Output:

Output defines where to emit the bundled files and assets. The following snippet tells out how the output can be configured in webpack.config file.

const path = require('path');
module.exports = {
   entry: './path/to/my/entry/file.js',
   output: {
     path: path.resolve(__dirname, 'dist'),
     filename: 'my-first-webpack.bundle.js'
  1. Loaders: 

webpack understands only JS and JSON files, so in order to allow webpack to identify other file types, Loaders came into the picture. It defines the webpack to transform other types. It has two main properties, test, a regex pattern for testing the type of files and use for using the specific loaders for that type.

const path = require('path');
module.exports = {
   output: {
     filename: 'my-first-webpack.bundle.js'
module: {
    rules: [{ 
            test: /\.txt$/
            use: 'raw-loader' 
  1. Plugins: 

While loaders are used to transform various modules, plugins can be used to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables. Plugins are customizable through options. We need to require() a plugin and need to create an instance of that using the new operator.

const HtmlWebpackPlugin = require('html-webpack-plugin'); 
const webpack = require('webpack'); 
module.exports = {
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})

How webpack works?

Webpack seems to be a mystery in the JavaScript world. So let’s go ahead and get some working examples to understand how it works. But before that, let’s make some basic setup to proceed with.

npm i -D webpack webpack-cli

Also, add build scripts to package.json

  1. Bundling JS

Create an src folder because webpack always looks for a source folder and index.js file before bundling JS. Now, if you run the npm run build, a dist folder will be created along with a main.js file that bundles your source file.

  1. Bundling HTML

Create an index.html file under the source folder and add the created index.js file into the script tag. Now, if you run build, you’ll get a syntax error. By now, you should have probably known the reason behind it. Yes! webpack doesn’t recognize any other type except JS. So let’s configure webpack for fixing this.

Create a webpack.config.js file and pre-install a loader to allow webpack to transform HTML files.

npm i -D html-webpack-plugin html-loader

Then configure the installed loader into the webpack config file and after that, now webpack will be able to bundle the HTML files as well.

  1. Bundling Image

Webpack neither bundles images so that we need to install a loader to allow webpack to do that.

npm i -D file-loader

Then configure the loader in webpack and create an image folder and put an image inside that. Also, include the image in img tag inside the index.html file and run npm run build. Now webpack bundles your images as well.

  1. Bundling Scss

I hope now there is no need to say that again. So let’s get straight towards installing loaders for bundling styles and see it bundled after configuring that in webpack.

npm i -D node-sass style-loader css-loader sass-loader mini-css-extract-plugin


Let’s have a look into the final code structure of webpack.config.js after all the above configurations.

const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
   module: {
       rules: [{
               test: /\.html$/,
               use: [{
                   loader: "html-loader",
               test: /\.(png|svg|jpg|gif)$/,
               use: [
               test: /\.scss$/,
               use: [
                   'style-loader', 'css-loader', 'sass-loader'
   plugins: [
       new HtmlWebpackPlugin({
           template: "./src/index.html",
           filename: "./index.html"
       new MiniCssExtractPlugin({
           filename: "[name].css",
           chunkFilename: "[id].css"



Speech Recognition with Javascript

Have you ever wondered how marvelous the technology is growing and has brought tremendous improvements in our lives? The rise of Artificial Intelligence and Machine Learning indicates that Robots and machines are our new human model in the future. So, what else we’ll do in this tech world without getting updated with technology. Let’s get started with the most popular AI technology i.e., Speech Recognition.

Voice is the future as well as the present. So anything that you brand with voice is going to be a massive hit. Because humans are fascinated by a machine that can understand us! Let me bring some statistics of voice recognition used almost everywhere.

According to Adobe Analytics, 71% of owners of smart speakers like Amazon Echo and Google Home use voice assistants at least daily, and 44% using them multiple times a day.

Over 76% of smart speaker owners increased their usage of voice assistants in the last year.

So, 50% of searches will be voice by 2020.

A little while ago, I got an opportunity to implement the Speech recognition to one of our Applications. I was really overwhelmed to work on the most talked technology and bumped into the google search about the possible ways to implement the same. I’ve come across several npm modules, most of them are really cool to proceed with. Amongst various npm modules and technologies, I found this JavaScript web speech API is so simple and accurate to go with the speech recognition process.

It is a very powerful browser interface that allows JavaScript to have access to a browser’s audio stream and convert that to text. The Web Speech API is actually separated into two independent interfaces. We have SpeechRecognition for understanding human voice and turning it into text (Speech -> Text) and SpeechSynthesis for reading strings out loud in a computer-generated voice (Text -> Speech). 

The first thing that we need to do is to check the Browser compatibility table carefully before using this in your work or else you would be jammed with errors. 

Note: I’ll list down the things that are implemented in Angular application and I don’t think there will be much difference in implementing this in other frameworks of JS.

Voice to Text


Let’s create an interface for the webkitSpeechRecognition like this,

export interface IWindow extends Window {
    webkitSpeechRecognition: any;


Now initialize the webkitSpeechRecognition to a variable like this,

const { webkitSpeechRecognition }: IWindow = window as IWindow;

   this.recognition = new webkitSpeechRecognition();


There are some properties to make the speech API to function as per the configuration of that.  

The continuous property controls whether continuous results are returned for each recognition or only a single result. It defaults to single results (false.)

The interimResults property controls over the display of results. If set true, the results will be streaming live. The default value for interimResults is false which displays the text at the end.

We could also set the language, grammar and various others through its properties.

this.recognition.continuous = true;

this.recognition.interimResults = true;

this.recognition.lang = 'en-US';

All set. We’re done with the initial setup without any installations. We made it too simple and Now it’s good to go! 

Event Handlers

There are many event handlers in this API where you can track every event and perform whatever you want to. The following are the most used events.

  • onstart: This event is triggered when speech recognition is started. This is where we could show some notifications to the user that they can start speaking.
  • onresult: This is the most important event where we could track this and get the text string that is processed from a user’s speech recognition.
this.recognition.onresult = (event) => {

     let interimTranscript = '';

     let finalTranscript = '';

     for (let i = event.resultIndex; i < event.results.length; ++i) {

       if (event.results[i].isFinal) {

         finalTranscript += event.results[i][0].transcript;

       } else {

         interimTranscript += event.results[i][0].transcript;



     this.message += finalTranscript; // Processed message

  • onerror: This is as important as handling onresult because the user might not know when their process stopped due to some reasons. So notify the user regarding this error and try to restart or stop the recognition or do whatever!
  • onend: A simple event that gets triggered when our recognition is stopped. 


There are three important methods in web speech API which is highly useful to invoke the actual speech recognition functions. Just keep reminded that only after calling methods, the respective events will get triggered. So let’s know when to call a method.

  • start(): It starts the speech recognition service listening to incoming audio with intent to recognize grammar associated with the API.
  • stop(): It stops the speech recognition service from listening to the incoming audio and attempts to return a result using the audio captured so far.
  • abort(): It stops the speech recognition service from listening to the incoming audio and doesn’t attempt to return a  result.

Text to Speech

Actually, text to speech is really very easy. It is accessible through the speechSynthesis object and there are a couple of methods for playing, pausing and other audio related stuff like changing the pitch, rate, and even the voice of the reader. But we can do it simply with the speak() method. Here is the entire code needed to read out a string.

textToSpeech(message) {

   const speech = new SpeechSynthesisUtterance();

   // Set the text and voice attributes.

   speech.text = message;

   speech.volume = 1;

   speech.rate = 1;

   speech.pitch = 1;


When this function is called, a robot voice will read out the given string, doing its best human impression.


It was cool. Isn’t it? Since conversational user interfaces and voice assistants are becoming more popular, we can build that with this simple and cool web speech API. I hope this blog has given some quick and simpler ways to implement speech recognition. Adding voice-based user interaction to your application would be a great form of user experience. So what are you waiting for? Just go ahead and do some wonder with voices.




Routing in nativescript-vue

I’m a big fan of Vue JS. So, when heading into mobile app development, Native script was the one thing which made me excited to work on. For those who are new to this, Nativescript is an open source framework which is used to create true native mobile apps for both Android and IOS. Nativescript supports Angular, Vue, Vanilla JS and Typescript. It is known for its performance, compared to other mobile app development frameworks like react native and ionic.

Here in this blog, we are going to focus on nativescript-vue routing…

Nativescript-vue is basically, Nativescript core combined with Vue JS.



How do we implement routing in nativescript-vue?

The shocking news here is, Vue routing is not supported in nativescript-vue. The Nativescript community is currently working on it. But for now, we have to go with manual routing methods.

oh my god


Let’s go ahead with manual routing…

To implement manual routing, you just need to know the following three methods:

  1. $navigateTo
  2. $navigateBack
  3. $showModal
  • $navigateTo:

The functionality of $navigateTo is to redirect from one component to another. This method can be used in the view and in the methods like given below:

Consider a scenario where the current component should be redirected to homePage component on click of the “Go” button. We use the $navigateTo methods like:

<Button text="Go" @tap="$navigateTo(homePage)" />

Or we could add in the method like :

<Button text="Go" @tap="goToHomePage" />

goToHomePage() {



There might be a scenario where we need to pass data from one component to another component. In that case, the data can be passed as props using the $navigateTo method by.

this.$navigateTo(ComponentName, {

  props: {

   // pass the data as an object here




What else we can do with “$navigateTo”?

This method also gives us properties to apply transitions while navigating to the next page.

There are three ways to set the transition:

  1. transition: Applies on all platforms.
  2. transitioniOS: Applies only to IOS.
  3. transitionAndroid: Applies only to Android.

The default transition is “platform”.

this.$navigateTo(NextComponent, {

  transition: {

     name: 'flip',

    duration: 2000,



The below listed are the available transitions:

  1. curl (same as curlUp) (iOS only)
  2. curlUp (iOS only)
  3. curlDown (iOS only)
  4. explode (Android Lollipop(21) and up only)
  5. fade
  6. flip (same as flipRight)
  7. flipRight
  8. flipLeft
  9. slide (same as slideLeft)
  10. slideLeft
  11. slideRight
  12. slideTop
  13. slideBottom

Another important property is clearHistory.

“clearHistory” is used to clear the navigation history. It accepts a boolean value. Setting it to “true”, clears the navigation history.

There are still a few other things that $navigateTo method can do. Refer here for the properties that are accepted by this method.

  • $navigateBack:

This method is used to navigate back to the previous page. It is used like:

<Button text="Back" @tap="$navigateBack" />
  • $showModal:

This method is used to display the component inside a modal.

For closing the modal we use “$modal.close”. Props are passed as an option to the $showModal as the following:

this.$showModal(Component, { props: { message: “Props is passed here”  }});

That’s it…. We have now mastered manual routing in nativescript-vue by learning simple three methods. Hope this blog was helpful and let me know your thoughts on this in the comments!

Thanks for reading!



Array methods in Javascript

Array is one of the most important and frequently used concepts in JS. If someone raises the question “What is an array?”, we used to say,

“An array is a homogeneous collection of elements”.

My own definition of the array is,

It is a data structure used for arranging the elements or data as a group and each element can be accessed through its index.

To develop a JS enabled application, we should know this basic concept of arrays and the methods to be used.

For e.g:

const sampleArray = [  ‘HTML’  ,  ‘JavaScript’  ,  ‘ES6’ ]


sampleArray [ 0 ] – ‘HTML’

sampleArray [ 1 ] – ‘JavaScript’

sampleArray [ 2 ] – ‘HTML’

Now, let us see some most commonly used array methods with simple examples

  • length:

To find the length or size of a particular array.

Eg: console.log(sampleArray.length); 

Output: 3
  • Adding an element to an array:
  1. push:

    To add an element at the end of an array.

    Eg: sampleArray.push(‘NodeJS’); 
    Output:  [  ‘HTML’  ,  ‘JavaScript’  ,  ‘ES6’ ,  ‘NodeJS’ ]
  2. unshift:

    To add an element at the front of an array.

    Eg: sampleArray.unshift(‘NodeJS’); 
    Output:  [ ‘NodeJS’ ,   ‘HTML’  ,  ‘JavaScript’  ,  ‘ES6’  ]
  • Removing element(s) from an array:
  1. pop:

    To remove the last element from an array.

    Eg: sampleArray.pop(); 
    Output:  [  ‘HTML’  ,  ‘JavaScript’ ]

    Here ES6 is removed as it was at the end of the array.

  2. shift:

    To remove the first element in the array.

    Eg: sampleArray.shift(); 
    Output:  [  ‘JavaScript’  ,  ‘ES6’  ]

    Here HTML is removed as it was the first element in the array.

  3. Remove an item by index position – splice(pos,1)

    To remove an element by index position.

    Eg: sampleArray.splice(2, 1);
    Output:  [  ‘HTML’ ,  ‘JavaScript’  ]

    Here ES6 is removed as it was present in the index 2 and the second parameter specifies the number of elements to be removed.

  4. Remove multiple items – splice(pos,n)

    To remove more than one elements based on the index position.
    Here n specifies the number of elements to be removed from the specific index pos.

    Eg: const removedItems = sampleArray.splice(1 , 2);
    Output:  sampleArray = [  ‘HTML’  ]
    removedItems = [  ‘JavaScript’ , ‘ES6’  ]

     Here both Javascript(index-1)  and ES6(index-2)  are removed and pushed to removedItems.

  • Copying an array:
  1. slice:
    To make a copy of an array with all its elements.

    Eg: const copyOfArray = sampleArray.slice();
    Output:  copyOfArray = [  ‘HTML’  ,  ‘JavaScript’  ,  ‘ES6’ ,  ‘NodeJS’ ]
  • Find the existence of an element:
  1. includes():
    To find whether an element present in an array or not.

    Eg: var isPresent = sampleArray.includes(‘ES6’);   // returns true
    var isPresent = sampleArray.includes(‘MongoDB’);   // returns false
  • Merging of arrays:
  1. concat():
    To combine/merge two or more arrays to form a new array.

    Eg:  var array1 = ['a', 'b', 'c'];
    var array2 = ['d', 'e', 'f'];
    Output:  [ 'a', 'b', 'c', 'd', 'e', 'f' ];
  • Operations/Functions that return a new array:
  1. filter:
    This returns a new array with the elements that pass the conditions given in the function.

    const filteredArray = sampleArray.filter(element => element.length < 5);      
    Output:  [  ‘HTML’   ,  ‘ES6’  ] , Here the length of each element is less than 5.
  2. map:
    Here, the given function is executed for each element of the array and the result will be pushed to a new array.

    Eg:     const sampleArray = [ 4, 2, 34, 50 ]
    const mappedArray  = => element*2); 
    Output:  [ 8 , 4  , 68 , 100 ]
  • Looping through an array:
    1. for loop.
    2. forEach
    3. for of
    4. for in
    5. Map
    6. Filter

These are some of the methods which we can use to loop through an array.

And yes…We came to an end and I hope this blog on frequently used array methods will be useful to develop a js-based application. For more methods, refer the below link.


Reactive Forms (Angular)

We all know that Angular Application is a reactive system. We have two categories of form structures in Angular:

  1. Reactive Forms
  2. Template Driven Forms.

In template driven forms, the template directives are used. Whereas in reactive forms, we could build our own representation of the form in the components. Thus, we could always opt for Reactive Forms.

Let’s begin by knowing the terminologies of reactive forms.

  • formControl
  • formGroup
  • formArray
  • controlValueAccessor

In this blog, we are going to look through formControls and formGroup.

Before beginning, do not forget to import the module (ReactiveFormsModule) and import the classes (FormControl, FormGroup, FormBuilder, Validators)

Imagine you have a form with the following fields:

  1. Name
  2. Age
  3. School
  4. Class
  5. Rank

So here, each field will be having different data types (such as alphabets, numbers, etc). Thus, in reactive forms, validating the fields become very easy using the built-in properties. Also, it is very easy for us to group the individual forms and make the necessary changes.

Let’s start with formControl:
Each field is recognized using the formControls for validation. Thus, we will be setting formControl for each field. Also, default values to the fields can also be set up initially.

In .html file, add:

<input type="text" [formControl]="name">

In .ts file, add:

name = new FormControl('any default values');

And then we go for formGroup:
These individual form controls can be grouped together for better handling of validation stuff and named as formGroup.

Let the HTML file remain the same.
In .ts file, add:

formGroupVariable = new FormGroup({
name = new FormControl('Smith Katana'),
age: new FormControl(12),

Now using the formGroupVariable, several validations, customizations can be done using the inbuilt methods. Following are some of them:

In .ts file, add :

name = new FormControl('any default values', {validators: Validators.required, updateOn: 'blur'});

Here, in the second parameter, we could use the Validators Object for validations. Refer the following link for Validators API reference:

Also updateOn key will intimate the validators to validate only after every blur to avoid validations for every keystroke.

We could also add our own customized method validator by adding the method instead of Validator object as follows:


In .ts file, add :

name = new FormControl('any default values',validatorMethod);

function validatorMethod(name: FormControl) {
//custom validations

Note* This method will be called for every keystroke

If you want to have a validation like to submit the form if any of the validations have been passed and it is not necessary that all the fields should be passed. But how do we do that?

formGroupVariable.patchValue('name', { onlySelf: true });

….Simple right?

To enable or disable the form use,

formGroupVariable.enable() && formGroupVariable.disable()

And also to disable a particular form control initially we could use the disabled attribute,


name: new FormControl({ disabled: true, value: null })

Reference Links:

Asynchronous Generators

For all the asynchronous challenges that we face in our code, would be solved by either Async-Await or Promises. Here comes another powerful alternative module which we call them as Generators!!!

There is a mysterious secret behind these generators which I will reveal it in the final section of our blog.

Let’s define Generators in simple:

1. What are they?

They are generally function with a * notation

2. Why do we need them?

They are just like normal Javascript functions with the motive of pausing and resuming the required particular function executions, thereby achieving better execution control


   asyncGenerator(function* () {

     let promises=yield apiService.get("asyncDb/promises.json");


     let callbacks=yield apiService.get("asyncDb/callbacks.json");


     let asyncAwaits=yield apiService.get("asyncDb/asyncAwaits.json");



   function asyncGenerator(generator){

     let a=generator();

     function handle(yieldObject){



           return handle(




     return handle(;


Illustration Explanation:

Here asyncGenerator is the generator. The keyword “yield” will pause the execution inside the function. Calling next() method each time will invoke the yield expressions separately one by one.

And most importantly the yield expression will return an object containing the keys value and done. The object is like,


value: {Promises…..} (the yielded return value will be here) 

done: false (states whether the generator execution have reached the end or not)


The above code looks almost the same as that of Async/await implementation. But what makes the difference is most important thing. Async/await returns a Promise, whereas Generators returns an object {value: X, done: Boolean}. Meanwhile yield returns a stream of values from the generators.

The error handling parts are very easier in generators when they are used along with RXJS filtering operators. Instead of using next() we could also use throw(error). Even we could force the generator to stop by using return() in place of next() methods.

When you are tired of using the next() method again and again, we could simplify it by using the setImmediate () method. This will make all the promises unwrap one by one and wait for them to resolve before calling the next iteration.


“setImmediate(() => next())”

The mysterious secret will be revealed now. Do we really need to learn generators and use them in handy?

The answer is NOOOO!


Because we have a more power tool “Async/await” which holds best due to its powerful features. Async/await is built using generators. Without these generators, Async/await will not work at all. But that doesn’t mean we do need to use and learn generators in our code. Generators are more complex. Let the framework and library developers use these generators to create more powerful modules like Async/await. The side benefit from the generator what we could say is “Easier Testing”. The famous bundler ”Brunch”, the interpreter “Co” and “Redux-Saga” make use of these generators specifically.


Reference Links:


Lint Driven Development

It is no wonder that “Lint Driven Development – LDD” is one of the most essential development approach that every developer should follow up! It is an integral part of every developer’s toolbox! If you could agree my statement, then you’re already on the track of super cool development. If not, then I can get you a step further towards that through this blog.

What is linting?

You write code. Probably a lot of code. And you make mistakes. Probably a lot of mistakes. Sometimes your mistake is a real bug that can be fixed. Sometimes it’s just an unclear coding style which may seem trivial at first but they become patently important as the codebase grows and as more people stick their hands in it. You can’t always focus on fixing this inevitable mistakes that you do! Isn’t it? Because, there is probably no practical way to make it impossible to write sloppy and unclear code, but it is fascinating to consider how tooling has evolved to make it harder. One fine tooling is “Linters” which understands you and your code.

Linter is part of the style guide. It’s a small piece of software that automatically checks if your code has any stylistic or potential errors and meets the predefined code convention rules. You don’t have to manually go through the code base to check style and any errors. Linting helps us in two ways. First, it looks for code that will potentially break. Second, it provides a style guide for the development team to follow.

Why Linting is Important?

Some great movies involves compelling stories, and colorful screenplays that are easy to watch and understand. From that aspect, the job of a developer is similar to that of the movie director, since the code has to be easy to read and comprehensive. I know it’s pretty hard to focus on code quality when you’re under pressure to meet the next deadline, but if you’re thinking long term, you definitely need to write code that’s readable and maintainable.

In addition to its readability and maintainability there lies an important third reason which is lower technical debt which allows speeding up long term software development since it can be reused without involving any future developer’s time to work on fixing the old bugs and styling the code.

How Linters prevent our problems?

Linting tools throws warnings about certain types of code that can lead to common problems. Some are quite major. As a Javascript Engineer, I’ll list down some major problems in JS code and how linters could prevent those problems!

Problem #1
Most of us have got this one common question in our mind that our code works in development but why not in production? We all knew that most modern web stacks support minification, but neither the minifiers nor the browser tell us when are we missing semicolons. But a missing semicolon can break minified javascript and so it stops in production. So Linters notify you about the missing semicolons, braces, etc..

Problem #2:

Have you ever created a variable called “id” or “name” or “value”? Yeah, so has every other developer in history, and people who work on the same codebase as you is not an exception. And if someone forgets to declare all their variables with var, as they can overwrite each other unexpectedly. The scope of the variables is gone as well as your code.

You don’t always need to rely on your reviewers to find mistakes in your code and in some cases it takes too much of your reviewer’s time to find some sloppy mistakes or even they might miss it completely. Linting your JS can prevent potential XSS security holes, readability problems, and many more!

Linting Tools

Linters comes with a lot of tools that are capable of finding stylistic errors and sloppy mistakes in every technology that we use. Among many JS linters, ESLint seems to be the best available linter as it is completely plug-able, every single rule is a plugin and we can add more rules at run-time. It gives concise output, and also includes the rule name by default so it’s always easy to know which rules are causing the errors. We also have Linters for most languages like TS, CSS, HTML, Python, etc..

There are different means by which one can use linting tools to improve the code quality. To mention a few,

Linting manually, in the browser

Copy and Paste your code into JSHint or CSSLint or HTMLHint or any other static code analysis tool to check for some interesting lint errors. This might be the quickest way to get started with linting.

Linting from your code editor

Many code editors have support for configurable linting, such as VSCode. Here is the guide to configure Linters in VSCode. It has many extensions for all of the linters above. Grab one and have it check your code automatically which is really great since you’re already in your editor, where you can clean your code up simultaneously while you write it.

Linting from the command line

If you’re using a command line tool like Npm, you’re ahead of the curve. Just install a linter of your choice and follow some commands to get notified of your errors in code.

Linting as part of the build process

This is the best way to ensure that these types of problems never see the light of day. I recommend adding a flag to the ng serve and the ng build commands that automatically runs ng lint before each build and causes a build failure on any linter rule violation.

Even if you set up a linter, it might warn you against invalid code but it cannot stop you from pushing this code to the repo. This is where Git pre-commit hook comes into the picture. It’ll restrict the developer from committing the code if it doesn’t pass the rules available in .git/hooks. For information about Git Hooks, please visit here.

It is NoteWorthy!

I recommend turning off most of your linter’s settings when you start using it, so that you have a minimal set of errors to start with. Consider the ones it throws out, learn what they mean and then fix them. Later, re-enable another setting and repeat until you understand all the rules. I understand, it takes some time to understand everything and to get them fixed up. Let me copy out some words from Bruce Lee.

“I fear not the man who has practiced 10,000 kicks once,

         but I fear the man who has practiced one kick 10,000 times.”

– Bruce Lee

Software development is pretty much always slower than anyone wants it to be. It takes time. Sometimes you just have to be patient enough to turn out the code you need to write. No matter how long you’ve been in this field, you should keep practicing the craft of coding.


Linting is a vital part of our workflow, and will definitely help us improve our skills. If you were not using linting, I hope this blog convinced you a bit to configure lint to your code. I think Linting is one of the traits that makes a good developer! What do you think makes a great developer? Love to hear from you!

Rendering in Web Browser

The main purpose of the browser is to present the web resources by requesting it from the server and rendering it. In present days, apart from the development phase, web developers face challenges where their UX designs are not the same across the browsers.

Basically, the HTML specifications are designed by W3C(World Wide Web Consortium). But only a part of the rules is followed by the browsers and the other parts are their own extensions and developments. This is why we face cross-browser compatibility issues.

The similarities across all browsers are the address bar, reload URL, bookmarks, home page, etc,,.

High Level Structure of a Browser

  • User Interface:  The View we see it when we hit an URL/link
  • Browser Engine: An engine that invokes the browser and responsible for displaying content on the screen(between UI and Rendering Engine)
  • Rendering Engine
  • Networking: For network calls that happen in the web browsers
  • UI Backend
  • Javascript Engine: Parse Javascript code
  • Data Storage: Refers the Local storage, cookies, WebSQL, IndexedDB, etc..

The Rendering Engine and the Javascript Engine will vary based on the browsers. Due to this, we face compatibility issues. Few are here,


Let’s go more detail about Rendering Engine!

Rendering engine

Rendering Outline

First, HTML is parsed to DOM tree using HTML parser. In the meantime, the CSS is parsed to CSSOM tree using CSS parser. Combining both DOM and CSSOM, the ‘Render Tree’ is constructed.
Then goes the layout formation. In the layout process, every DOM element gets its coordinates.
Using the paint method, all coordinates get their position in the view/display

For a better experience, the rendering engine will try to display the contents on the screen as soon as possible. Many times we see the half view is loaded in the browser. This is because only a part of the HTML and CSS is parsed as rendering engine tried to give the view as quickly as possible and remaining are loaded later.


The Rendering engine reads the HTML document line by line. If it finds a script tag <script>, the parsing of the document halts until the script finished. Due to this, the loading of the document takes time. To avoid this, use async/defer in the script tag to process asynchronously which means a separate thread is called for script parsing.

Changing the style of the element that does not affect the respective element’s position, like changing the background color, the repaint will happen.

The Reflow will happen on changing the content that affects the element’s position or a situation where restructuring the DOM is necessary, like changing the text of an element, animations for the relative elements, resizing, scrolling, etc,.The cost of rendering is high when reflow happens frequently.

Better Optimization:

  • Use proper encoding document types and valid HTML, CSS elements.
  • Apply the rules in the correct cascade order
  • Apply animation only for the absolute/fixed positioned elements.
  • Work with ‘offline elements’.
  • Place the scripts end of the document or use async/defer in the scripts



Angular Lazy Loading

In this blog, we will be learning about lazy loading in angular. The main concept of lazy loading is that don’t load something which you don’t need. Lazy loading is a useful technique for reducing the size of the bundle when the app loads initially which improves the app loads time thus improving the user experience. It’s also easy to have features loaded only when the user navigates to their routes for the first time.

Main steps to set up lazy loading

  1. Create a feature module.
  2. Use loadChildren in the main routing module.
  3. Create a routing module for feature module.

Create a feature module

In order to use lazy loading, we need submodules in our applications often called a feature module. Assuming that you have an Angular CLI project, let’s create a feature module using the following command.

Create lazy loading module

Note: Don’t load the feature module in your main module.

Now let’s create two components inside the lazyLoading module using the following command.

Create lazy loading component

Use loadChildren in the main routing module

Now let’s load the feature module in our main routing module (app-routing.module.ts). We need to use loadChildren() method to lazy load the feature module.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]

export class AppRoutingModule { }


The loadChildren() method takes the path to the module, then # followed by the module’s class name.

Create a routing module for a feature module

Now let’s configure routes in the routing module for the components under the feature module.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { OneComponent } from './one/one.component';
import { TwoComponent } from './two/two.component';

const routes: Routes = [
{ path: '', component: OneComponent },
{ path: 'two', component: TwoComponent },

  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]

export class LazyLoadingRoutingModule { }


In the feature routing module include the routes with RouterModule’s forChild() method instead of the forRoot() method.

Lazy loading has been configured successfully now LazyLoadingModule will load only when the user navigates to “/lazyLoading”.

Preloading Strategy

When we run the application only the main modules are loaded all the other modules are lazy loaded. In this case, the lazily loaded modules load only when the user navigates to the feature module. Since the module is lazy loaded we have to wait for it to be loaded to overcome this we can use preload strategy.

To use preloading strategy we have to add preloadingStrategt in our app-routing.module.ts as shown below.

import { NgModule } from '@angular/core';
import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
const routes: Routes = [
 { path: '', redirectTo: 'home', pathMatch: 'full' },
  path: 'lazyLoading', 
  imports: [RouterModule.forRoot(routes, {
    preloadingStrategy: PreloadAllModules,
exports: [RouterModule]
export class AppRoutingModule { }

The two subclasses in preloadingStrategy are.

  • NoPreloading: Default strategy which provides no preloading.
  • PreloadAllModules: Preloads all the lazy loaded modules.

By using PreloadAllModules we can load the modules which are required on the initial load of an application. All the other lazy loaded modules are loaded asynchronously right after the initial load of the application is done.

Another strategy is to preload the modules which are required and some other module with a delay. The method to use this is to add the data object to the route config as shown below.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
    path: 'lazyLoading', 
    loadChildren: './lazy-loading/lazy-loading.module#LazyLoadingModule',
    data: { preload: true, delay: false },