Showing posts with label advanced JavaScript. Show all posts
Showing posts with label advanced JavaScript. Show all posts

Saturday, January 20, 2018

JavaScript : Can (a ==1 && a== 2 && a==3) ever evaluate to true?

You may also like to see:

Recently, this question has been making the round on different sites on the internet like Reddit and StackOverflow.

The answer to the question is Yes!, it is possible in  JavaScript.






You might have already seen the solution on different sites, I will try to explain the code to make you understand why it works.



const a = {
  i: 1,
  valueOf: function () {
    return a.i++;
  }
}

if(a == 1 && a == 2 && a == 3) {
  console.log('JavaScript Rocks!');
}

Why It Works?


There isn't any trick in this code. The solution is simply using the concept of loose equality using double equals(==) operator. If you need to understand the difference between double equals vs triple equals, please read my this article. JavaScript Triple Equals Operator vs Double Equals Operator ( === vs == )

If you have noticed, we compared two different types here in a == 1Here a is an object which is compared to a number. Whenever we compare two different types with a double equal operator, type coercion happens. In type coercion, operator tries to convert both types to a similar type.

In this case, the object will be converted to primitive(number) type by calling the function valueOf if it is available.

valueOf is a builtin function in JavaScript to convert an object to a primitive type, if no primitive value available in the object, valueOf returns the object itself. If valueOf fails then toString is used to convert an object to a string. In toString case, the number on the right-hand side will also be converted to a string for comparison using loose equality(==) operator.

The cool thing is that these methods valueOf and toString can be overwritten.

a.valueOf = function() {
  return 'magic will happen here!';
}

Here we have overwritten the native implementation of the valueOf function with our own. As we know while doing a comparison with double equals operator, it coerces the object type to a primitive type by invoking the valueOf function of the object type.

The Magic Spell


To evaluate (a ==1 && a== 2 && a==3) this statement to true, we need to increment the value of a systematically. To achieve this we have overwritten the valueOf the object as:
valueOf: function () {
    return a.i++;
  }

We have initialized the i with 1 and then incremented it using ++ operator after each use. So our expression (a ==1 && a== 2 && a==3) will be break into following steps:

  • While comparing a == 1; valueOf function of the object will return current value of i(which is 1) and after returning the value will increment it to 2
  • While comparing a == 2; valueOf function of the object will return current value of i(which is now 2) and after returning the value will increment it to 3
  • While comparing a == 3; valueOf function of the object will return current value of i(which is now 3) and after returning the value will be incremented to 4
That is the reason our expression evaluates to true.

Hope this article helped you to understand it. If you have any question please post it in comments.

You may also like to see:

Sunday, November 24, 2013

Best Resources to Learn JavaScript

You may also like to see:

If you want to learn JavaScript and need some good tutorial, Here I listed some nice resources to be refer.

Videos

The best resources are the videos from Douglas Crockford:

Crockford on JavaScript
  1. Volume One: The Early Years
  2. Chapter 2: And Then There Was JavaScript
  3. Act III: Function the Ultimate
  4. Episode IV: The Metamorphosis of Ajax
  5. Part V: The End of All Things
  6. Scene 6: Loopage
The JavaScript Programming Language
  1. The JavaScript Programming Language Part 1
  2. The JavaScript Programming Language Part 2
  3. The JavaScript Programming Language Part3
  4. The JavaScript Programming Language Part4

An Inconvenient API: The Theory of the DOM
  1. Theory of the DOM Part 1
  2. Theory of the DOM Part 2
  3. Theory of the DOM Part 3

Advanced JavaScript
  1. Advanced JavaScript" (1 of 3)
  2. Advanced JavaScript" (2 of 3)
  3. Advanced JavaScript" (3 of 3)

Object Oriented Programming in JavaScript

  1. Part 1 : Object Oriented Programming & JavaScript
  2. Part 2: Object Oriented JavaScript : Classes, Methods and Properties
  3. Part 3: Object Oriented JavaScript : Inheritance, Polymorphism and Encapsulation

Books

  1. JavaScript: The Good Parts by Douglas Crockford
  2. John Resig's book Pro JavaScript Techniques for the more advanced stuff.
  3. Javascript: The Definitive Guide to be of great help
  4. Online book Eloquent JavaScript by Marijn Haverbeke
  5. Essential JavaScript Design Patterns For Beginners by Addy Osmani
  6. Head First HTML5 Programming:Building Web Apps with JavaScript

Learning Sites

  1. Douglas Crockfords writings on JavaScript.
  2. comp.lang.javascript FAQ is quite a nice resource.
  3. Learn appendTo created for learning JavaScript. 
  4. J Resig, Secrets of the javascript ninja
  5. bonsaiden's Javascript Garden quick walk through
  6. Codecademy is interactive - it's pretty sweet

Articles

  1. A re-introduction to JavaScript
  2. Mozilla Developer Center.
  3. Data Types in JavaScript 
  4. JavaScript Best Practices : === vs == 
  5. JavaScript Prototype and Inheritance 
  6. Currying in JavaScript 
  7. How Prototype works?
  8. Is JavaScript's "new" Keyword Considered Harmful?
  9. Pass by reference / value 
  10. This keyword
  11. Teaching JavaScript
  12. "Let's Make a Framework" series on DailyJS.
  13.  Module pattern
  14. Closures

You may also like to see:

Sunday, November 17, 2013

JavaScript : Closures

You may also like to see:



Closure can simply be defined as "In JavaScript, the inner function has the access to all the variables defined outside of that functions."




Here is a simple code with Closures:

function sayHelloToClosures(yourName) {
  var text = 'Hello Closures from' + yourName;
  var sayAlert = function() { alert(text); }
  sayAlert();
}

Here in this example inner function sayAlert() has access to text defined in outer function sayHelloToClosures(), yes that simple concept is Closure.

Closures says the local variables for a function is not de-allocated after the function has returned.

Lets see it another way:

function outerFunction(x) {
  var z = 3;
  return function (y) {
    alert(x + y + z);
  }
}
var innerFunction = outerFunction(2); // innerFunction is now a closures.
innerFunction(10);

Here when we call outerFunction() it sets the values x = 2 and z = 3 and returns a function which takes a parameter y and sum of x, y and z. This retuning function get assigned to innerFunction() on return. In general the variables x and z should be destroyed as outerFunction() has completed its execution and it returned successfully, but closures say it exists for innerFunction() and whenever we call innerFunction() values of x and z will always be the same defined by the outerFunction().

so whenever we call innerFunction() it will add x + z = 5 to y and alert the value.

So when a function is invoked in JavaScript , it creates a new execution context. This context has access to Parent objects with the arguments for the current function get invoked, this execution context also has access to the variables declared outside of its scope.

The simplest example:

var foo = 20;
function myFunction(x) {
  var bar = 6;
  console.log(foo); // will output 20
  console.log(bar); // will output 6
  console.log(x); // will output 10
}
myFunction(10);

As we know JavaScript always uses the Object by reference when it passes as argument, so if we pass objects to a function as closures and call innerFunction() which updates the value of the object, on the next execution of innerFunction() it will have updated value, not the value set by the outerFunction().

Let see the example:

function outerFunction(x) {
  var z = 3;
  return function (y) {
    x=x+1;//x++
    alert(x + y + z);
  }
}
var myVal = new Number(2);
var innerFunction = outerFunction(myVal); // innerFunction is now a closures.
innerFunction(10); //will alert 16
innerFunction(10); //will alert 17
innerFunction(10); //will alert 18


On first execution it will get the Number Object and increment it and set to closures function, but here it also updated the value of the object as the object in JavaScript passed by reference, so updating its value will update the original object, so next time on calling innerFunction() it will get incremented value and so on. So on each time function will get incremented value.

Loops and Closures


How closures can cause issues in loops and how to solve it?

As closure tells you that innerFunction() use the outer or upper scope variables copy(if it is not object), so it may cause some ambiguous functionality in loops, like:

var myFunctions = {};
for (var i = 0; i < 3; i++) {      // let's create 3 functions
    myFunctions[i] = function() {  // and store them in myFunctions
        console.log("My value: " + i); // each should log its value.
    };
}
for (var j = 0; j < 3; j++) {
    myFunctions[j]();              // and now let's run each one to see
}
It will output:
My value: 3
My value: 3
My value: 3
instead of:
My value: 0
My value: 1
My value: 2

why?


because, your myFunctions() is bound to outer-scope variable i which is changed in each loop so after complete loops it value is 3, that is the reason it is printing 3 each time.


So, How to solve it?

Pass variable i as a parameter, instead of using it directly, as we know if we pass a parameter function makes its own local copy of the variable (if it is not object type which pass by reference). So each time function has its own local copy of variable which not get updated by loop iteration. Here is a solution for above issue:
var myFunctions= [];

function createMyFunction(i) {
    return function() { 
           console.log("My value: " + i); 
    };
}

for (var i = 0; i < 3; i++) {
    myFunctions[i] = createMyFunction(i);
}

for (var j = 0; j < 3; j++) {
    myFunctions[j]();    // and now let's run each one to see
}
Now as each time creatMyFunction() will have its own copy so it output the correct result, as expected:
My value: 0
My value: 1
My value: 2
You may also like to see:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,