Showing posts with label programming concept help. Show all posts
Showing posts with label programming concept help. 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:

Thursday, August 14, 2014

Object Oriented Programming & JavaScript

You may also like to see:

JavaScript is an excellent programming language. It is a race cars with so many gears, you just need to know how to handle it. JavaScript supports Object Oriented programming, it will not force it while compiling by throwing errors. But if you know how to write OOP code with JavaScript you can get all the aspects of OOP in JavaScript and believe me its amazing.


JavaScript supports object oriented programming because it supports properties, methods, inheritance through prototyping which are building blocks of OOP. Many developers avoid JavaScript because they are used to off writing OOP code with C#, Java or any other OOP programming languages and they don't know that JavaScript supports OOP and once you start writing code with JavaScript, It gives you encapsulated, re-usable and well managed object oriented code.

JavaScript Object Oriented Programming

Namespace


If you are C# or Java developer you must be familiar with Namespace. Namespace is a logical group of classes containing similar functionality under a unique name.In JavaScript Namespace is an object(namespace) which contains other objects, functions (classes). There is no difference in Namespace object and class object used in JavaScript unlike C# or other OOP languages.

Here is an example of namespace
// global namespace
var OOPJS = OOPJS || {};
Here in above code it is checking if namespace(object) of OOPJS is already existed within applications then use the same object but if it is not created then it create an empty object and initialize our object(namespace). Now this namespace is ready to contain the classes(function) and properties.

You can write your namespace helping function or common variables, functions across the namespace within this namespace.
// Create container called OOPJS.Helpers for common methods

var OOPJS = {};
OOPJS.Helpers = {

    //common variables
    global_variable: "Object Oriented Programming",

    //common methods
    myNamespace: function () {
        return "OOPJS";
    }
}
console.log(OOPJS.Helpers.global_variable);
console.log(OOPJS.Helpers.myNamespace());


See here demo.

Core Classes/Objects

JavaScript has many object (classes) available for use, like in C# there is Math object which contains static function abs(), round() etc, same concepts available in JavaScript. There are objects like Math, Object, Array, Number, Date, JSON, String and others.

See here a math object random() function which generate a random value.
console.log(Math.random());


Like Math there is object Object available which contains  prototype, create() [ECMAScript 5 and above] and many others. Since specified built-in objects have the object referred to by Object.prototype in their prototype chain by default therefore all the properties and functions of Object is inherited to that object. Note all these methods and properties also inherited to namespace too since it is also an object.

So if you want to add a function to all the objects, you can add it to Object using prototype property.

Custom Classes/Objects

The Class
JavaScript contains no separate class declaration like C#, Java or other programming languages. In JavaScript class is a function which contains methods and properties.

Here is a class declaration:
function Person() { } 
//or 
var Student = function(){ }
Class Instance
To create an instance of class we use new keyword with the class name, which instantiate a new fresh instance of class.


Here we declare a class and then created two instance of the class.
function Student() { }
var student1 = new Student();
var student2 = new Student();

In next article we will see classes in details with different access modifiers and other aspects of Object Oriented Programming in JavaScript. Please comment your valuable feedback and suggestion for improvement of this post.

Here is Next Part of this series:

Tuesday, May 6, 2014

Learning AngularJS Part 4: Modular Design of AngularJS Application

Here is Previous Part of this series:

So here I am with the fourth article in the series of Learning AngularJS a guide for beginners. If you have not read the previous articles I recommend you to read in sequence, it will help you in understanding more quickly. In this post we will see the modularity of AngularJS Application.

Before starting the real topic we need to see SPA (Single Page Application).

So what is SPA?

Single Page Application (SPA) or also called Single Page Interface (SPI) is a web application in which we have only one main view which is able to load many small pages on a fly, providing enhanced desktop application like fluid user experience.

Traditional web application gives a blink and load impact when we route from one page to another while in SPA we load a main page on first time then we never post back completely instead we load partial or small HTML pages which make it faster and give it a better user experience.

AngularJS application are Single Page Application, we have a main container page index.html load on first go then we only load the views which we required. To load the view at run-time we need to handle routing which is one of the main SPA concepts.

In the previous post we see the directives, filters and data bindings, so now we will see AngularJS as a complete module and how controller, model views, directives, routes actually fit into this module.

Module (AngularJS Application)


we define module for our application as:


<html ng-app="moduleName" > 

and in JavaScript we create an object for our module as:

var moduleName = angular.module('moduleName', [ ] );

Defining ng-app on html  tag will create a scope for angular application to the HTML and within this HTML scope angular directives , filters and data bindings will work. Since we are working on SPA application so having ng-app on html tag will scope whole application because when this page gets loaded then we not actually loading another page instead we loading partial views which get renders within this main page.

Now we have define the module for our application now we need to add config, controllers, directive, services to our module. Module in actually a container in which we bundle all of our same functionality.

Different module can also interact with each other. If you noticed the empty array passed to the module function with module name is the dependency injection we discussed in our first post. Here we can inject helping module or the module our application depends on. Like for route management we have many already written module available, we just need to pass the module object to our module and then we can use it within our application. We can define multiple modules:

// Define sub modules with no dependencies
angular.module('AccountApp', []);
angular.module('LoginApp', []);

// define main module and inject all other modules as dependencies
angular.module('MainApp', [
    'AccountApp',
    'LoginApp']);

Firstly we set config to our application module in which we can configure routing (we will see in details later). For this we just need to set config in module object.

//we passed ngRoute is an external module for handling routing
var moduleName = angular.module('moduleName', ['ngRoute']);

moduleName.config(function ($routeProvider) {
  $routeProvider

   // route for the home page
   .when('/', {
    templateUrl: 'pages/home.html',
    controller: 'mainController'
  });

}); 

If you noticed here we also passed the controller to the view previously we declare the controller for a view within the view but that is not a recommended way as we said in Model View Controller view should be independent of controller so it must not be dependent on controller, so better way is to pass controller to view on the fly when we routing to view.

Now View has the controller scope so it can access the scope variables of controller. We also need to add controller to our application module, for this we simple need to add controller to main module object.

 // create the controller and inject Angular's $scope
moduleName.controller('mainController', function ($scope) {
    // create a message to display in our view
    $scope.message = 'Hello friend I am Main Controller';
});
and the view for home page will look like:

<!-- home.html -->
<div class="content">
        <h1>First Application</h1>
    <p>{{ message }}</p>
</div>

Here in this simple application we do not required a service or factory but in application when we interacting with APIs then we need to create factory [or services, provider, value]. These four are for same things with some different features. As we might need to get User data from server using AJAX calls and we may need it in five different controllers so instead of repeating the same code for fetching user's data in controllers we move this to User Service and then call this service from different controllers.

We can define factory to our application using:

moduleName.factory('MyService', function () {

    var factory = {};

    factory.getUser = function () {
        //..
    }

    return factory;
});

So lets review a complete cycle of angular application. Our application is a single module. It has configured routes when a particular URL get hit, it will be routed to specific View and Controller is also passed to the view at routing. Now View has the scope access of particular controller. It will call the controller for data. Controller will hit the service for data and service will send back data to controller fetching it from server. Controller pass that data to View and View render it accordingly.

So It was concept of modularity in AngularJS application. If you have any confusions or feedback or If you want to see any particular topic regarding AngularJS in this series please comment below.

Here is Previous Part of this series:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,