ReactJS Interview Questions

ReactJs Interview Questions

ReactJs Interview Questions

1. What is Virtual DOM? List down the steps on how does React Handle change to the DOM?

A virtual DOM object is a representation of a DOM object, like a lightweight copy. When you render a JSX element, every single virtual DOM object gets updated. Once the virtual DOM has updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update. Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM.
In summary, here’s what happens when you try to update the DOM in React:

  • The entire virtual DOM gets updated.
  • The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
  • The changed objects, and the changed objects only, get updated on the real DOM.
  • Changes on the real DOM cause the screen to change.

2. Why can’t we call this.setState from render function of React Component?

this.setState updates the state of the component and since the component state is updated, it calls render method on its own. So, if we call this.setState from render method there will be infinite loop.

3. What do you mean by Automatic Binding of context in React?

Automatic binding allows you to pass functions as props, and any this values in the functions’ bodies will automatically refer to whatever they referred to when the function was defined. Consider following code example:

 class Parent extends React.Component {
    inputChanged() {
        //do something using context this
    },
    render() {
        return <Child onChange={this.inputChanged}> 
 } 
 };
class Child extends React.Component({
    render() {
        return <input onChange={this.props.onChange}> 
 } 
};

When input changes in Child component, inputChanged function of Parent component is called.
Considering dynamic context binding in Javascript, inputChanged must have this referring to Child component,
but because of automatic binding by ReactJS, the context refers to where the function is defined hence this
in inputChanged refers to Parent component.

4. What is Stateless Functional Component and how do we define them?

Component written directly as function is called stateless functional component. e.g.

function Card(props) {
    return (
        
{props.name} {props.email} {props.phone}
) }

When a component class has nothing else but only render function and returns JSX then stateless functional component can be used. The props parameter passed to the function is equivalent to {this.props}.

5. What are propTypes and how do we define propTypes for Stateless Functional Component?

If a component class expects the prop to be passed from parent component then propTypes is to be used. It helps in mainly in two purposes:

  • Validation w.r.t. datatype, required etc
  • Documenting the expected properties.

propTypes in components:

var Child = React.createClass({
    propTypes: {
        name: React.PropTypes.string
    },
    render: function() {
        return {this.props.name}
    }
})

propTypes in stateless functional component should be provided as direct function properties:

function Child(props){
    return {this.props.name}
} Child.propTypes = { name: React.PropTypes.string };

Contd…

Credits: http://codecademy.com/

ECMA2016: Array.prototype.includes

One of the features, proposed as part of ECMAScript2016 is, Array.prototype.includes method. This method searches the passed element, inside the array. This was highly requested by developers, as, without that, the solution used was to use, Array.prototype.indexOf. The primary purpose of indexOf is to get the index value of first occurrence of the element and return the index value. To deduce whether the element is present in array or not, the returned value is then compared to some integer, resulting in indirect approach to achieve that.

[10, 20, 30].indexOf(30) >= 0	//returns true

Array.prototype.includes, provides the direct result for element’s presence.

[10, 20, 30].includes(30)		//returns true

This method takes two arguments the element to search and the starting index of the array from where the search begins. It works similar to indexOf in almost all the cases, for example:

[10, 20, 30].includes(30) 	 		//returns true
[10, 20, 30].includes(30, 1) 			// returns true
[10, 20, 30].includes(0)			//return false
[10, 20, 30].includes(30,3) 			//returns false
[10, 20, 30].includes(3,3) 			//returns false

But there are few differences from indexOf, for example:

NaN can be searched using includes

[10, 20, NaN].includes(NaN)	//returns true
[10, 20, NaN].indexOf(NaN)	        //return false

Left out values are treated as undefined by includes

[10,,].includes(undefined)	//returns true
[10,,].indexOf(undefined)	//returns false 

The more logical name for this method could have been “contains” or “has”. But apparently, inside lots of other libraries, the name “contains” as already been defined in Array.prototype so using same name would conflict with existing definition. The “has” method is mostly used with respect to keys (in object and sets) and includes method searches value not the key.

Array.prototype.includes works only with primitive values and not with objects.

[{'a':1},{'a':2},{'a':3}].includes({'a':1}) 	//returns false
[[10],[20],[30]].includes([2]) 			//returns false

This seems little different from String.prototype.includes, proposed in ECMAScript 2015, which takes the search element as string as well and not only as chars. The difference can be justified with their indexOf counterparts i.e. String.prototype.includes is related to Array.prototype.includes in similar way as String.prototype.indexOf to Array.prototype.indexOf.

The more examples can be tried out from the polyfills present here. I have created following pen, using that polyfill.

References:
https://github.com/tc39/Array.prototype.includes/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Similar reads:
http://www.2ality.com/2016/02/array-prototype-includes.html

Multi Level Pie Chart Using D3

multilevelPieChart

Using D3, the MultiLevel pie chart is constructed from a hierarchical data (shown below). This could be achieved by modifying the original example of pie chart in mike’s blog.

The implementation is a 2 step process. In the first step the hierarchical data is stored for each level and in the second step the corresponding pie charts are drawn (by tweaking inner and outer radius) for each level, using the stored data.

To store the data for each level, I have used BFS (Breadth First Search) to traverse the array of objects and then storing the each level’s data in an array, where the index of the array being the level of the in the nested object structure. I modified a little, the solution proposed in this blog to achieve the same.

var setMultiLevelData = function(data) {
    if (data == null)
        return;
    var level = data.length,
        counter = 0,
        index = 0,
        currentLevelData = [],
        queue = [];
    for (var i = 0; i < data.length; i++) {
        queue.push(data[i]);
    };
    while (!queue.length == 0) {
        var node = queue.shift();
        currentLevelData.push(node);
        level--;
        if (node.subData) {
            for (var i = 0; i < node.subData.length; i++) {
                queue.push(node.subData[i]);
                counter++;
            };
        }
        if (level == 0) {
            level = counter;
            counter = 0;            multiLevelData.push(currentLevelData);
            currentLevelData = [];
        }
    }
}

 

Once the data for each level is obtained, the all that remains is drawing multiple pie chart circles iteratively (for each level), one outside the other. I am using the function “drawPieChart” shown in below code (also explained in Mike’s blog) for each level by iterating over the stored multiLevel Data.

 

var drawPieChart = function(_data, index) {
    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
            return d.nodeData.population;
        });
    var arc = d3.svg.arc()
        .outerRadius((index + 1) * pieWidth - 1)
        .innerRadius(index * pieWidth);

    var g = svg.selectAll(".arc" + index).data(pie(_data)).enter().append("g")
        .attr("class", "arc" + index);

    g.append("path").attr("d", arc)
        .style("fill", function(d) {
            return color(d.data.nodeData.age);
        });

    g.append("text").attr("transform", function(d) {
            return "translate(" + arc.centroid(d) + ")";
        })
        .attr("dy", ".35em").style("text-anchor", "middle")
        .text(function(d) {
            return d.data.nodeData.age;
        });
}
//Calling drawPieChart for each level's data
for (var i = 0; i < multiLevelData.length; i++) {
    var _cData = multiLevelData[i];
    drawPieChart(_cData, i);
}

One point to notice in above code is, to have inner radius of the outer pie chart as outer radius of it’s immediate inner pie chart and so on, we used:

var arc = d3.svg.arc()
        .outerRadius((index + 1) * pieWidth - 1)
        .innerRadius(index * pieWidth);
//index is the index of corresponding level in the nested data object. The structure of the data object is shown at the bottom.

Refer following codepen snippet for complete working code:

The hierarchical data looks like:

{
    "nodeData": {
        "age": "5",
        "population": 60
    },
    "subData": [{
        "nodeData": {
            "age": "5",
            "population": 60
        },
        "subData": [{
            "nodeData": {
                "age": "5",
                "population": 60
            }
        }]
    }]
}, {
    "nodeData": {
        "age": "5-35",
        "population": 100
    },
    "subData": [{
        "nodeData": {
            "age": "5-15",
            "population": 60
        },
        "subData": [{
            "nodeData": {
                "age": "5-10",
                "population": 30
            }
        }, {
            "nodeData": {
                "age": "10-15",
                "population": 30
            }
        }]
    }, {
        "nodeData": {
            "age": "15-35",
            "population": 40
        },
        "subData": [{
            "nodeData": {
                "age": "15-25",
                "population": 25
            }
        }, {
            "nodeData": {
                "age": "25-35",
                "population": 15
            }
        }]
    }]
}, {
    "nodeData": {
        "age": "35-65",
        "population": 100
    },
    "subData": [{
        "nodeData": {
            "age": "35-50",
            "population": 75
        },
        "subData": [{
            "nodeData": {
                "age": "35-50",
                "population": 75
            }
        }]
    }, {
        "nodeData": {
            "age": "50-65",
            "population": 25
        },
        "subData": [{
            "nodeData": {
                "age": "50-65",
                "population": 25
            }
        }]
    }]
}, {
    "nodeData": {
        "age": "65",
        "population": 100
    },
    "subData": [{
        "nodeData": {
            "age": "65-75",
            "population": 60
        },
        "subData": [{
            "nodeData": {
                "age": "65-75",
                "population": 60
            }
        }]
    }, {
        "nodeData": {
            "age": "75",
            "population": 40
        },
        "subData": [{
            "nodeData": {
                "age": "75",
                "population": 40
            }
        }]
    }]
}

JS Channel Conference, 2015 – Day 2

[In continuation from previous post i.e.  JS Channel Conference, 2015 – Day 1]

The second day of the conference started with keynote by Yehuda Katz. He spoke about EmberJS and it’s advantages as a framework as well as what’s new, which can be expected in upcoming versions of EmberJS. The core principal of Ember lies in isolation to scale. The framework treats each screen like its own app and this type of isolation helps in scaling big applications (he also pointed that Ember is not meant for small applications or widgets). With the capabilities of glimmer-components in in Ember, he mentioned, how it captures good qualities of ReactJS like
1. components own their data to maintain their state
2. one way data flow by default
3. just refresh the component when something changes
For Ember 2.0, he hinted that transition plan will be feedback oriented and more focussed on convention than configuration.

 

 

Adriaan de Jonge, did a live coding session to compare Angular2.0 with Aurelia framework. During that, he pointed out various loop-holes, in the design of Angular2.0 and demonstrated how the similar loop-holes are handled by a bit flexible framework Aurelia. The session proved to be opening new doors for side-lining from mainstream technologies and try out much more suitable(but relatively new in the industry) frameworks.

 

 

HariKrishnan and Dharampal took the participants for the journey of the evolution of javascript. They started right from the language grammer, which was implemented in 10-days and in the course of 15-20 years, it has reached MVC frameworks like BackboneJS, AngularJS, Ember etc. They also mentioned about how JS frameworks these days are taking good parts from server-side frameworks as well as desktop application architectures. The analogy of JS evolution, they presented as evolution of human beings (right from the unicellular organisms) was funnier but relevant. They put the current status of JS evolution to have reached till Ape’s level and still to evolve to reach humans 🙂

 

 

Post lunch sessions started with hands-on and live-coding workshop by Christian Lilley on ReactJS and FLUX. It was a good follow-up of what was started by Yahuda Katz in the morning as ReactJS, with most of design principals seems alike Ember or vice-versa. Christian re-iterated the core principals behind ReactJS components (like it is for glimmer-component of Ember), additionally he explained about Virtual DOM, structure which is maintained by ReactJS. In his opinion, Virtual DOM is not the key success point of React, as most of people think, but it is the performance advantage one get while rendering the Virtual DOM, via ReactJS. He also explained the surrounding framework FLUX (which is not exactly the framework, but the architecture used by facebook), to best consume power of ReactJS.

 

 

Following that was the panel discussions, again involving major discussions about the current status of the web and the JS framework architectures. There were interesting questions from participants to fuel the best out of panel discussion.

 

 

The conference ended with keynote from Satty Bhens. He talked about micro-services, a relatively new concept of managing big projects.

 

 

Overall the conference was an amazing gathering of technology enthusiasts, with best knowledge awareness from the experts and enough pointers to explore further in the land of opportunities – the Javascript world.

JS Channel Conference, 2015 – Day 1

JS Channel’s conference for the year 2015 was conducted on 17-18th July, 2015 in Bangalore. It was an amazing platform to come across with best brains of current web technology world, hear from them, put across the questions to them and have some fun and learning time with other participants. I am glad that Imaginea gave me and few other colleagues, this opportunity to attend the conference.

The conference spanned for two days. First day started with keynote from Douglas Crockford, father of JSON. His lecture was mainly on finding a suitable idea and plan to upgrade the web in it’s current form. He stressed more on the security loop-holes existing in the web, when accessed with present methods. As a plan to fix some of those, he explained his thoughts on using new URL format, which works with a helper app(in the browser). The URL format uses some strong cryptography (like ECC 521, AFS 256, SHA 3-256) as the unique identifier and the helper app to be a NodeJS (or some other JS based server) message engine. The transition plan, which he shared for the entire web, also seems to be promising.

 

 

The next session was from Charanjit Singh, which was about FRP (Function Reactive Programming) in RxJS. He explained about the power and simplicity of Observables in RxJS, by show-casing Observables features like re-usability, reactivity, iterative over time. Also, there are performance optimizations while using the Observables as there are no memory leaks, no intermediate collections created(while chaining) etc.

 

 

Following that, was Apoorv Saxena‘s session, a deep diving into Javascript performance. He introduced a set of tools like Profiling, FPS meter, rendering and recording tab, page speed insights etc. which can be used to measure the performance of web page. He also presented a number of techniques to solve the performance hits. Some of those solutions are – Pre-fetching DNS registration, load asynch script, avoid complex selectors for styling, reduce number of elements styled, GPU acceleration etc. There was a lot in his session to be demonstrated and explained, but due to limited time, he had to rush through the concepts.

 

 

Followed by Lunch, there was an interesting workshop/live-coding session by Joe Pettersson on “WebGL and ThreeJS”. In his session he demonstrated the entire new world of possibilities in the web, with these frameworks. WebGL and ThreeJS can work combine to represent the 3D objects, in different forms and motions, which in turn opens up the possible opportunities for the web in the domain of virtual reality and the gaming applications.

 

 

Parallel to this session, there was an angularJS workshop going on by Mangesh K, which included building an angularJS based plaform from scratch.

The day ended with some “lightning flash talks” by participants on the random topics. It was interesting to get involved and hear from co-attendees about their ideas and theirs views on different technologies.

[The details of second day are continued in next post – JS Channel Conference, 2015 – Day 2]

Find Correct Event Target Element Using document.elementFromPoint

While creating the position based visual elements i.e. maps/charts on my web page, I often came across the situation where more than one elements are stacked above each other but not in parent-child hierarchy i.e. absolutely positioned. To handle the events such as click, in this case, the target is the topmost element (the element which is added last). And since the elements are not in hierarchy, the bubbling also, will not traverse to bottom elements.  What if we want the event target, to be some other element (based on some selector such as class name) which is lying below.

Here I describe a solution using “document.elementFromPoint”. I have used jQuery for selection purpose.

The key here is, “document.elementFromPoint” returns the currently visible element at given coordinates. So if the current element is not matching the selector, hide it, using display:none and use “document.elementFromPoint” again. It is done it recursively, so that during return from the function, elements are re-shown, to return to previous state.

SOME INTERESTING FACTS ABOUT JAVASCRIPT

Based on my experience with javascript, I came across some interesting facts about javascript. Here is the list of few of those:

  1. To include javascript in a web-page we can have inline javascript within script tag as well as external javascript file provided as src attribute of script tag. What happens when both are used for the same script tag?
<script src="somefile.js">
   function HelloWorld() {
      alert("Hello World");
   }
</script> 

Well in this case the content of the external file will be picked and the inline script will be ignored silently. We can visualise the behavior as the inline content of the script tag is replaced by script in external file.

In case you are familiar with AngularJS, does it ring a bell about ng-include or a directive with a template html.

  1. “noscript” tag

If you want to check whether the browser supports javascript or browser’s support to javascript is turned off by user and in that case if you want to show some message the tag is designed for that purpose.

 

<noscript>
   This site will work only on javascript supporting browser
</noscript>
  1.  Something interesting about typeof:
  • Even though typeof is an operator, so no parenthesis required but there is no problem if parenthesis are used e.g.
typeof(“abc”); //returns string
typeof “abc”; //returns string
  • typeof NaN is number.
  • typeof null is object, because null is considered to be empty object.
  1. 0.1 + 0.2 is not equal to 0.3

It is because the way floating numbers are stored. So never reply on such comparisons. You can use toFixed() to solve this problem.

  1. An array can be truncated using it’s length e.g.

 

var arr = [1, 2, 10, 4, 4];
 //truncate the last 2 values of the array;
 arr.length = 3;
 //is similar to
 arr.splice(3); 
  1. Apply isNaN on different values.
isNaN(“ ”); //false
isNaN(true); //false
isNaN(null); //false
isNaN(“0xf”) //false
isNaN(undefined) //true
isNaN(“hello”) //true

Thumb rule is any value which can be converted to a valid number can not be categorised as NaN. In the cases above “ ” can be converted as 0, true can be converted as 1, null can be converted as 0, “0xf” is valid hexadecimal number so all these values are not treated as NaN whereas undefined and “hello” can’t be converted to any number so these are treated as NaN.

 

  1. parseInt() 2nd parameter:

The second parameter of parseInt function is the radix parameter, which tells the function about the base number format (decimal, octal or hexadecimal). If the radix parameter is not provided and the string begins with “0x”, the radix is hexadecimal i.e. 16 and if the string begins with any other value, the radix is assumed to be decimal i.e. 10

  1. Some interesting outcomes of euality operator (==)
false == " "               //true 
0 == " "                   //true
NaN == NaN                 //false
false == 0                 //true
true == 1                  //true
null == undefined          //true
true == 2                  //false
"5" == 5                   //true