Front End Developer Interview Question & Answer
Java Script Questions
What is a Closure?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.
The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
Using Closures (Examples)
Among other things, closures are commonly used to give objects data privacy. Data privacy is an essential property that helps us program to an interface, not an implementation. This is an important concept that helps us build more robust software because implementation details are more likely to change in breaking ways than interface contracts.
What is Event Bubbling ?
Event bubbling occurs when a user interacts with a nested element and the event propagates up (“bubbles”) through all of the ancestor elements. When a user clicks the button the event first fires on the button itself, then bubbles up to the parent div, and then up to the ancestor div.
What is Event Delegation?
Event delegation is when you bind an event listener to a parent (or ancestor) element rather than the element(s) you are particularly interested in. When the event is triggered you can check the event target to make sure it was actually the triggered on the element of interest. In general this would be inefficient as you’re now listening to events on the parent, and have to filter out any that aren’t on the particular element of interest. However, event delegation is particularly useful when you have many siblings (or decedents of the ancestor) that you’re interested in.
A simple example is as follows:
<ul>
<li> First list element </li>
<li> Second list element </li>
<li> Third list element </li>
</ul>
While it would be possible to bind to the individual li elements it would require 3 listeners. Using event delegation it is possible to bind one event listener to the ulelement and just check if the event’s target is an li element (very likely in this case...).
What is js map function and what it provide?
The map() method creates a new array with the results of calling a provided function on every element in this array.
As you can see, we have five different types of objects:
- An array
- The elements contained within this array
- A function
- The results returned by this function
- A new array
Looking at it this way, we can start to see what’s going on. map is a function that:
- Takes an array and a function
- Applies the function to every element in the array
- Keeps track of the results of each successive function call
- Returns a new array containing these results
In the physical world, a map is a way of projecting a surface (terrain) onto another (paper). Similarly, the map function “projects” the original array into the new one.
Difference Between Promises & callback
JavaScript Promises use callback functions actually to specify what to do after a Promise has been resolved or rejected, so the two are not fundamentally different. The main idea behind Promises is to take callbacks - especially nested callbacks where you want to perform a series of actions, each one after the resolution of the former- and “flatten out” the code required to do this
Angular JS Questions
What is Scope?
In an AngularJS application, the controller and view share an object called a scope; this object is at the core of its amazing two-way data binding. The controller sets properties on the scope, and the view binds to those properties. AngularJS takes responsibility for keeping the two in sync.
Scope Creation
When your application starts, AngularJS creates the initial scope, which it calls $rootScope. It then "compiles" the document, starting at the root element. As it traverses the DOM, it encounters and processes markers that it calls directives, and some of these (such as ng-controller) request new scopes. After compilation is done, AngularJS will have created a scope tree that mirrors the DOM tree - the $rootScope is bound to the root element and child scopes are bound as the DOM nodes that request them are discovered. Separate scopes are incredibly useful. As seen in the example above, they allow for different parts of the view to cleanly separate their part of the underlying model. Additionally, child scopes can access properties of their parent.
What is Directive?
Directives are a core AngularJS feature. From the framework directives you will use every day like ng-model or ng-repeat, to your own custom directives that allow you to extend the vocabulary of the browser, if you are learning AngularJS, you need to have a solid understanding of Directives.
Scope of the Directives
Scope : False ( Directive uses its parent scope )
When scope is set to “false”, the controller Ctrl1 and directive are using the same scope object. This means any changes to the controller or directive will be in sync
Scope : True ( Directive gets a new scope )
When scope is set to “true”, AngularJS will create a new scope by inheriting parent scope ( usually controller scope, otherwise the application’s rootScope ). Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the Ctrl1 ( the parent scope ) will be reflected in the directive scope.
Scope : { } ( Directive gets a new isolated scope )
This new scope also known as Isolated scope because it is completely detached from its parent scope.
But, can we pass some values from the parent scope to the directives now?
Yes ! Not only that, we might need to handle situations like invoking callbacks in parent scope, two-way binding between parent & directives scope ..etc
scope: {
PropA: "@",
PropB: "=",
PropC: "&"
},
The “@” prefix is a one-way binding between the directive scope and parent scope. It always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}. Since “@” is creating a one-way binding between the parent and directive scope, any changes made in the parent scope will reflect inside the directive scope, but not the other way. “@” prefix is really useful when our directive needs to be initialised with some data from parent scope.
Secondly we have the “=” prefix. It creates a two-way binding between the parent and directive scope. The most important point about “=” prefix is, it’ll always expect the attribute value to be the model name. That means you cannot provide an expression as the value of attribute mapped to “=” prefix. This is useful, when any of our directive scope property to be same as the parent scope property.
Finally, we’re going to talk about the last prefix. The “&” prefix is also known as a method binding. This is used to bind any methods from the parent scope to the directive scope. This will be particularly useful when our directive needs to execute any callbacks in the parent scope. Look at the code to see how attribute value for the “&” prefix to be set.
Difference Between Compile & Link Functions
The concept of compile and link comes from C language, where you first compile the code and then link it to actually execute it. The process is very much similar in AngularJS as well.
Compile: It traverses the DOM and collects all of the directives and deals with transforming the template DOM. The result is a linking function.
Link: The link function deals with linking scope to the DOM.
While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre & post function.
What is the digest cycle?
Angular JS digest cycle is the process behind Angular JS data binding. The process is initiated by making a function call such as $scope.$apply() to kick off a digest cycle.
Angular js has something called two way binding , .i.e whatever changes you make on view are reflected in controller through viewmodel($scope) or vice versa and the way it is implemented internally is using dirty checking or digest . So once you create a variable on $scope and do a watch on it (either explicitly creating a watcher or through using directives like ng-model etc) your are telling angular to watch for changes on it. internally angular keeps a copy of all the variables it is watching . So whenever you make a change on those variable either on view or in js, angular compares it with the old copy to make sure if it has changed or not in digest cycle (or a cycle in which dirty checking is done) .if it has changed it will update it with the new one so that single value is available in both view and controller. But imagine if variable value changes within its watch function every time, it will go on updating it making the watch function go into an infinite loop , to avoid this if the variable value is inconsistent in digest cycles angular will throws error like “variables has exceeded 10 iterations in digest ” to avoid infinite loop.
What is $scope.$apply?
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life-cycle of exception handling, executing watches.
$apply should be used to update the bindings for your models, but that is only required when the update comes from outside Angular. In most cases you don't need to call it manually.
What does transclude do on directives?
Consider a directive called myDirective in an element, and that element is enclosing some other content, let's say:
<div my-directive>
<button>some button</button>
<a href="#">and a link</a>
</div>
If myDirective is using a template, you'll see that the content of <div my-directive> will be replaced by your directive template. So having:
app.directive('myDirective', function(){
return{
template: '<div class="something"> This is my directive content</div>'
}
});
will result in this render:
<div class="something"> This is my directive content</div>
Notice that the content of your original element <div my-directive> will be lost (or better said, replaced). So, say good-bye to these buddies:
<button>some button</button>
<a href="#">and a link</a>
So, what if you want to keep your <button>... and <a href>... in the DOM? You'll need something called transclusion. The concept is pretty simple: Include the content from one place into another. So now your directive will look something like this:
app.directive('myDirective', function(){
return{
transclude: true,
template: '<div class="something" ng-transclude> This is my directive content</div>'
}
});
This would render:
<div class="something"> This is my directive content
<button>some button</button>
<a href="#">and a link</a>
</div>.
In conclusion, you basically use transclude when you want to preserve the contents of an element when you're using a directive.
$http vs $resource
$http is for general purpose AJAX. In most cases this is what you'll be using. With $http you're going to be making GET, POST, DELETE type calls manually and processing the objects they return on your own.
$resource wraps $http for use in RESTful web API scenarios.
Why ui-router over ngRoute?
ui-router is a 3rd-party module and is very powerful. It supports everything the normal ngRoute can do as well as many extra functions.
Here are some common reason ui-router is chosen over ngRoute:
- ui-router allows for nested views and multiple named views. This is very useful with larger app where you may have pages that inherit from other sections.
- ui-router allows for you to have strong-type linking between states based on state names. Change the url in one place will update every link to that state when you build your links with ui-sref. Very useful for larger projects where URLs might change.
- There is also the concept of the decorator which could be used to allow your routes to be dynamically created based on the URL that is trying to be accessed. This could mean that you will not need to specify all of your routes before hand.
- states allow you to map and access different information about different states and you can easily pass information between states via $stateParams.
- You can easily determine if you are in a state or parent of a state to adjust UI element (highlighting the navigation of the current state) within your templates via $state provided by ui-router which you can expose via setting it in $rootScope on run.
In essence, ui-router is ngRouter with more features, under the sheets it is quite different. These additional features are very useful for larger applications.