The Bad and The Worse – JavaScript Scoping Issues

Hope you all gone through how amazing JavaScript worker is. Today, we learn something core to JavaScript. Every language has its bad sides or “How not to use/write code” like that. Lately, I wrote JavaScript more than 3 years now and felt I using it well. But, every time looks back and read see my code a couple of months back, it looked awful. Over the times, I kept on learning and improving thanks to my mentor and colleagues. I started using Linters and learned what are the ways to write and ways not. So this about the bad side of JavaScript and especially Javascript scoping issues, which is the pillar in understanding this language for proper use.

JavaScript Scoping Issues

To know the JavaScript scope issues, first, we have to understand about global variables how it works and what is the scope.

Understanding Global Variables

Global variables or variables belonging to window are the great aid to newbies, Just assign a value in a global it can be used anywhere. Its pretty helpful, but, you don’t how bad it is until you are code starts getting bigger and bigger till you end up not knowing where the variables it declared.

Take this simple code,

As you can see thisIsGlobal is declared outside the function which automatically becomes a global level variable, it can be used anywhere. Can anyone see the problem here?

In the function foo I’m just directly using a thisIsGlobal. If the function foo becomes big, you will have no idea where this variable come from.

 

This example shows the badest way to use a variable. The variable ‘poem’ becomes global, function getPoem becomes global. Based on the order of usage in index.html, they are overwritten.

Solving This:
Never use a variable outside the function or put a function directly in a file. Better way to do this wrapping it like this,

The Scope & JavaScript Scoping Issues

What is scope? It is nothing but,

A block of statements wrapped in a curly braces. The one we seen previously is called ‘Global Scope’. And there is, Local/Functional Scope and Block scope (Recent JavaScript version)

Okay, the bad stuff here, when compared to other languages like PHP, is, if you forgot to var inside the function getPoem, it will automatically become a global variable.

Solving This

Always use var keyword inside a function in the very first line it starts.
Avoid global usage even intentionally

And Block Scope
The let is something new, its only supported in few browsers which support block level scope

Hope it makes it clearer about how scoping works in JavaScript and how it won’t show any errors or warning. Understanding how scope works and its usage and flaws are must for any developers.

 

Understanding Web Workers

Before getting to Web Workers, let us understanding the purpose for its need and how JavaScript works.

everything is single“,

  1. JavaScript will execute everything in a single thread.
  2. Each statement is added to a stack and will execute one-by-one.

The good thing is, our code will execute in a synchronous way. But the bad side is, rest of the statement in the stack has to wait if the current process takes a lot of time.

Performing heavy ‘client to server side’ task or huge data processing like JSON or complex calculations which going to taking a lot of time.

Eventually when we run this code, either it might freeze and become unresponsive or ends by blocking rest of the process (or both).

unresponsive

To solve this problem, we are going to use something called ‘Web Workers‘, which runs independently of any user interface. All the statements/code mentioned in ‘Web workers‘ will run in the background. Well, let’s get started.

  1. Need for Web Worker!
  2. What is Web Worker
  3. How it works
    • Creating a Worker
    • Web Worker Communication
    • Importing External Files
  4. Web Workers Example
  5. Stopping a Web Workers
  6. Handling Errors
  7. Security Concerns
  8. How to use & When to use
  9. Browser Compatibility

Consider the following example,

Not only it will take a lot of time to print the statement ‘end’… our browser freeze and hangs and you might end up killing the process.
Let’s see how the above code runs in Web Worker. To create a worker

and

Now, if you run this you won’t see any freezes at all! That’s the magic of the Web Worker.

So, What is Web Worker?

Web Worker provides a way to run the task in the background and independently of any user interface. We can put any long running tasks in workers which will not interrupt keyboard or mouse click events.

  • It enables to offload expensive operations
  • It includes separate message queue, event loop, and memory.

How it works

Creating Worker

Web Worker are created using the object Worker()

The new Worker('javascript_file.js') will look for a file named ‘javascript_file.js’ which will run independent thread from our actual code.

Web Worker Communication

To communicate to and fro from our worker we’ll use window.postMessage to pass messages.

Import External Files

Using importScripts you can import JavaScript files inside workers.

Let’s see an example, to understand all this stuff.

Web Workers example – Creating a simple Web Worker to poll for contents.

In this example, we will randomly fetch contents from Wikipedia periodically from workers in a nonblocking way.

First, let’s build the worker part and then create our index.html to link the worker. See the code below for explanation

Stopping Web Workers

Once our Web Worker is created, it will continue to listen for any changes using the event listeners, when it’s time to stop use the terminate command.

Handling Errors

The onerror event listeners we will attach the Web Workers for capturing any errors.

or simply

Security Concerns

Since Web workers use postMessage for communication, the origin needs to be checked on receiving the message.

https://security.stackexchange.com/questions/20022/how-to-use-postmessage-securely

Web Workers Limitations

Though awesome it seems there are some limitations with Web Workers.

  • You cannot access the DOM from web workers (I.e, No document, getElementById)
  • Cannot access global objects or functions on the main page
  • Workers have high start-up performance cost and high per-instance memory cost. So it’s best to use minimal amount of Web Workers
  • Communication to our application only be carried our using postMessage

Overall Web Worker is must use any high processing tasks, from web polling high data processing, it does’em all. But, know when to use Web worker and when not to. You don’t need to use it all the time. And finally, there are other types of Workers which will see it soon.

codelikeapoem_caniuse_web_worker

Reference

  1. https://gist.github.com/sk8terboi87/32699d5a3a9bcbdd10d7b94316f54ccd
  2. https://html.spec.whatwg.org/multipage/workers.html
  3. https://www.tutorialspoint.com/html5/html5_web_workers.html
  4. https://www.html5rocks.com/en/tutorials/workers/basics/
  5. http://ejohn.org/blog/web-workers/

Bashing your Way — Learn Bash Skills – 1

As with art, learning the foundations of skills can improve the productive over time. No matter what programming language like PHP, Node or Python you know, the very basic skill with Linux is shell programming. Shell programming is an essential skill many lacks. Here we learn bash skills.

Part 1 – Basic Bash

Bash – is the standard shell on Linux, also a superset of the Bourne shell such that, commands that work in sh, will work in bash also.

In Part 1, we learn some basic stuff to get started for anyone.

The Shebang!

All file to be written in bash starts with shebang which is #!/bin/bash. Below explains a simple file

Creating a File & Folder

Setting Permission

chmod – change file mode bits. The + operator used to add file mode bits and – to remove the file mode.

The combination of letters controls the user access

u is for a user,
g is for group,
and o is for others.

r is for reading permission,
w is for write permission,
x is for execute permission.

Variables

Note there shouldn’t be any space between = or bash will throw error which only wizards can understand 😛 and semicolon is not required at the end

Mathematical Operations

Mathematical operations are done using the $[]

 

Conditional & Comparison Statements

Following is the simple skeleton for if statement.

and else statement

Comparsion

Numeric

Text/String

File operation

Reading From Users

Reading from bash is very simple using read

Looping!

This takes care of part 1 of learning bash skills. In Part 2 we will make a big jump to advanced stuffs like sed, functions, signals & jobs.

 

My Secret Love For Atom — Going From Sublime Text to ATOM

One of the best sidekick for awesome programmer is the tool he/she chooses. I know that relying completely on a tool can slow us down but some tools are very important which defines a programmer. One of them is the editor he chooses. Long long back ago, one of my favourite was (sometimes still) is notepad++ when I’m working in Windows. I never could find a better, fast, easy editor like notepad++. Every since I moved on to linux for development, notepad++ was missing! It was a great lose to me in the beginning. I tried lot of editors like gedit, eclipse and etc. All of them are, well… okay to some extent but it never made me feel like “its the one“. Then i meet Sublime Text which I fell in love instantly and using it for more than 3 years now! But, after this long while and I fell in love again… for ATOM text editor.

My Blossoming Love With Sublime Text 2 & 3

Never I could find such a finer editor in my life, it is the best I could say which exist! Its perfect in all the way, It is smooth, lighting fast, tons of themes and dozens of packages. Below are the few reasons which makes a Sublime Text an awesome editor.

  • Like i said, smooth, lighting fast!
  • Based on Python and all settings are in JSON files (easy customizing)
  • Ease to install packages and themes
  • ctrl+p the life saver! Easy switch to files.
  • Tons of key bindings and shortcuts and easy way to customize them
  • Supports in Windows, Linux and OS X
  • Its free!!!

And here are the some of the finest packages/themes provided by Sublime Text

One Loves that Fades… Another Blossoms!

As times goes by (its like 3 years with Sublime Text), it started to feel little bored and I couldn’t see any huge difference in Sublime Text 2 to 3. Lot of packages and themes still growing and ofcourse, its still fastest when i met! But, there isn’t much huge change or cool updates.

Lately, I took resolution to study Python this year and found this book useful “learn python the hard way” (and its free online). The installation suggest to try something new called atom– yet another editor! I remember trying ATOM text editor long time ago and went off as it looks same as sublime and my love of sublime was more then! Today I tried again to give it a whirl (why not!). But I’m pretty much in awe after installating it! Its somewhat more grand and smooth! Its like falling in love at first sight! (not the first ofcourse). Some of the stuffs which got me loving this Atom text editor are

First impression, Best impression!

As soon as double click the ATOM icon, the first page look awesome! It was neat! Great start page. Its like Sublime but in a neater way!

ATOM welcome page
ATOM welcome page

Look at the above screenshot, neat 2 column layout with one introduction and right has everything you need to get started! Where as in Sublime Text, introduction will printed as text and no! information about how to get things started with themes and packages. We gotta install the package manager separately and start installing. This small but finer and clear information about these installation in the way beginning highly impressed me! (So I continued further…)

Theming – much easier to install!

Installing the theme is just a click way. I feel like Windows! Everything done snappy in click button.

ATOM settings page
ATOM settings page

As you can see, instead of Sublime Text everything is like HTML inputs, checkbox, color picker. There are lots of options to mess around. And yea, it also has the Google material theme.

ATOM Google UI
ATOM Google UI

But I’m lost the love of Android to Apple last year, so yea… I love the default ‘One Light’ UI and Syntax which is simple and elegant.

Looks – Smoothier and More Appealing!

Interface (sidebar + syntax area) is smooth similar to Sublime Text. The theme ‘One Light’ makes a milky look to the editor. It has the default ‘bracket matcher’, markdown preview, Git diff, able to add snippets.

ATOM package menu
ATOM package menu

It also has the variety of selections like select word, multiple word selection similar to pressing ctrl + d like in sublime text. There is a extra one which i found is the ‘select inside brackets’ which is seriously help for me as I work with huge unprettified XML & HTML files, its easy for me to select a chunk of a node. There is a shortcut of the same in Sublime Text or was it using an ‘add on’? Not sure. But its not clear as it is ATOM text editor.

Even the ctrl + shift + p is appealing in ATOM text editor.

ATOM smooth looks
ATOM smooth looks

Overall ATOM text editor is as good as Sublime Text but I’m starting to feel its much more than Sublime Text. But, I’m still going to use Sublime as my editor as i cannot replace with ATOM text editor just by using it in one day. So, I’m going to use partially for a week and then lets see. Both are great editors and best out there! So gonna for either one of them!

Keeping Promises using JavaScript – Part 1

Promises using JavaScript is not something new, it has been introduced years back, but we are not using because of not all the browsers didn’t support Promises at the time.

Before using Promises one should have clear idea about why need to use promises, as there any alternate apporaches to it etc. I seen lot of blog just giving a example to get started on promises before even explaning about basic asynchronous concept or even callbacks, which are related to JavaScript Promises. Below we are going to cover almost all concept involving around promises.

Life in Synchronous & Asynchronous Way!

Synchronous are things which are aligned over time, i.e one has response to the other and so on. For example, conversation is synchronous, dancing like that.

JavaScript, by default holds to things and do it one by one which we id this a “synchronous” (Except for few things like AJAX calls). Because JavaScript is single threaded and code will run one after an another.

Eventhough the working of ‘Synchronous’ can be useful for debugging; but it limits the thought of doing things multiple.

The problem with handling multiple things at the same time is “how to handle” the response? However, there are lot of other options to try.

Living with Callbacks!

Callbacks are nice way to acheive “asynchronous” way! Just a create a function, wrap the environment and pass it on, so it can be triggered somewhere else.

Example: simple callback

This is just a simple example, we can create even more complex callbacks. But there comes a problem with callbacks which are difficult to solve.

Example: Deep nesting A.K.A callback hell

{ function OnSuccess() { function DoThat() { …. } } function OnFailure() { function CallThis() { } } }

– Deep nesting
– Inconsistent callback behaviour
– Handling Errors
– Chaining

you read more about issues on callback from [https://medium.com/@ayasin/solving-common-node-io-js-callback-problems-d3d1f6049259]

What about Events?

Similary like callback, events are great way to attach multiple times on a same object. Managing success and failure is still tricky!

Writing as Human Brain’s – Promises!

Promises – an asynchronous operation which provides great way to handle simulationous requests with precesion. They provide callbacks like functionality for each indiviual requests with more control both success and error data.

Promises exist to represent something that will be available in the future

Promises are very Promising because…

  • Code looks clean and more readable
  • Catching errors
  • Chaining
  • Multiple API calls &checking it simultaneously.

Solving the callback hell using Promises!

even better, chaining,

also, simultaneously run!

With JavaScript Promises, you can acheive the asynchorous way with ease and have more control over the data. In the part 2, we will some examples in action and also we need to know when to use Promises and when not to use it. Thats it for today! Enjoy!

Promises ain’t Callbacks; Its better!

References
  1. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
  2. http://robotlolita.me/2015/11/15/how-do-promises-work.html#introduction
  3. http://www.bloggerever.com/2015/09/all-you-need-to-know-about-javascript.html (for the image)

Ubuntu Budgie — The Newest Ubuntu Flavour

Ubuntu Budgie is the newest and coolest of the Ubuntu version which just landed! It digs some awesome looks LightDMArc GTK and Faba Icons. It has really smooth interface (feels like mac) and tons of update!

codelikeapoem-budgie-menu

So what is Ubuntu Budgie!?!

  1. This a version of the operating system which uses the relatively new Budgie environment.
  2. Budgie Remix 16.04 is based on Ubuntu 16.04 LTS
  3. It includes the latest Budgie Desktop 10.2.5. Budgie Desktop
  4. Budgie Remix 16.04 includes Nautilus 3.18

Budgie is the flagship desktop of Solus and is a Solus project. It focuses on simplicity and elegance

Installing Ubuntu Budgie

or download directly from https://budgie-remix.org/downloads/

Check it few screenshots

codelikeapoem-budgie-remix

 

codelikeapoem-gnome-videos

codelikeapoem-libreoffice

Learning the Basics — Machine Code and High Level Languages

Now we know how a CPU executes a program, let’s move on to understanding machine code and high level languages. This is the next step in understanding core concepts.

Understanding Machine Code and High Level Languages

The above nice illustration video shows how machine code gets converted by assembly into machine understandable format.

Low-Level Languages

Low-level languages are referred to as ‘low’ because they are very close to how different hardware elements of a computer actually communicate with each other.

Example: 10010101100101001111101010011011100101

High-Level Languages

A high-level language is a programming language that uses English and mathematical symbols, like +, -, % and many others, in its instructions.

Example:

Compiler

Computer program that translates a program written in a high-level language to the machine language of a computer.

Example: gcc, clang, go

Interpreter

Computer program that simulates a computer that understands a high-level language (or) a program that executes source code or byte code.

Example: ruby, python, php.

Thats it for today in understanding machine code and high level languages. Happy learning.

References:

Learning the Basics — How does a CPU executes a Program

We are learnt how a microprocessor works, but, I didn’t learn well. All i ever want to get a degree in my engineer! Now, I am seeing myself how i lacked the basics even though I could do well in UI & Backend, I am seriously missing the basics. So, here is an awesome video showing how does a CPU executes a Program.

How Does a CPU Executes a Program

Reference

 

Geolocation API — How to get current user location

Before using Geolocation API, lets understand why need to use it.

If you are building a web application, there will come a time where your need to know the current location of the users. Why I need to know the location of the users? Because you might need to show contents relevant to the location of the user or even change your locale based on it or even you can allow use to track location using app ex. fitness apps.

Geolocation API

JavaScript has an API which can be used to retrieve the user location, only if user allows permission. Below is a script simple script to do that!

Breakup of above Geolocation API

1) Getting Geolocation object

We check for whether geolocation api is currently supported in our browser.

2) Getting Current Position

Now if the thing is supported, we can easily pull the latitude and longitude of the current user location.

Make sure to provide permission for browser to pull your current location

geolocation-api
Geolocation allowing permission

 3) Watch Position for Change.

Finally, you can use the watch to track the changes in user location and update it. (cases in which we provide mobile apps like fitness app to track user jogging locations)

4) Using Google Maps or OpenStreepMap to display the fetch information in a awesome map

Google Maps:

OpenStreeMaps: (Make sure to include OpenLayers.js)

You can even revoke permission later to any site by clicking the label in address bar.

geolocation-revoking-permission
Geolocation revoking permission

Geolocation Accuracy

Geolocation is most accurate for devices with GPS.

“W3C Geolocation” — the Web site will get the accuracy of whatever geolocation method (whether based on IP, access point MAC, GPS, cell-ID, etc.)

Some Web browsers have access to GPS receivers. Some of them (like Firefox and Chrome/Chromium) can use the MAC address of a WiFi access point to query Google’s database of the locations of WiFi access points.

Geolocation API removed from unsecured origins in Chrome 50

 According to Google API, https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https, but it is a change that we do believe is beneficial to all users on the web. This post should help you understand the reasoning and how to proceed.

 Browser Support

http://caniuse.com/#search=geolocation

geolocation browser support
geolocation browser support

References

  1. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation
  2. http://caniuse.com/#search=geolocation

 

Yet another UI Framework — Aurelia For beginners

AngularJS is one of the coolest front end frameworks I’ve ever used, but it doesn’t hurt to try more Frameworks. One Em is Aurelia, a actually simple JavaScript framework or say framework of tomorrow. (Just like AngularJS). Below aurelia for beginners provides an insight of how to install and also know the difference between AngularJS and Aurelia.

Getting started with Aurelia for Beginners

Why aurelia is awesome? Because of the few below stuffs which makes it easier to run and understand at the same time, it still gives the power to write very simple code. So, anyone can easily write a Aurelia code.

  1. Focus on business logic, not on framework
  2. For users looking for fast development also providing a structured UI FRAMEWORK
  3. Written with next-generation EcmaScript. Integrates with Web Components.
  4. Similar to AngularJS, “Two-way” Binding
  5. Can be written using ES5, ES 2015, ES 2016 and TypeScript

Installation

There are lots of way to install Aurelia, you can use Yeoman, Webpack or simple Aurelia-CLI

Pre-requirements

  1. NodeJS 4.x
  2. npm 3
  3. npm aurelia-cli

To make it less dependent on machine installation (Ubuntu/Windows), lets install aurelia in Docker. So, it can run in any machine! Cool!!

Installing Aurelia on Docker for Windows

1. Create a Dockerfile with below content

2. Now run docker build -t aurelia/cli

3. Now you have the Docker image lets create a container for this image and bash into it!

4. After executing this command, you will be inside the container. lets check whether it is installed correctly with the $ aurelia

checking aurelia in windows
checking aurelia in windows

Starting your project

Using the in-built Aurelia CLI command lets create a project. (Since you previously ran docker run command, you’ll be inside the container now)

  1. Now cd /Aurelia
  2. Run the command to create a new project au new --here
  3. The wizard you can keep hitting enter (unless you want to modify the default value. I’ve choose Sublime Text editor instead of VS Code)
  4. Now see the project directory, it’be created.
    aurelia-cli-new-project
    aurelia-cli-new-project

    5. Finally after confirmation you have created a project successfully (with everything you needed for awesome in a jiffy)

Aurelia Vs. Angularjs

Now we’ve created a project, you can simple create a todo example and try it http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/quick-start/1 (skipping the setup part)

1. Syntax: No weird symbols or abstract naming, just similar syntax to what you can already find within Javascript itself.

2. ES6 Support: You write web applications using ES6 syntax and not have to worry about ES5 support because the included build system and configuration. With AngularJS, you’ve to learn its abstractions; directives, controllers, services, factories

3. Pluggable & Modular: Framework that can be decoupled to the point where you can use parts of Aurelia in other applications/Node.js modules.

4. Templating in Aurelia: Utilises the W3C HTML Imports specification for importing HTML templates and logic.

5. Dependency Injection: Just define a static method that returns what you want to be injected into the application!

Overall Aurelia seems and better than AngularJs in terms of simplicity with power matching to AngularJS. But, there is one question goes in the mind of most of the UI Developers, why another UI Framework? We just learnt and starting using AngularJS and now another?

Well, Aurelia is created long back and thing is that, there is always going to be tons of ‘yet another framework’ whether is PHP or UI or whatever, you can either stick to what you like or learn something new. And there are so many “new”, so might good and provide tons of new features and browser support or some might now. So before trying a new Framework your application, it’s better know the ups and downs of a framework and its support. Both Aurelia and AngularJS are great frontend framework! But, comparatively with Aurelia, AngularJS is very well know and has tons of support over the web.

Well, thats it. Thank you for reading!

References:

  1. http://blog.aurelia.io/2015/03/16/aurelia-and-angular-2-code-side-by-side/
  2. http://ilikekillnerds.com/2015/01/aurelia-vs-angularjs-round-one-fight/
  3. https://github.com/aurelia/framework/issues/74