Sei sulla pagina 1di 9

Angular Interview Questions

1. What is the difference between Angular and AngularJS?

AngularJS

1. AngularJS refers to version 1.x which is in JavaScript (hence JS).


2. AngularJS is a structural framework for dynamic web apps. It can be added to an
HTML page with a <Script> tag.
3. It extends HTML attributes with directives & binds data to HTML with
expressions.
4. Rendering at client side
Angular
1. Angular refers to Angular 2 and above which is in TypeScript (hence no JS)
2. mobile oriented & better in performance.
3. Angular provides more choice for languages. You can use any of the languages
from ES5, ES6, TypeScript or Dart.
4. Angular implements web standards like components, and it provides better
performance.
5.Component based and MVVM.
6. Rendering at server side.

2. What are the main components of Angular 2?


Component:− This can be used to bring the modules together.
Service: − This is used to create components which can be shared across the entire
application.
Modules: − This is used to break up the application into logical pieces of code. Each
piece of code or module is designed to perform a single task.
Templates: − This is used to define the views of an Angular JS application.
Metadata: − This can be used to add more data to an Angular JS class.

3. What are the core differences between Observables and Promises?

A Promise handles a single event when an async operation completes or fails.

Note: There are Promise libraries out there that support cancellation, but ES6
Promise doesn't so far.

An Observable is like a Stream (in many languages) and allows to pass zero or more
events where the callback is called for each event. Often Observable is preferred over
Promise because it provides the features of Promise and more. With Observable it
doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same
API in each case. Observable also has the advantage over Promise to be cancelable.
If the result of an HTTP request to a server or some other expensive async operation
isn't needed anymore, the Subscription of an Observable allows to cancel the
subscription, while a Promise will eventually call the success or failed callback even
when you don't need the notification or the result it provides anymore. Observable
provides operators like map, forEach, reduce, ... similar to an array. There are also
powerful operators like retry(), or replay(), ... that are often quite handy.

Promises vs Observables

o Promises:
i. returns a single value
ii. not cancellable
o Observables:
1. works with multiple values over time
2. cancellable
3. supports map, filter, reduce and similar operators
4. proposed feature for ES 2016
5. use Reactive Extensions (RxJS)
6. an array whose items arrive asynchronously over time

https://stackoverflow.com/questions/36064303/what-are-the-differences-between-
observables-and-promises-in-javascript

4. How do components communicate with each other?

A: Various ways - for example: Input/Output properties, services, View child /


ViewContent.

5. What is an async pipe?

A: An impure pipe that accepts a promise or observable as input and eventually


returns emitted values.

6. What are observables?

A: They provide a declarative way of message passing between publishers and


subscribers in an application. They typically produce one or more values over time,
which are subscribed to by observers. They provide some advantages over promises.

7. What are some advantages to using observables?

A: Observables are cancellable; they come with powerful transformative functions


(especially when using RxJS) to make asynchronous coding easier.

8. Explain the life cycle hooks of Angular 2 application

Angular 2 component/directive has lifecycle events, managed by @angular/core. It


creates the component, renders it, creates and renders its children, processes
changes when its data-bound properties change, and then destroys it before
removing its template from the DOM. Angular provides a set of lifecycle
hooks(special events) which can be tapped into this lifecycle and perform operations
when required. The constructor executes prior to all lifecycle events. Each interface
has a single hook method prefixed with ng. For example, ngOnint interface
has Oninit method that must be implemented in the component.

Some of the events are applicable for both component/directives while few are
specific to components.

 ngOnChanges: Responds when angular sets its data-bound property which


receives the current and previous object values.
 ngOnInit: Initializes the component/directive after first ngOnChange triggers.
This is most frequently used method to retrieve the data for the template from a
back-end service.
 ngDoCheck: Detect and act upon changes occuring outside Angular context. It is
called when every change detection run.
 ngOnDestroy: Cleanup just before Angular destroys the directive/component.
Unsubscribe observables and detach event handlers to avoid memory leaks.

Component-specific hooks:

 ngAfterContentInit: Component content has been initialized


 ngAfterContentChecked: After Angular checks the bindings of the external
content that it projected into its view.
 ngAfterViewInit: After Angular creates the component’s view.
 ngAfterViewChecked: After Angular checks the bindings of the component’s
view.

9. What is lazy loading and How to enable lazy loading in angular 2?

Most of the enterprise application contains various modules for specific business
cases. Bundling whole application code and loading will be huge performance impact
at initial call. Lazy lading enables us to load only the module user is interacting and
keep the rest to be loaded at runtime on demand.

Lazy loading speeds up the application initial load time by splitting the code into
multiple bundles and loading them on demand.

Every Angular application must have one main module say AppModule. The code
should be splitted into various child modules (NgModule) based on the application
business case.
JavaScript Interview Questions
What is Closure?
A closure is a feature in JavaScript where an inner function has access to the
outer (enclosing) function’s variables. Closures is a neat way to deal with
scope issues.
The closure has three scope chains:
it has access to its own scope — variables defined between its curly brackets
it has access to the outer function’s variables
it has access to the global variables

Suppose, you want to count the number of times user clicked a button on a
webpage. For this, you are triggering a function on onclick event of button to update
the count of the variable.
<button onclick="updateClickCount()">click me</button>
Now there could be many approaches like:

1) You could use a global variable, and a function to increase the counter:

var counter = 0;

function updateClickCount() {
++counter;
// do something with counter
}

But, the pitfall is that any script on the page can change the counter, without
calling updateClickCount().

2) Now, You might be thinking of declaring the variable inside the function:

function updateClickCount() {
var counter = 0;
++counter;
// do something with counter
}
But, Hey! Every time updateClickCount() function is called, the counter is set to 1
again.

3) Thinking about Nested functions?


Nested functions have access to the scope "above" them.
In this example, the inner function updateClickCount() has access to the counter
variable in the parent function countWrapper()

function countWrapper() {
var counter = 0;
function updateClickCount() {
++counter;
// do something with counter
}
updateClickCount();
return counter;
}

This could have solved the counter dilemma, if you could reach
the updateClickCount() function from the outside and you also need to find a way to
execute counter = 0 only once not everytime.

4) Closure to the rescue! (self-invoking function):


var updateClickCount=(function(){
var counter=0;

return function(){
++counter;
// do something with counter
}
})();

The self-invoking function only runs once. It sets the counter to zero (0), and returns
a function expression.

This way updateClickCount becomes a function. The "wonderful" part is that it can
access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have


"private" variables.

The counter is protected by the scope of the anonymous function, and can only be
changed using the add function!

More lively example on Closure:


<script>
var updateClickCount=(function(){
var counter=0;

return function(){
++counter;
document.getElementById("spnCount").innerHTML=counter;
}
})();
</script>

<html>
<button onclick="updateClickCount()">click me</button>
<div> you've clicked
<span id="spnCount"> 0 </span> times!
</div>
</html>

Self exercise https://js.do/

Difference between call, apply and bind method in JavaScript?


Call - allows you to pass in arguments one by one.
Example
function Product(name, price) {
this.name = name;
this.price = price;
}

function Food(name, price) {


Product.call(this, name, price);
this.category = 'food';
}

console.log(new Food('cheese', 5).name);


// expected output: "cheese"

Apply -allows you to pass in arguments as an array.


Example
var numbers = [5, 6, 2, 3, 7]; //passed as a array
var max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
Bind returns a new function, allowing you to pass in a this array and any number of
arguments.
Example

Bind () Allows us to Borrow Methods


var pokemon = {
firstname: 'Pika',
lastname: 'Chu ',
getPokeName: function() {
var fullname = this.firstname + ' ' + this.lastname;
return fullname;
}
};

var pokemonName = function() {


console.log(this.getPokeName() + 'I choose you!');
};

var logPokemon = pokemonName.bind(pokemon); // creates new object and binds


pokemon. 'this' of pokemon === pokemon now

logPokemon(); // 'Pika Chu I choose you!'

React JS interview

1. Differentiate between Real DOM and Virtual DOM.

Real DOM Virtual DOM


1. It updates slow. 1. It updates faster.
2. Can directly update HTML. 2. Can’t directly update HTML.
3. Creates a new DOM if element updates. 3. Updates the JSX if element updates.
4. DOM manipulation is very expensive. 4. DOM manipulation is very easy.
5. Too much of memory wastage. 5. No memory wastage.

2.What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the
real DOM. It is a node tree that lists the elements, their attributes and content as
Objects and their properties. React’s render function creates a node tree out of the
React components. It then updates this tree in response to the mutations in the data
model which is caused by various actions done by the user or by the system.
This Virtual DOM works in three simple steps.
1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual
DOM representation.

2. Then the difference between the previous DOM representation and the new

one is calculated.
3. Once the calculations are done, the real DOM will be updated with only the

things that have actually changed.

React vs Angular

TOPIC REACT ANGULAR

1. ARCHITECTURE Only the View of MVC Complete MVC

2. RENDERING Server-side rendering Client-side rendering

3. DOM Uses virtual DOM Uses real DOM

4. DATA BINDING One-way data binding Two-way data binding

5. DEBUGGING Compile time debugging Runtime debugging


6. AUTHOR Facebook Google

Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

i. componentWillMount() – Executed just before rendering takes place both on the client
as well as server-side.
ii. componentDidMount() – Executed on the client side only after the first render.
iii. componentWillReceiveProps() – Invoked as soon as the props are received from the
parent class and before another render is called.
iv. shouldComponentUpdate() – Returns true or false value based on certain conditions. If
you want your component to update, return true else return false. By default, it returns
false.
v. componentWillUpdate() – Called just before rendering takes place in the DOM.
vi. componentDidUpdate() – Called immediately after rendering takes place.
vii. componentWillUnmount() – Called after the component is unmounted from the DOM. It
is used to clear up the memory spaces.

What do you know about controlled and uncontrolled components?

Controlled vs Uncontrolled Components

Controlled Components Uncontrolled Components

1. They do not maintain their own state 1. They maintain their own state

2. Data is controlled by the parent component 2. Data is controlled by the DOM

3. They take in the current values through


props and then notify the changes via 3. Refs are used to get their current values
callbacks

Potrebbero piacerti anche