Moving To Linux

Well, a year back I decided to sell my MacBook Air and build my own desktop. I hand picked all the hardware I needed but the thing I was confused about was which OS to use? I knew I’ll need dual boot with Windows + Linux. I never really like using Windows as my day to day OS of choice (someday will write down why!!). I installed it because sometimes I have to use Word Processor or MS Excel.

The question was which Linux distribution to use. I was just diving into the world of Linux and had no real experience. I tried YouTube for reviews but I figured out the good advisors were avid users/developers on the Linux platform and they had their reasons to like/dislike certain distros (if you’re using Linux, have to call them distros not distributions :P), on the other hand I was just an application developer who wanted to stop using MacBook. I easily get bored with things and this article is about my journey with Linux distros I ended up using. (Manjaro, Ubuntu, KDE Neon & Pop OS).

Some of the famous Linux distros

Manjaro

Why Manjaro?
  1. It is a rolling distro with all the good things or arch linux and very user friendly
  2. KDE Desktop

Few people complained that community support is not great for newbies but I never faced any such problems for any questions I put out there in the forums. I receive prompt and detailed help from community users for every query I posted.

Why did I stop using it?
  1. It is a rolling distro, compared to any other distro you’ll receive the bleeding edge stuff here and the people behind manjaro make sure that only stable things gets to you but still for my setup I faced couple of issues
  2. My Wi-Fi would stop connecting If I boot to windows and come back to manjaro by restarting instead of shutting down the machine and then start again to boot to manjaro.
  3. Once while updating the package manager froze and crashed. I started and figured out, it crashed while updating the kernel and now it doesn’t know which one to use while booting up. I am sure any experienced linux user would have fixed it but I failed to understand the process. My learnings were to create timeshift backups and have a bootable disk for the linux distro ready to boot using live mode and fix the issues.
  4. Some people find the packages on Ubuntu to be very old and they are in the favour or frequently updating rolling distros.

Well I made a mess out of it and had to wipe my hdd so thought of falling back to very famous distro ‘Ubuntu’.

Ubuntu

Very famous distro among the people just diving into the world. Built on the stable base of Debian and has LTS versions. Linux users have the love hate relationship with it.

Reasons?
  1. Ubuntu uses GNOME as their desktop environment but in between the decided to build their own desktop. Some people disliked it (It is important to know that while using linux, one can choose their desktop environments based on the factors of look & feel, configurability and simplicity. Famous choices are GNOME, KDE, Cinnamon, Budgie etc).
  2. A central proprietary repertoires for installing software like SnapCraft. Some users hated it while others welcomed it with open arms as they see snap as the future of software distribution. One source of truth over PPA and for having updated software from official providers.
  3. In between they partnered with a know corporation for collecting some users data which they later on removed but it caused a trust issue among users.
Why Ubuntu?
  1. After Manjaro, I thought let me start with something basic, a stable OS and I chose ubuntu.
Why did I stop using it?
  1. I did not like the desktop environment. Personally I felt GNOME was not good (May be I was more in favour of KDE and hooked to it).
  2. I installed KDE on ubuntu and after a month KDE released 5.20 version. With great excitement I went to my PC to update my KDE and I realized, as a user I would just get the updates for bug fixes to version 5.18 and not the upgrade to version 5.20 (Same applies to Kubuntu)
  3. Also made a mistake of using tasksel to install KDE (kubuntu desktop). It should not be used I feel. Uninstalling any component via tasksel deletes the packages associated with OS and ends up causing trouble while booting for users. Use this as a guide if you want to install KDE.
  4. If you are not sure ever that what packages to uninstall, go to /var/log/apt/history.log and search for the package you installed. You will find all the supported packages installed with it. Copy and uninstall them.
  5. I wanted to move on to latest KDE and I came across this good distro called KDE Neon which is technically not a distro. It is packaged by the team at KDE using ubuntu LTS as base along with KDE desktop and this my friends, it receives all the KDE desktop updates. You can even go an extra mile and install a dev version which receives all the updates under test.

KDE Neon

There comes KDE Neon. When I installed I thought I will end using this distro for a long time but it didn’t even last for a week. I encountered many issues.

  1. Why pkcon? If the base is ubuntu, using apt should be good enough?
  2. It doesn’t have great support for GPU drivers. I downloaded amd-gpu drivers from AMD website targetting to Ubuntu think KDE Neon is nothing but Ubuntu. It didn’t work. I opened the install script where I could see they check which os it is first. The script expect it to be either Ubuntu, Kubuntu or Lubuntu. I added one more param for Neon and script worked but failed again as it found so many other packages which are part of Ubuntu, they are missing from KDE Neon.
  3. Driver manager. Another way to find the drivers was the driver manager. I installed it but it was always crashing. Never it opened successfully showing list of devices.
  4. Sound output selection. It was able to remember across restarts which device for sound output I have selected. Sometime it would even fail to detect all the sound output devices attached.
  5. As it was struggling with drivers, it never use the refresh rate of 144 Hz on my machine. I disliked it. I wanted my investment on monitor to be used properly.

Pop! OS

Enters Pop! OS by System 76. While watching videos on YouTube I came across this OS. System 76 provides hardware as well if you are interested. I tried to learn more about it and fell in love with it.

What did I like?

  1. Based on Ubuntu and no package manager enforced. I used apt and installed snap for official packages. It also has Pop shop for packages inspired by the store of Elementary OS (uses flatpak to install software or you can choose the option of installing package using .deb file)
  2. It is made specially with programmers in mind with ease of setting up the development environment
  3. Out of the box support gaming and graphics drivers. Thanks to Pop! OS, steam & valve. Google more about it, gaming on linux is a thing to watch for. No longer Windows is mandatory. Even some games are better on linux compared to windows. More and more titles are coming for native linxu gaming. I would recommend to read more about Steam, valve, linux, lutris.
  4. A special Pop! OS build with Nvidia drivers there. (I use AMD gpu)
  5. A thing I forgot to mention Manjaro (Manjaro, Arch, Ubuntu, Fedor etc) also has steam.

Few things I still didn’t like but I can live with

  1. Desktop is back to GNOME but I am fine with it. In fact I am happy with workspace switching options and Pop! OS boasts the best tile window arrangement across various desktop environment.
  2. Font management. I love my fonts Dank Mono. I installed them but I cannot set them as fonts for my terminal. Not sure what it doesn’t like about it. Will figure it out later. (If you are using VSCode, use these fonts with Night Owl theme, enable font ligatures. Write a piece of code and take a moment to admire how beautiful that piece of code looks. You’ll agree with me if you have an OCD with fonts like I do. Another option for you to play with is using Nerd Fonts. Happy hacking.)
  3. You may find it too plane.
  4. If you don’t like ubuntu, may be it is not for you.

Well, that is all from my side. I will keep updating and posting about my learnings. I would love to know about your favourite distros, IDEs, fonts. Let me know your thoughts about them in the comments. Cheers!!!

for loop & JavaScript

Looping is the most familiar concept in the arena of programming. One of the most basic and most used programming syntax. Throughout this article we will see the different way to loop through array and objects in JavaScript. Computer science is the science of trade-offs and that will our focus while going through various possibilities.


Simple for loop

This is the most familiar way of using for loop for iterating over structures like array where an individual element can be accessed using index based mechanism.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
view raw loop.js hosted with ❤ by GitHub

It is familiar method but the short-coming here is there are too many moving parts. As a programmer in the approach above, we control an index variable represented by i, it’s initial value, boundary condition and finally incremental value of index variable with each iteration.


forEach

This approach is becoming more and more popular with ES6 and onward. It leans towards the functional way of programming. Compared to the for loop we discussed in the section above, it presents very simple & readable programming construct. We focus on the functional programming principle of ‘what to do’ rather than ‘how to do’ stuff with code.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
fruits.forEach(fruit => console.log(fruit));
view raw loop-foreach.js hosted with ❤ by GitHub

Earlier we discussed that we will pick which solution to use within our application based on the trade-offs we have to make upon choosing the solution. If we discuss about choice between for and forEach, one should use forEach as it makes code very simple to understand, it comes with less overhead. But, if you want to skip a step while iterating by using keyword continue or stop the iteration in the midway with the help of keyword break, it is not compatible with forEach loop. Upon using keyword break or continue it will show a syntax error. So one needs to skip a few iteration or break an on-going iteration, for is the right choice.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
fruits.forEach(fruit => {
if(fruit === 'kiwi') {
// A syntax error will be thrown for putting a break statement
// Uncaught Syntax Error: Illegal break statement
break;
}
console.log(fruit)
});
for (let i = 0; i < fruits.length; i++) {
if(fruits[i] === 'kiwi') continue;
console.log(fruits[i]);
}
// output
// apple
// orange
// grapes
// pineapple

for in

Till now, we just focused on array data structure for iteration. With for in we will see that it is designed to iterate over another most used data structure object. An interesting thing to know that in JavaScript, typeof array and any object is object. That means, array is a special case of object. Also, a value of a particular attribute in object can be accessed using index like structure. var obj = { message: 'Hello World!'} can be accessed either using obj.message or obj['message'] where attribute name is passed as string.

Now let’s see how for in helps to iterate over the object. Interesting thing to note is, when we iterate, we receive attribute names but not the attribute value.

const person = {
firstName: 'Virat',
lastName: 'Kohli',
email: 'vk@rcb.in',
profession: 'Cricketer',
team: 'India/RCB'
}
for(attr in person) {
console.log(`Attribute: ${attr} Value: ${person[attr]}`);
}
// Output
// Attribute: firstName Value: Virat
// Attribute: lastName Value: Kohli
// Attribute: email Value: vk@rcb.in
// Attribute: profession Value: Cricketer
// Attribute: team Value: India/RCB
view raw loop-for-in.js hosted with ❤ by GitHub

What happens when we use for in with an array instead of objects? Well, in that case it provides with number keys (array indices) instead of values on the those indices. Shall we use this with array? Well, using for in with array can be a bad idea sometimes. Let’s look at the example below:

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
fruits.code = 'is crazy';
for(e in fruits) {
console.log(e);
}
//Output
// 0
// 1
// 2
// 3
// 4
// code
view raw for-in-array.js hosted with ❤ by GitHub

for of

Another construct iterate over an array is for of. Let’s first how it works.

const fruits = ['apple', 'orange', 'kiwi', 'grapes', 'pineapple'];
for(fruit of fruits) {
console.log(fruit);
}
// Output
// apple
// orange
// kiwi
// grapes
// pineapple
view raw loop-for-of.js hosted with ❤ by GitHub

This approach sits somewhere between standard for and forEach approach. We are not using any extra variable to access any members of data-structure neither data-structure is instructing us on how to iterate on itself. So how it differs? Let’s look at a sample array like const fruits = ['apple', , 'orange', 'kiwi', 'grapes', 'pineapple']; Did you notice the second element on array. It is just blank. Now how forEach and for of will behave in this scenario? Let’s have a look at it.

const fruits = ['apple', , 'orange', 'kiwi', 'grapes', 'pineapple'];
for (fruit of fruits) {
console.log(fruit);
}
// Output
// apple
// undefine
// orange
// kiwi
// grapes
// pineapple
fruits.forEach(f => console.log(f));
// Output
// apple
// orange
// kiwi
// grapes
// pineapple

It is evident from the output that forEach ignore the blank element within the array while for of construct considered the blank element and logged as undefined to the console. So as a programmer we will have to make this choice, are we expect any blank element for the source where we receive the data? If yes, what shall we do with them.


I hope this article helped you understand various way to iterate over object and array data-structure in JavaScript and what trade-offs you make as a programmer when you choose one over another. Let me know your thoughts in comments.

React Unit-testing – Finding DOM Elements

Writing unit-tests for your React components are important, but it also important that tests are robust. Brittle tests are not maintainable & cause frustration to developers.

This post addresses once such scenario that can cause brittle unit-tests, which is finding the nodes or DOM elements. Let’s work on making them robust.

DOM elements are identified using selectors such as id or CSS class-names. If the CSS class-names are generated dynamically then using them is out of the question. How using them as your identifier makes your test brittle? Well, if your code is refactored which changes the id of your DOM element or CSS class-name is changed, in such scenario, despite your component having the same functionality, the unit-test(s) will fail. E.g. We were using a <button> element to create a button & id was btnCreate but later on we decided to refactor it & use <a> anchor tag & we refactored id to anchorCreate or lnkCreate.

To make your unit-tests immune to such changes, we use an identifier that is consistent through out the life-cycle of an application. For achieving the robustness we can use data-test attributes for the nodes or DOM Elements we want to identify within the test. An extra attribute we will added to the nodes or DOM Elements we want to find or raise assertions with help of unit testing framework & test utilities in the context & this selector will remain unchanged even if the underlying DOM element is changed which was used to represent the data received or will not be affected by code refactoring (unless the whole element is removed in which case test should fail).

How do we achieve this? Source code is available under a GitHub repository to download here. Let’s discuss about it.

To protect the unit-tests from the changes of id or CSS class-name we will introduce a data-test-id attribute to the components or elements we need to find via unit tests. Refer to the Workout.js component in the code example:

import React from "react";
function Workout({ name, target, group }) {
return (
<div data-test-id="workout-container">
<h4 data-test-id="workout-name">Name: {name}</h4>
<h6 data-test-id="workout-target">Target: {target}</h6>
<h6 data-test-id="workout-group">Group: {group}</h6>
</div>
);
}
export default Workout;
view raw Workout.js hosted with ❤ by GitHub
Workout.js

I’ve added the data-test-id attribute to 4 elements we want to identify for Workout.js component via unit-test. We want to make sure when details about a workout are provided, the container is rendered along with name, target & group. For the example application, we’re using Jest & Enzyme to write this unit test. When the test starts, we setup the component using shallow method of enzyme to render the component. Enzyme returns a ShalloWrapper for the component & within this wrapper we will search & identify the components/elements we’re looking for.

A small utility method is written to search for nodes with data-test-id in shallow rendered component so we don’t duplicate logic across out tests. It is available under test/utils/testUtils.js

/**
* Returns node(s) for the given string attribute value of `data-test-id`
* @function findByTestAttribute
*
* @name
* @param {ShallowWrapper} wrapper – ShallowMounted Enzyme wrapper
* @param {string} attributeValue – value of data-test-id attribute as string
* for searching the nodes
* @returns {ShallowWrapper}
*/
export function findByTestAttribute(wrapper, attributeValue) {
if (!wrapper) {
return null;
}
return wrapper.find(`[data-test-id="${attributeValue}"]`);
}
view raw testUtils.js hosted with ❤ by GitHub
testUtils.js

Now we will write the unit-test using Jest & Enzyme along with the help of above utility method. This is test is now immune from changes of id or CSS class-names. Even if you change the underlying element representing the data the tests run without error. For example to represent the text about workout name one decides to use <span> instead of <h6> the data-test-id can remain same as it represents workout name thus producing robust test. We will look at the unit-test now:

import { shallow } from "enzyme";
import React from "react";
import { findByTestAttribute } from "../test/utils/testUtils";
import workouts from "./data/worksouts.json";
import Workout from "./Workout";
function setup() {
return shallow(<Workout {workouts[0]} />);
}
describe("Workout renders", () => {
test("without error", () => {
const wrapper = setup();
const container = findByTestAttribute(wrapper, "workout-container");
expect(container.exists()).toBe(true);
expect(container.length).toBe(1);
});
test("workout name, target and group", () => {
const wrapper = setup();
const workoutName = findByTestAttribute(wrapper, "workout-name");
expect(workoutName.exists()).toBe(true);
expect(workoutName.text()).toContain("Bench Press");
const workoutTarget = findByTestAttribute(wrapper, "workout-target");
expect(workoutTarget.exists()).toBe(true);
expect(workoutTarget.text()).toContain("Chest");
const workoutGroup = findByTestAttribute(wrapper, "workout-group");
expect(workoutGroup.exists()).toBe(true);
expect(workoutGroup.text()).toContain("Upper Body");
});
});
view raw Workout.test.js hosted with ❤ by GitHub
Workout.test.js

It is clear from the test & code above is that we are adding an extra attribute to the code & this attributes are now part of the code we release to production & any data that is not related to application business logic should be avoided & keep things de-cluttered.

There are two ways to achieve this.

Using a Babel Plug-in:

Eject the react app using npm eject or yarn eject (only if application is created using create-react-app) & use a babel plugin called babel-plugin-jsx-remove-data-test-id. If you’ve created app manually then you can use above mentioned plug-in directly. What this plugin does is, it removes data-test-id attribute from the production build.

README.md is very self-explantory for this plug-in. Also if you name your attribute something different e.g. data-testid or data-test-attr you can let the plug-in know your custom attribute name to be removed from production build.

plugins: [
[ "babel-plugin-jsx-remove-data-test-id",
{ attributes: [
"data-test-id", "selenium-id", "another-attr-to-be-stripped"
]
}
]
];
view raw bableConfig hosted with ❤ by GitHub
babel config to be updated

Without Ejecting from CRA & Adding Babel Plug-in

Well, in this case we will construct a method that will add data-test-id attribute to a component only if the NODE_ENV is set to development.

/**
* Returns and object with `data-test-id` as key and attributeValue as
* associated value to the key
* @function
* @name getDataTestAttribute
*
* @param {string} attributeValue
* @returns {object}
*/
export function getDataTestAttribute(attributeValue) {
return process.env.NODE_ENV !== "production"
? {
"data-test-id": attributeValue,
}
: {};
}
attributeHelper.js

Now we will use the method above to add data-test-id attribute to component/element when the NODE_ENV is development. Look at the updated code of Workout.jsx here. It won’t have data-test-id for the production build.

import React from "react";
import { getDataTestAttribute } from "./helpers/attributeHelper";
function Workout({ name, target, group }) {
return (
<div {getDataTestAttribute("workout-container")}>
<h4 data-test-id="workout-name">Name: {name}</h4>
<h6 data-test-id="workout-target">Target: {target}</h6>
<h6 data-test-id="workout-group">Group: {group}</h6>
</div>
);
}
Workout.js updated with attributeHelper

This strategy can be used with your selenium UI test(s) as well by adding selenium-id to the elements you want to identify & build robust tests. No matter how big or small is your application, this strategy can be used to write unit-test(s) or UI test(s).

Vim for JavaScript Developers

Are you a JavaScript developer who loves command line interface and loves to remember commands? Are you a developer who wants to keep writing code without leaving keyboard at all? Well then vim is for you my friend.

This article assumes you are little familiar with Vim editor, how to open a file and navigate within it. If you are not, not to worry. Here is vim cheat sheet for commands which I used in my initial days of learning vim. While it is impossible to just remember these commands, my approach was I started using vim, and kept this cheat sheet printed on my desk. I referred the commands until they came to me naturally.

Vim is a very versatile IDE for developers and it’s plug-in based Eco-system allows developers/communities to build and contribute various plug-ins and with the power of these plug-ins it can be used as development tool for multiple technologies and programming languages. This article specifically focuses on Vim for JavaScript development. I will be sharing the list of plug-ins I am using and the vim configs I have created for my vim environment.

I am using GUI based vim for better experience and using tab based UI. The GUI based vim options are gVim, Neovim or MacVim (OSX users). You can install them by downloading binaries, or using your favorite package manager or by downloading the source code and compiling it locally on your machine. I am Linux user and I have use pacman package manger to install Neovim.

List of Plug-ins Used

To install vim plug-ins, the first thing you need is a plug-in manager. There are many options like vim-plug, vundle, pathogen etc. My choice of plug-in manager is vim-plug. The documentation on the README.md is self explanatory and it is very easy to setup. Once this setup is done, we can go ahead, install all the plug-ins we want and enhance the capabilities of this simple yet powerful IDE.

  • vim-polyglot

    Initially I thought to install vim-jsx for JavaScript and JSX support but then I came across this plug-in. It provided the language support for multiple Programming languages. Once installed, it starts working out of the box.

  • fzf

    FZF aka Fuzzy File Finder. In an IDE when you open a project, it is very import for one to open file quickly. FZF is command line query tool which is integrated to Vim via plugin. It is lighting fast for searching a file within vim. With vim it needs bit of a tweak to search more efficiently, like ignoring node_modules folder for JavaScript projects. I am learning it myself and should update those tweaks once fine-tuned.

  • lightline

    lightline is a configurable statuline or tabline for vim editor. By default it shows the mode of vim, file encoding, file ending style, cursor position etc. You can configure it show extra information or custom messages helpful to you.

  • vim-prettier

    It is prettier plug-in for vim. It has pre-configured options for vim. You can reconfigure them to apply on your JavaScript files. You can also configure it to honor the prettier settings provided by your .prettierrc.json or yaml file.

  • ale

    ALE aka Asynchronous Lint Engine. We know linting is very import for JavaScript based projects. ALE helps use to choose the linters we want to apply for the project. For my JavaScript & React based projects, my choice of linters are ESLint & Prettier. If you are adding TypeScript, the choice of linters may very.

  • coc

    As a developer we need support for intellisens, to see the functions or APIs being exposed by libraries, what are the params expected for the function being called. Well coc brings the auto complete feature to your vim. All you need to do is install coc with the help if vim plug. Once installed it provides you with set of commands. Using :CocInstall to install extension specific to language for which you need auto-complete support. e.g. JavaScript auto-complete feature is supported by coc-tsserver. The list of extensions are available here.

  • oceanic-next

    I love using dark mode for IDEs and oceanic-next is the perfect dark theme for Vim editor. If you are a fan of now so dark theme or fan of a light theme solarized is another good option as it has both dark and light mode. Practically there are many themes out there and you can install the one you like.

  • vim-jsdoc

    Recently, I have started adding project JS-Doc style documentation/comments to my JavaScript projects. It really helps me to understand the code I am writing or the API and libraries I am using. Until I came across this plug-in it was a little bit tedious task to add these comments. vim-jsdoc is an interactive way to add JS-Doc style comments to your JavaScript code and you can also configure it to adapt it to your style of coding or project standards.Refer to the README.md to explore these options.

  • nerdtree

    It is a full-fledged project explorer built for vim. You can search for files using FZF or ctrl-p when you know what to search, but project explorer is really useful to go through project structure, explore and understand it. It allows you to navigation, explore, bookmark, creating, modifying, rename, deleting files etc. I really love the simplicity of the plug-in.

  • vim-devicons

    Well, with nerdtree you have a project explorer, now lets have devicons which associates icons with file or foldertype based on your project. There is a bit of extra stuff required for this to work flawlessly. 1st you have to set the encoding to UTF-8 and 2nd you have to install and use NERDFonts for your editor. They are the patched fonts and I am sure you will find your pick in the list. You can supply your own patched fonts as well. To intall NERDFonts you can either clone the repo, or install them using package mangers.

  • vim-mulitple-cursors

    This plugin bring the multiline select feature of Sublime to vim. It is a simple yet powerful feature for refactoring your code quickly.

  • ctrlp

    If you are using VSCode, Sublime or Atom as your current IDE, then ctrl-p has been your favorite shortcut to open known files. Just pressctrl-p start typing. Well, this plug-in bring the same functionality to vim. It is a fuzzy file finder which searches for files, MRUs (recently used files), allows you to open multiple files or event create files for directories.

Now we have all these plug-ins and information. But where do we put it? Well vim a config driven editor and by default the config is stored in vimrc file. Where is this file located, what is the name of file for MacVim vs Neovim vs gVim? Well, it is very easy to figure it out. All you need to do is type a command within your vim editor and it will list all the vim config files and plug-ins it will load at the start. That command is scriptnames. Type this command and press enter, the list will be presented to you.

For my Linux machine and Neovim, that file was sysinit.vim located under /etc/xdg/nvim/sysinit.vim while for my work laptop which is a Windows machine, it was ~/AppData/Local/nvim/_vimrc.

  • For my Linux machine, I did not want to put all my config under one vimrc file and specially not under file which is under /etc hierarchy. So I created a _vimrc file and sourced it to sysinit.vim.
  • All my plugins I have installed with the help of vim-plug are mentioned in _plugrc file and then sourced to my _vimrc
  • All the plugin are stored in ~/.vim/plugged folder, you can choose your own path and you have to let vim-plug know when you initialize plug-in within _plugrc
  • All the configs are available on my GitHub repostory for vim-configs.

If you like this article, and if it helps you to learn and configure Vim, do like, and give a star to my GitHub repository. I will keep updating these repository and article as and when I tweak my settings, add new features. Feel free to post your comments or if your identify a better plug-is/configs. Happy to give you mentions.

Atom for React & JavaScript Developers – 2020

I recently started using Atom as my IDE for React & JavaScript development. (I am here to write my experience with Atom. I love using different editors as and when I feel like I need change.)

My experience with Atom is good. I love it’s base theme Atom Dark (UI Theme) and One Dark (Syntax Theme). It took time to figure out the packages I needed to have the best React/JavaScript development experience.

Installation is pretty easy, I am sure there are plenty of options like downloading the binary or install it using your favorite package manager. I installed on my Manjaro Linux using pacman package manager.

Packages Configured

I installed following packages to support React & JavaScript development. In case there were duplicate packages or unofficial packages, I went through the reviews on packages and installed them. I all the items in list have link to actual packages for the reference. I have just added short description stating the primary feature package is providing.

  • atom-ide-ui (Supports language services, if you have installed linter package, it will tell you to disable it as this package takes care of it)
  • atom-path-intellisense (Path intellisense, when you write your import statements to get items from installed node modules or import functions/components created by yourself)
  • atom-ternjs (JavaScript code intelligence for Atom)
  • autocomplete-html-entities (Autocomplete for HTML, more exhaustive compared to installed by default)
  • docblockr (I love adding JsDoc comments to my code, this helps me to generated comments faster when I type /** and press enter. Supports multiple languages)
  • file-icons (Icons theme for Atom)
  • ide-json (Json support for IDE)
  • ide-typescript (types & TypeScript support in Atom)
  • import-cost-atom (when you import a plugin, how much size it contributes to your build. Helps to reduce build size.)
  • minimap (In your editor, on the right side shows entire file as minimap. Helps to navigate faster to during search & replace or refactoring.)
  • pigments (shows colors in css files when you type hex color code or RGB color code.)
  • prettier-atom (I use prettier to format my code, this is the office plugin)
  • react (Complete JSX & React support.)

Feel free to post comments if you want to suggest any better plug-ins or alternatives. I will keep adding or modifying packages and experience with Atom.

Equality Gotchas – JavaScript

Type coercion is one of the very interesting concept to understand in JavaScript. To delve deep into the understanding of this concept let us first evaluate few conditional statements into the console of google chrome (or you can use node or any suitable method to evaluation these conditions. You will have to modify your code slightly based on the method you choose to evaluate the code from snippet if not using chrome console).

false == 0 //true
false === 0 //false
false == '' //true
false === '' //false

Well, we can clearly see though we are comparing the the same operands, if we change our logical equality operator from == to === the result varies.

Important concept here to understand is when we use == operator to compare two operands and they are not of same type, the type coercion comes into the picture as one of the operands is type-casted to  the similar type of another operand and then comparison is done. E.g. false == 0, in this statement numeric value 0 is falsy value which is type-casted to Boolean equivalent and then compared and this the reason the end result is true.

When we use === operator for comparison, no type casting takes place for any of the operands involved in comparison. They are compared as it is. This means, if we compare false === 0, in this case a boolean value false is checked for equality against numeric value value zero. In that case the conditional statement false === 0 return false as an end result.

Similar is the case with != and !==, e.g.

false != 0 //false (here type coercion takes place)
false !== 0 //true (here boolean value false is evaluated against Numeric value zero)
type coercion while using != vs !==

In short, we can say that == (or !=) is abstract equality while === (or !==) is value equality (strict comparison). In abstract equality an implicit conversion of operands takes place while in value equality no such implicit conversion of value is being carried out. Strict comparison is always an correct way to carry out comparison operation except for Numbers due to floating point precision. If you are interested in digging more, especially trying different combinations of type and == (or !=) and result of such statements, I would recommend you all to go through this page over MDN.

.

JavaScript – Data Types

Well, we all know that JavaScript is a functional language (which is an entirely a different discussion about being functional language) has some data types, namely:

Let’s talk about each of this data type in detail:

Number:

JavaScript has no integers, numbers are represented by data type Number. They are 64-bit floating point numbers. Well it is a strange name for floating point numbers and they are represented by standard IEEE-754 which are similar to double data type.

Now as we know that they are floating point numbers we have to be bit careful about arithmetic operations over the operands of this type, especially if we are performing calculations representing money. The reason is, floating point operations always return approximations, not exact values. For example:

function multiplyTest() {
var x = 0.1 * 0.2;
console.log(x);
}
multiplyTest();
//which might return an approximate answer like 0.020000000000000004
//this is a bad idea if we are dealing with $ or INR values
view raw multiplyTest.js hosted with ❤ by GitHub
Multiplying number in JavaScript

Now, we will see how to deal with this situation. Solution here is very simple. We know that when we are dealing with money, we deal with numbers like 34.56$ or 8.99$ or 100.35 INR. These are the numbers with precision up to 2 digits after floating point. So scale them up by multiplying with 100. Perform arithmetic operations and then again scale them back by diving with 100. Let’s apply this solution to function above and see what it returns:

function multiplyTest() {
var x = ((0.1 * 100) * (0.2 * 100)) / 10000;
console.log(x);
//We are dividing here with 10000 because we multiplye 2 different numbers with 100
//here console log statement will return exact answer 0.02
}
multiplyTest();
Solution

Another important value to keep in mind is NaN while dealing with arithmetic operations. It is an output of any erroneous arithmetic calculation. If any arithmetic function is given NaN as an input, it is sure that end result will be NaN too.

There are few strange things about NaN. NaN is not equal to NaN. NaN is not greater than or less than NaN. NaN is not a numerical value but if we check type of NaN in JavaScript using typeof, the type returned is a Number. (Strange!!!!)

//You can directly type this in chrome console for instant output
NaN == NaN // false
NaN >= NaN // false
NaN <= NaN // false
typeof(NaN) // number (though it say, it is `not a number`)
view raw js-nan.js hosted with ❤ by GitHub
NaN behavior in JavaScript

It provides a function (or we can say constructor), Number(value) which helps converting a string into a Number. It works same a + prefix operator (we will see in the program).

function sum() {
var a = new Number('3');
//Converts String value '3' to numeric value 3
var b = +'4';
//Converts String value '4' to numeric value 4
var c = a + b;
//If there is any issue in conversion it must return NaN as output
console.log(c);
// Output is numeric value 7
}
sum();
view raw sum.js hosted with ❤ by GitHub
Type coercion with Number and + operator

The final thing we will discuss about Number is a function called parseInt (strange again, now it says int). Well, this function helps parsing a string into Number. It takes two arguments: parseInt(String to parse, raddix)

function parseIntTest() {
var a = parseInt("5");
console.log(`a: ${a}`)
//variable a will have numeric value 5
// this is a bug in some of the older browsers where
// parseInt with '08' will return 0
// if you are supporting older browsers, make sure you
// mention second argument, the base for number system as 10
var b = parseInt("08");
console.log(`b: ${b}`)
//variable b will have numeric value 0
var c = parseInt("08", 10);
console.log(`c: ${c}`)
//variable c will have numeric value 8
}
parseIntTest();
view raw parse-int.js hosted with ❤ by GitHub
parseInt(any, radix)

parseInt will  stop parsing the input String when it will encounter the first no-numeric character. It is also important to pass the radix argument which we can see in the program above. It the input String is ’08’ in that case we can see the output is numeric value 7 because parseInt thinks (in the absence of radix argument) that input String is an octal number input. In the third statement when we have passed raddix argument we can see that now the output is 8. The radix argument is nothing but the base into which we want to convert the String.

It is important to know as a developer that the default value of radix is not 10. It always depends on the first input. parstInt converts first arguments to string. If it can be parse the output will be an Integer other wise it will return NaN.

String

String are nothing but sequence of 16-bit characters. One important thing to keep in mind is, in JavaScript String UCS-2 encoding not UTF-16. The major difference between UCS-2 and UTF-16 is, in UCS-2 there is no support for surrogate pairs (For detailed explanation of surrogate pairs check this out. For String variables in JavaScript, similar strings are equal. == returns true for similar strings. Also we can represent String literals  using either ” or “”. Both are same.

string.length in JavaScript returns the count of number of 16-bit characters in a string. Function String(value) helps to convert numeric value into String.

  1. Input string begins with 0x or 0x, the radix value will be assumed as 16
  2. Input string begins with 0, the radix value assumed is 8 or 10. Which will be used? It depends how browser has implement ECMA5 standards. How to cope with it? Always be specific and provide radix value.
  3. For any other input string, radix assumed is 10.

Boolean

There are two Boolean values, true and false. Function Boolean(value) takes value as an input and based on the value being truthy or falsy, it returns true or false. This urges us to delve in another concept which is: ‘What is truthy or falsy value?

Well, in JavaScript falsy values are:

  • false
  • NaN
  • null
  • undefined
  • ” or “” (empty String)
  • 0 (numeric value zero

Rest all values are truthy value. Even “0” (zero in quotes) or “false” are turthy values as all the non-empty String are truthy.

//if you try following line of code in chrome console
var a = new Boolean(undefined);
console.log(a);
//false
a = new Boolean(null);
console.log(a);
//false;
a = new Boolean(0);
console.log(a);
//false
a = new Boolean('0');
console.log(a);
//false
a = new Boolean(false);
console.log(a);
//false;
a = new Boolean('false');
console.log(a);
//true
a = new Boolean(NaN);
console.log(a);
//false
view raw js-boolean.js hosted with ❤ by GitHub
Boolean in JavaScript

null

In JavaScript null is not a value but absence of value. Yet it is import to note that typeof null is object. That’s the way it has been implemented from the beginning and now it cannot be changed without breaking applications written in the past. JavaScript engine, whenever not sure, assigns undefined while null is assigned by the programmers.

undefined

Well, it  is a special value (I wish a less confusing name would have been choosen) assigned to any variable when when left uninitialized. It means a variable defined but not assigned any value will have value undefined in it. undefined == undefined returns true and type of undefined returns undefined when typeof function is used. undefined is also a value returned when we try to extract a member from an object when it doesn’t have a member present.

var emp = {
name: 'John Snow',
email: 'john.snow@abc.com'
}
console.log(emp.name);
//John Snow
console.log(emp.address);
// undefined (here we are trying to extract a member which object doesn't have)
var test;
console.log(test);
//undefined (a variable defined but not initialized)
view raw js-undefined.js hosted with ❤ by GitHub
undefine in JavaScript

Rest everything in Java is an Object. But that will be an entirely a different discussion. We will take it separately in a different article.