Tuesday, 13 September 2016

Java Script Falsy Values

Java script is weird. Here is another weird behavior of java script. Like any other programming language Java Script has Boolean data type. But in Java Script any value and any data type can be converted into Boolean. If some one not understand falsy values they might run into trouble. Understanding of falsy values will help you in debugging.

What is falsy?

Any value which will be translated into false is called falsy. Below are the falsy value of Java Script.

  • false
  • 0 (Zero)
  • ""(Empty String)
  • null
  • undefined
  • NaN (It is a Number But Not-A-Number)

1
2
3
4
5
6
console.log(!!(false)) // false
console.log(!!(0)) // false
console.log(!!("")) // false
console.log(!!(null)) // false
console.log(!!(null)) // false
console.log(!!(null)) // false

All other than above values are true in Java Script. You might wonder what about the "0" (Zero in double quotes)? But it is also returns true.


1
console.log(!!("0")) // true

Based on above logic one might think below code will return false.


1
console.log("0" == false) // true

What? "0" is true, true==false should be false. But it is not. This called coercion. It is not bug. It is feature. TO get better understanding look at this "Java Script Coercion".

Above mentioned values are falsy. Each one will behave differently when comes to comparision between then. Look into the compare table of falsy values.

==false0""nullundefinedNaN
falsetruetruetruefalsefalsefalse
0truetruetruefalsefalsefalse
""truetruetruefalsefalsefalse
nullfalsefalsefalsetruetruefalse
undefinedfalsefalsefalsetruetruefalse
NaNfalsefalsefalsefalsefalsefalse


False - Zero - Empty String

The falsy values false, 0 and "" are equivalent when comparing to one another.

1
2
3
console.log(0 == false) // true
console.log("" == false) // true
console.log(0 == "") // true



null and undefined


The falsy values null and undefined is false with all other falsy values except themselves.

1
2
3
4
console.log(0 == null) // false
console.log(0 == undefined) // false
console.log(null == undefined) // true
console.log(null == null) // true


NaN

NaN returns false with any value including NaN itself.


1
console.log(NaN == NaN) // false

Hope you have good understanding on falsy values of Java Script.  

Friday, 9 September 2016

JavaScript Coercion

Java script is weird. We know that. Here is one of the weird behavior.Let us look into the below two lines of code. In most of the programming languages, it will thrown as error "Can not compare Boolean to number". But java script won't throw an error and executes the code.

1
2
console.log(1<2<3);//true
console.log(3>2>1);//false

Java script will execute the above lines, that is fine. But why the first line is true and second line is false? On a plain sight any one can think of that if first line is true then second also should be true right. It is not. Let us see why this weird behavior. To understand this behavior we need to know the coercion.

What is Coercion?

In Java script coercion is treated as error and unexpected behavior. But it is a feature of Java script and we need to know how to use it. Coercion is will be applicable only on "==" and logical operators operator.

Type Coercion means if the data types operands of an operator are different. One of the operator is type castes to other operators type. Or both operands will be converted to a common data type.


1
console.log(5+"7"); //57

In a above line 5 is converted into string and + is concatenation operator. So output will become 57. This kind of implicit type casting is called coercion.

Line 1 :
Now try to solve the above problem. In the first line there are two operators and precedence will be left to right.


1
2
3
4
5
6
7
Console.log(1<2<3);
//Step 1: 1<2 is true.
//Step 2: result of the  1 < 2 will be placed in console.log.
Console.log(true < 3);
//step 3: Coercion will happen then true will be converted to number. true => 1.
//Step 4: 
Console.log(1<3); // is true.

Line 2:
Now we see the second line of code execution step by step.


1
2
3
4
5
6
7
Console.log(3>2>1);
//Step 1: 3>2 is true.
//Step 2: 
Console.log(true > 1);
//Step 3: Coercion will happen then true will be converted to number. true => 1.
//Step 4: 
Console.log(1 > 1); // is false.

This what happened in above code. Coercion happened. If you are not comfortable with coercion use "===" triple equal. "===" will compare data type and value both.

Please refer the coercion table..



Thursday, 1 September 2016

What is HOSTING in Java Script?

Hoisting

This is another weird part of Java script. Some times this is misleading and useful at times.  Let us take an example below.

1
2
3
console.log(myvar); //undefined
var myvar ='Hello World!';
console.log(myvar); //Hello word!

In most of the programming languages line 1 will result in an error saying variable not declared. But in Java Script it didn't throw an error. if we assume that without var keyword variable got created then second line should result in error saying variable already declared. Neither of them happened.

What is happened?


Hoisting is happened. Hoisting is not an ECMA terminology. Execution in Java script engine is happens in two phases.

Creation


On creation phase all variable and functions will get allocated memory. By default variables will get assigned with undefined. This creation phase is mostly misinterpreted as hoisting.

Execution


In Execution phase only code will be get executed line by line. Execution is like any other programming languages will be executed line by line.

Here is what happened. 


On creation phase myvar variable is got created and assigned with undefined. On execution phase, first line printed undefined, on second line myvar will get assigned with "Hello world!". In third line it printed with "Hello world!".


Conclusion


Hoisting is nothing but allocation memory to variables and functions even before the execution of line of code.To avoid confusion declare variables at the top of the function. 

Thursday, 18 August 2016

Java Script - Understanding the difference

Java Script is some times weird...

Introduction
Java Script is one of the most popular languages in the world. I always felt even though it is most popular language but still it didn't got the respect or recognition to it. We can't deny that some of the widely used soft wares were written in it.

May be you are new to Java Script or you know it for years. Question is how much you really know about it. Today we are not going to discuss about creating an interactive web page. We are going to understand How Java Script Works? We need to understand the authors of JQuery understood. Lets get started.

What is Java Script?

Java Script is a Single-threaded Non-blocking Asynchronous Concurrent Language. 

"What? What are you talking? Single threaded but concurrent? How come it is possible". I hope this would be your reaction.
Yes. Java script is single thread. At any given point only one thing can be executed through Java Script Engine. "Concurrency" is possible with help of asynchronous callbacks. What is call backs? Will discuss it later.


What is Blocking?
There is no strict definition on blocking. Any code which runs slower in the browser or makes the browser slower is called blocking. Now you got it what is non-blocking. Writing code which won't affect the browser performance is called non-blocking code.

Pothum.. Will look into our problem..
1. Problem


By looking at the code normal programmer will say the output will be as below.
Pic 2. Expected Output


It is wrong. One can argue by saying "if Java script is single threaded then above output is correct.  In C# it would be the output.".  Java Script is weird. Actual output is
Pic 3. Actual Output


There is no issue in the code. Actual problem lies in the understanding How Java Script Works under the hood? To understand why it happened like that  we need to the know the components in browser.

Browser Components:
  • JS Engine - Call Stack or Execution Stack
  • Web APIs
  • Task Queue or Event Queue 
  • Event Loop
Pic 4. Components of browser

From above picture, it is clear that Java Script Engine has two components one is Heap which is used memory and other one is Call Stack. Java Script Engine does not know setTimeout. I got surprised when i first found that. Web APIs browser components for DOM, AJAX etc. If Java Script Engine wanted to change a value in a text box. It requests DOM API. Once the WEB API completed there work and want to execute the callback then it will add it to callback queue. Event Loop will fetch the item from callback queue and add it to call stack. Once it added into call stack it will get executed.

Event Loop adds the callback to Call Stack only when the Call Stack is Empty.

Let us see step by step:

1. Console.Log will get executed. "Hi" will get printed.
2. Variable status will get initialized with false.
3. Ajax call will get executed. JS Engine will send the call to Web API.
4. If Condition Statement will get executed. Status will be still false so "fail" will be printed.
5. Now call stack is empty.
6. In the mean time, WEB API executes the ajax call and adds the callback to event queue.
7. Event loop checks the call stack is empty or not? Now Call Stack is empty so callback will be added to Call Stack.
8. Callback will get executed and Pronts "I am in".


Down the Files  Here....