JSHint Errors

When using a simple ternary operator with JSHint, may cause the build error shown below,

someExpressionThatIsEitherTrueOrFalse ? someFunctionThatIsCalledIfExpressionIsTrue(x, y) :
setOtherVariableIfExpressionIsFalse = true;
^ Expected an assignment or function call and instead saw an expression.


Add below JSHint Comments where expression has been written

/* jshint expr: true */


/* jshint expr: true */
nameController.isMiddleNameNullOrEmpty ? submit() : validate();

Note: The important thing to remember is to have this JSHint comments (/* jshint expr: true */ ) be used only within the function where the expression is being used, else it would turn off the JShint globally.

All about NPM (Node Package Manager)

All about NPM (Node Package Manager) https://www.npmjs.com/

  • Its about Sharing the Code or Packages or Modules on the node package manager repository.
  • By default node package manager repository is publicly accessible, however there are options to make it private at a price.
  • We can search for packages that have been registered in the registry. Go to https://www.npmjs.com/ and find the Packages or Using the Query URL https://www.npmjs.com/search?q=bower
  • The packages are managed and powered by the CouchDB database.
  • You can also run the published packages on the node package manager over the browser using Runkit @https://runkit.com/npm/npm-demo-pkg29 where “npm-demo-pkg29” is the package I created. This package has a reported method “printMsg()”, which prints “Hello”. You can also share the code https://runkit.com/5801f19682bd9d0014eec77c/580289b7ce0bd500138eec0c

Here are some of the differences between Packages and Modules within NPM


  • A “package” is a file or directory that is described by a package.json file. In other words, a package.json file defines a package. For example, if you create a file at node_modules/foo.js and then had a program that did var f = require(‘foo.js’), it would load the module. However,foo.js is not a “package” in this case, because it does not have a package.json.
  • A package is any of:
    • a) a folder containing a program described by a package.json file
    • b) a gzipped tarball containing (a)
    • c) a url that resolves to (b)
    • d) a <name>@<version> that is published on the registry with (c)
    • e) a <name>@<tag> that points to (d)
    • f) a <name> that has a latest tag satisfying (e)
    • g) a git url that, when cloned, results in (a).
  • Even if the package is never published to the npm repository, you can circulate the packages locally and achieve benefits of using npm:
    • if you just want to write a node program, and/or
    • if you also want to be able to easily install it elsewhere after packing it up into a tarball


  • A module is any file or directory that can be loaded by Node.js’ require(). For example, if you create a package which does not have an index.js or a “main”field in the package.json file, then it is not a module. Even if it’s installed in node_modules, it can’t be an argument to require().
  • ‘CLI’ packages for example is not modules since they only contain executable command line interface and don’t provide a main field for use in Node.js programs.
  • A module is any of:
    • A folder with a package.json file containing a main field.
    • A folder with an index.js file in it.
    • A JavaScript file.
  • In the context of a Node program, the module is also the thing that was loaded from a file. For example, in the following program:
    var req = require(‘request’)
    we might say that “The variable req refers to the request module”.
  • Most npm packages are modules because, npm packages that are used in Node.js program are loaded with require, making them modules. However, there’s no requirement that an npm package be a module

Here are the list of NPM commands that I use (some of which are the ones that I occasionally use).

npm -v
Gives the version of installed npm

npm install npm@latest -g
Installs the latest version of npm

npm install {packageName}
{packageName} can be any packages that are available on the npm repository. If the Packages are not available then npm CLI will throw error.
npm install {packageName} -g
options: -g
global install. Usually this gets installed in (/usr/local). If this option is not specified, node_modules gets installed in the same directory where you are on the terminal. Check pwd for the current directory.

For uninstalling use npm uninstall {packageName}

Note: Just in case if you do not have permissions to the folder (/usr/local), run the commands using sudo prefix

npm config get prefix
Gives the current directory where npm modules gets installed globally.
Check this https://docs.npmjs.com/getting-started/fixing-npm-permissions if you intend to change permissions.

npm init
This is used to create a package.json with a questionnaire being prompted on CLI.

npm init –yes
option –yes // Creates a default package.json file with default inputs, without asking any questions.

npm install {packageName}  –save This adds entry to package.json’s dependencies attribute.

For removing the dependency use npm uninstall {packageName} – – save

npm install {packageName}  –save-dev
This adds entry to package.json’s devDependencies attribute

For removing the dependency use npm uninstall {packageName} –save-dev

npm update
Updates the dependencies of the the packages defined in the package.json file. Note: The folder should contain package.json file

For updating all packages globally (/usr/local), use option -g; npm update -g

npm outdated
Check if the packages are outdated.

For checking all outdated packages globally (/usr/local), use option -g;

npm outdated -g

npm outdated -g –depth=0 // Same as above, but finds at a given depth

npm config list
Spits out the npm’s configuration file’s list

npm config ls -l
Lists out all the default values of npm’s configuration file.

npm ls  OR npm list
Lists the dependencies and see the relationships of other dependent dependencies with version numbers

npm ls –depth=0
Lists only the primary dependencies. The other alternative is using the ‘tree’ command tree -d /usr/local/lib/node_modules

npm root
Gives the directory path where node moduels are installed. npm root -g gives the directory path where node modules are installed globally.

npm view {packageName} version
Ex: npm view angular version
Gives the package version that is installed locally. -g at the end of the command gives the package version installed globally.

Breakdown of NPM resources from NPM Documentation:

Using package.json with versioning’s and versioning details:






Creating and Publishing packages to npm registry:



NPM’s Dependency resolution, Duplication and DeDuplication





Javascript: A word with Spaces

Given a word “HELLO”, print the word with spaces “H E L L O”.

Naive Solution:

function spacing(a){
   var b = a.split(''), c = b[0];
   for(var i=1; i < b.length; i++){
       c += " " + b[i];


The output is:

h e l l o

Using Javascript prototypes:

function SetString(stringName){
   this.stringName = stringName;

function SpacingFunction(){
   var b = this.stringName.split(''), c = b[0];
   for(var i=1; i < b.length; i++){
      c += " " + b[i];

SetString.prototype.spacingFunction = SpacingFunction;

new SetString('hello').spacingFunction();

The output is:

h e l l o



Javascript: Type Error vs Reference Error

In order to understand Type Error vs Reference Error, first we will need to know Variable Declaration vs Variable Initialization.

var x;

In this above statement, we can say that x is declared but not yet initialized.

var x = 5;

Here, we can say that x is declared and as well initialized.

Now, let’s say we would want to access the x’s property that has been declared but not initialized.

var x;

This would result variable x to be


Now, let’s say that we would want to declare and initialize x to undefined and then access the x’s toString() method.

var x = undefined;

This would result in

Uncaught TypeError: Cannot read property ‘toString’ of undefined(…)

Now, let’s say we would like to access the x’s property thats been been declared as well as initialized.

var x = 5;

This would result

5   // Since 5 is declared and initialized as a number, 
    //and we were trying to convert it to a String.

Now, let’s say we would want to access a variable y that doesn’t exist in the scope (meaning that there is not presence of variable y with out any initialization or declaration)


This would result in

Uncaught ReferenceError: y is not defined(…)


Happy Learning 🙂

Order of execution in Javascript

Given the below functions

function ME(){console.log("ME")};

function MYSELF(){window.setTimeout(function(){console.log("MYSELF")}, 0);}

function I(){
   return new Promise(function(resolve, reject){
     }, function(error){

If I supposedly call these functions sequentially as shown below:


Here is the order the javascript engine (Google’s V8 if chrome) takes precedence of executing it.

The output would be:

ME    // The ME() function outputs its result in the first place because it gets executed immediately even though it is being called in 3rd line, and the main reason being, it has no timeouts and nothing gets listed to the browser’s window Object

MYSELF   // The MYSELF() function outputs its result the second place even though it is being called in the 1st place AND it has a timeout function which is set to 0 seconds, because the timeout function is bound to the window object of the browser and it takes an extra roundtrip for the browser to get the event listened on its window object.

I   // The I() function outputs its result in the third place even though it is being called in the 2nd place, because it uses the asynchronicity feature using the Javascripts Native Promise function and also the resolve function of Promise gets called after a timeout of 5 seconds.



Find the middle element of the linked list in single pass – O(n) complexity

A linked list contains Nodes that are linked to each other.

Create a Node – A node consists of data of that node and some information about the next linked node

function Node(data, nextNode){
this.data = data;
this.nextNode = nextNode;

Create all nodes

Note: First Node from right. This would be our last node in sequence. The reference to next node would be null since this is our last node.

var n5 = new Node("5", null); 
var n4 = new Node("4", n5);
var n3 = new Node("3", n4);
var n2 = new Node("2", n3);
var n1 = new Node("1", n2);

// So here is the representation of the linked list nodes, that we just created.
// n1 (1, n2) –> n2 (2, n3) –> n3 (3, n4) –> n4 (4, n5) –> n5 (5, null)

Here is how the linked list looks


The Naive Solution to this problem would be in 2 passes (2 for loops), which takes O(n^2) worst case complexity

1st pass is to loop thru to get the count of nodes in linked list and
2nd pass is to loop thru find the middle element by dividing the Count of Nodes by 2

So, for example if there are 5 Nodes.

1st pass is to count the number of nodes = 5
2nd pass is to loop thru to get the middle element by dividing 5/2 = 2.5 (so in the middle element to be 3)

There is a better and a faster way to get this in 1 Pass (1 for/while loop), with O(n) complexity

Assign 2 pointers while looping.
1st pointer moves 1 element at a time.
2nd pointer moves 2 elements at a time (twice as faster as the 1st pointer)

Some theory/story:

Assume that Person A and Person B would like to reach a destination X from same starting point.

Assume that it would actually take 10 mins to reach destination X.

Assume that Person B walks 2 times faster than Person A, then by the time Person B reaches destination X, Person A is exactly half way thru.

So, lets give a starting point to our node n1.

var slowNode = n1;
var fastNode = n1;

// Check if nextNode is not null and nextNode of the nextNode 
// (2 Nodes from the current Node) is also not null
while(fastNode.nextNode != null && fastNode.nextNode.nextNode != null) {
// slowNode should be moving to the next element of the linked list sequentially
slowNode = slowNode.nextNode;
// Now the fastNode should be twice as faster as the slowNode
fastNode = fastNode.nextNode.nextNode;


Relevant Code using Java

public class MiddleElementLinkedList {

	 * @param args
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// Create Linked List Nodes
		LinkedListNode n5 = new LinkedListNode("5", null);
		LinkedListNode n4 = new LinkedListNode("4", n5);
		LinkedListNode n3 = new LinkedListNode("3", n4);
		LinkedListNode n2 = new LinkedListNode("2", n3);
		LinkedListNode n1 = new LinkedListNode("1", n2);
		// Set the starting point
		LinkedListNode slowNode = n1;
		LinkedListNode fastNode = n1;
		while(fastNode.getNextNode() != null && fastNode.getNextNode().getNextNode() != null){
			slowNode = slowNode.getNextNode();
			fastNode = fastNode.getNextNode().getNextNode();
		System.out.println("Middle Element: " + slowNode.getData());

	public static class LinkedListNode {
		private String data;
		 * @return the data
		public String getData() {
			return data;

		 * @param data the data to set
		public void setData(String data) {
			this.data = data;

		 * @return the nextNode
		public LinkedListNode getNextNode() {
			return nextNode;

		 * @param nextNode the nextNode to set
		public void setNextNode(LinkedListNode nextNode) {
			if(nextNode == null)
				this.nextNode = null;
			this.nextNode = nextNode;

		private LinkedListNode nextNode;
		LinkedListNode (String data, LinkedListNode nextNode) {
			this.data = data;
			this.nextNode = nextNode;


Here is how the linked list looks in Java



Happy Coding !!!

A few Javascript Gotchas

Regular Equality vs Strict Equality.

{} === {}

false // Even though they are empty objects, strict equality not only checks for type & value, but also checks the created instance. The created instance is different for each new Object

{} == {}

{x:5} == {x:5}

{x:5} === {x:5}

0 === false

0 == false

0 == 0

0 === 0

1 == 1

1 === 1

new Object() == new Object()

new Object() === new Object()

Object.create([]) === Object.create([])

Object.create([]) == Object.create([])

var x =””;
if(x){console.log(“123”)} else{console.log(“456”)}

var x = [];
if(x){console.log(“123”)} else{console.log(“456”)}

“” == 0

[] == “”

“” === 0

[] === “”

“” == ”

“” === ”



” instanceof String

“” instanceof String

new String(“”) instanceof String

typeof(new String())

“”.toString == new String(“”)

“”.toString() == new String(“”)

“”.toString() == new String(“”).toString()

“”.toString === new String(“”)

“”.toString() === new String(“”)

“”.toString() === new String(“”).toString()

[] == new Array[];
VM362:1 Uncaught SyntaxError: Unexpected token ]

[] === new Array[];
VM363:1 Uncaught SyntaxError: Unexpected token ]





typeof(new Array())

typeOf(new Array()) // typeOf is not defined, O in red is capital
VM418:1 Uncaught ReferenceError: typeOf is not defined(…)(anonymous function)

[].constructor.toString().indexOf(“Array”) > -1

[] instanceof Array

typeof null

typeof {}

{} instanceof Object
VM1270:1 Uncaught SyntaxError: Unexpected token instanceof

var t = {}
t instanceof Object

Object instanceof t
VM1385:1 Uncaught TypeError: Right-hand side of ‘instanceof’ is not callable(…)

typeof undefined
Note that typeof undefined is undefined which is wrapped in string quotes, but not a string.

typeof (typeof undefined)
Since the (inner) typeof undefined is undefined wrapped in string quotes, and the (outer) typeof (“undefined”) is being assumed as a string.

typeof when variable is defined.

var d = {};

typeof d === undefined

typeof d === “undefined”

d === “undefined”

d === undefined

typeof when variable is not defined

typeof u === undefined

typeof u === “undefined”

u === “undefined”
VM455:1 Uncaught ReferenceError: u is not defined
at <anonymous>:1:1
(anonymous) @ VM455:1

u === undefined
VM458:1 Uncaught ReferenceError: u is not defined
at <anonymous>:1:1


1/-0 > 0


-Infinity == 0

-Infinity > 0

-Infinity === 0

-Infinity > 1

-Infinity == 1

-Infinity === 1

Infinity == NaN

Infinity === NaN

1 instanceof Number

1/0 instanceof Number


Infinity instanceof Number



new Number(1) instanceof Number

99.99 instanceof Number


new Number(99.99) instanceof Number


NaN instanceof Number

new Number(NaN)
Number {[[PrimitiveValue]]: NaN}

new Number(NaN) instanceof Number

NaN == Number

NaN === Number

new Number(NaN) === Number

new Number(NaN) == Number

NaN == undefined

NaN === undefined

NaN === ”

NaN == ”

NaN == null

NaN === null



var e = function(){};
var r = function(){};
var e1 = new e();
var r1 = new r();

e == r

e === r

typeof e

e instanceof function
VM352:1 Uncaught SyntaxError: Unexpected end of input

function instanceof e
VM387:1 Uncaught SyntaxError: Unexpected token instanceof

e1 == r1

e1 === r1

e1 instanceof r1
VM750:1 Uncaught TypeError: Right-hand side of ‘instanceof’ is not callable(…)(anonymous function) @ VM750:1

e1 instanceof Function

e1 instanceof Object



var a = [1,2,3];
var b = [4,5,6];

a = b
[4, 5, 6] // This the value of a

[4, 5, 6] // a assignment to b copied over all values of b

[4, 5, 6] // No changes to b, so b still had reference to its original values

Pass by reference/value

var func = function(a) { var tempArray = [4,5,6];   a = tempArray;   console.log(a);}


[4,5,6] // Even though we pass by reference with a different value, the assigned variable value would be overridden with internal assignment (if any).

Which is best to use: typeof or instanceof?


mailto: protocol with attachment in javascript?

Hello Folks,

It’s been quite a while I haven’t word pressing. I wanted to take some time out to blog a few helpful coding tips & tricks that I am coming across these days.

A few days back, my colleague had a requirement on opening a Outlook email using simple javascript which also includes a attachment to the outlook email. Well google’ing a bit found the answer to do so, but including a attachment to that is being hosted on a different server (OnBase Document Server) was a challenge.

Clicking this button below opens the Mail Draft Dialog Window (Mail is a default application for eMails in Mac OSX) / Outlook Draft Dialog Window (if Windows OS), with user set TO (sent by) email address, Subject Line (Outlook takes in maximum of 255 characters on Subject Line), Message Body. Note that the FROM (received from) email address will be decided by the default account set in Mail App/Outlook App.


<a href="mailto:rc@rakeshchouhan.com?subject=Test%20Mail-To-Talk"></a>
According to RFC 2368 you can’t add an attachment to a message with the mailto: URL scheme due security reasons:

The user agent interpreting a mailto URL SHOULD choose not to create a message if any of the headers are considered dangerous; it may also choose to create a message with only a subset of the headers given in the URL. Only the Subject, Keywords, and Body headers are believed to be both safe and useful.


mailto: only supports header values or text/plain content.


Happy learning 🙂

Difference between dot ‘.’ and Square Braces ‘[]’ notations

Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.

The dot notation only works with property names which are valid identifier names [spec], so basically any name that would also be a valid variable name (a valid identifier, see also Valid Characters for JavaScript Variable Names) and any reserved keyword [spec].

Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.


obj.foo;  // valid
obj.else  // valid, reserved keywords are valid identifier names
obj.42    // invalid, identifier names cannot start with numbers
obj.3foo  // invalid,                ""
obj.foo-bar // invalid, `-` is not allowed in identifier names

obj[42]   // valid, 42 will be coerced to "42"
obj["--"] // valid, any character sequence is allowed
obj[bar]  // valid, will evaluate the variable `bar` and 
          // use its value as property name

Use bracket notation:

  • When the property name is contained in a variable, e.g. obj[foo].
  • The property name contains characters not permitted in identifiers, e.g. starts with a digit, or contains a space or dash (-), e.g. obj["my property"].

Use dot notation: In all other situations.

There is a caveat though regarding reserved keywords. While the specification permits to use them as property names and with the dot notation, not all browsers or tools respect this (notably older IE versions). So the best solution in my opinion is to avoid using reserved keywords for property names or use bracket notation if you cannot.

Square bracket notation allows use of characters that can't be used with dot notation: var foo = myForm.foo[]; // incorrect syntax var foo = myForm["foo[]"]; // correct syntax

The second advantage of square bracket notation is when dealing with variable property names.

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables
  • The bracket notation allows you to access properties by name stored in a variable:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

obj.x would not work in this case.


You cannot use . to access array elements. However you can use both . and [] to access object properties.

When trying to access a non-existing object property with . you will get an error but if you try with []instead you will get undefined