JS, Angular and Angular JS Top Interview Questions
1. Closures with respect to returning functions (Practical Usage of Closure in Question 21.)
A closure
is a function having access to the parent scope, even after the parent function
has closed.
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
var counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
// the
counter is now 3
2. This
The
JavaScript
this
keyword
refers to the object it belongs to.3. Inheritance in js
//ES 5 Inheritance
function Parent(g,d){
this.genes= g;
this.dna= d;
}
Parent.prototype.getQualities= function(){
return this.genes+' '+this.dna;
}
function Child(g,d,m){
Parent.call(this,g,d);
this.myQualities= m;
}
Child.prototype= Object.create(Parent.prototype);
console.log(new Parent("parent genes","parent dna").getQualities());
console.log(new Child("child genes","child dna","child
qualitites").getQualities());
// Output
// parent genes parent dna
// child genes child dna
//ES 6 Inheritance
class Parent{
constructor(g,d){
this.genes= g;
this.dna= d;
}
}
Parent.prototype.getQualities= function(){
return this.genes+' '+this.dna;
}
class Child extends Parent{
constructor(g,d,m){
super(g,d);
this.myQualities= m;
}
}
Child.prototype= Object.create(Parent.prototype);
console.log(new Parent("parent genes","parent dna").getQualities());
console.log(new Child("child genes","child dna","child
qualitites").getQualities());
// Output
// parent genes parent dna
// child genes child dna
4. Call() vs bind() vs apply()
apply(),
call(), and bind() all take a this argument as a context to execute a function in, but
call() and apply() invoke the function immediately where bind() returns a
function that we can pass around or store as needed. When invoked, the bound
function will always execute in the context provided as the this argument.
var dog
= {
noise: “arf”,
speak: function () {
console.log(this.noise)
}
};
var cat = {
noise: “meow”
};
dog.speak.call(cat); // meow
noise: “arf”,
speak: function () {
console.log(this.noise)
}
};
var cat = {
noise: “meow”
};
dog.speak.call(cat); // meow
But
that last line is very ugly. Instead we could do:
cat.speak
= dog.speak;
cat.speak(); //meow
cat.speak(); //meow
setTimeout(cat.speak.bind(cat), 1000);
The difference between call() and apply() is
that call() passes all arguments after the first one on to the invoked
function, while apply() takes an array as its second argument and passes the
members of that array as arguments. The following have the same effect.
someFunc.call(thisArg,
1, 2, 3) VS someFunc.apply(thisArg, [1, 2, 3])
Call
function example available in the above inheritance example
5. What does call() do and what is the difference between function.call() and function()
Call() can be used to
access an object properties/methods from a different object.
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
person.fullName.call(person1); // Will return "John Doe"
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
person.fullName.call(person1); // Will return "John Doe"
6. css position property
The
position
property specifies the type of positioning
method used for an element (static, relative, absolute, fixed, or sticky).7. Scope in js
Scope determines the
accessibility (visibility) of variables.
Local Scope
// code
here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
Global Scope
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
// code here can use carName
function myFunction() {
// code here can also use carName
}
8. Scope timeline
The
scope of variables is defined by their position in source code. In order to
resolve variables, JavaScript starts at the innermost scope and searches
outwards until it finds the variable it was looking for.
9. What is ngrx
NgRx is
a framework for building reactive applications in Angular. NgRx provides state
management, isolation of side effects, entity collection management, router
bindings, code generation, and developer tools that enhance developers
experience when building many different types of applications
10. What is rxjs
The Reactive Extensions
for JavaScript (RxJS) is a set of libraries for composing asynchronous and
event-based programs using observable sequences and fluent query operators that
many of you already know by Array#extras in JavaScript. Using RxJS, developers represent
asynchronous data streams with Observables, query asynchronous data streams
using our many operators, and parameterize the concurrency in the asynchronous
data streams using Schedulers. Simply put, RxJS = Observables + Operators +
Schedulers.
11. Given an array with positive and negative numbers. How will u find out the least positive number
let array= [-1,-2,-10,2,4,5,6,7];
let min= 0;
for (let i=1; i<array.length; i++){
if(array[i] > min && min==0 ){
min= array[i];
}
else if(array[i]>0 && array[i]< min){
min= array[i];
}
}
console.log(min);
12.
What is ... In js (spread operator)
The
spread operator allows an iterable to spread or expand individually inside a receiver.
const codeburst = 'CODEBURST'; // Line 1
const characters = [ ...codeburst ]; // Line 2
// [ 'C', 'O', 'D', 'E', 'B', 'U', 'R', 'S', 'T' ]
13. Diff between observable and promise
Promise
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.
Observable
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.
14. Callback vs promise
Callback:
For JavaScript to know when an
asynchronous operation has a result (a result being either returned data or an
error that occurred during the operation), it points to a function that will be
executed once that result is ready. This function is what we call a “callback
function”. Meanwhile, JavaScript continues its normal execution of code. This
is why frameworks that does external calls of different kinds have APIs where
you provide callback functions to be executed later on.
const
request = require(‘request’);
function
handleResponse(error, response, body){
if(error){
// Handle error.
}
else {
// Successful, do something with the result.
}
}
if(error){
// Handle error.
}
else {
// Successful, do something with the result.
}
}
When you have a callback in a
callback, the code tends to be a bit less readable and a bit messy. In some
cases you may have a callback in a callback in a callback or even a callback in
a callback in a callback in a callback. You get the point: it gets messy. This
is the anti-pattern that has been named “callback hell”.
Promise:
A promise is an object that wraps an
asynchronous operation and notifies when it’s done. This sounds exactly like
callbacks, but the important differences are in the usage of Promises. Instead
of providing a callback, a promise has its own methods which you call to tell
the promise what will happen when it is successful or when it fails. The
methods a promise provides are “then(…)” for when a successful result is
available and “catch(…)” for when something went wrong.
The below function returns a promisesomeAsyncOperation(someParams)
.then(function(result){
// Do something with the result
})
.catch(function(error){
// Handle error
});
Instead of nesting callbacks inside callbacks inside callbacks, you chain .then() calls together making it more readable and easier to follow.
15. Will the observable stop executing once we get the response
The observable is a stream of data.
It will keep emitting the values as long as it gets them. We can remove an observable
by using unsubscribe method.
16. What is a directive
Directives are extended HTML
Attributes.
At a high level, directives are
markers on a DOM element (such as an attribute, element name, comment or CSS
class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via
event listeners), or even to transform the DOM element and its children.
17. Can we use both ngIf and ngFor on the same element?
Angular v2 doesn't support more than
one structural directive on the same element.
As a workaround use the <ng-container> element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM.
As a workaround use the <ng-container> element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM.
<ng-container *ngIf="show">
<div *ngFor="let
thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</ng-container>
Ng-container will not be rendered in
the DOM tree, providing an advantage of not disturbing the styles with rules.
18. Tell me something about router module
We use router module to navigate
between different routes. Each routes redirects to the respective component and
renders the respective html dynamically. We use routing extensively in Single
Page Applications.
19. In How many ways can we share data between components
There are four ways to share data
between components In Angular 2+.
Parent to Child: Sharing Data via
@Input
Parent.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-parent', template: ` <app-child [childMessage]="parentMessage"></app-child> `, styleUrls: ['./parent.component.css'] }) export class ParentComponent{ parentMessage = "message from parent" constructor() { } }
Child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Say {{ message }}
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() { }
}
Child to Parent: Sharing Data via ViewChild
ViewChild allows a
one component to be injected into another, giving the parent access to its
attributes and functions. One caveat, however, is that child won’t be
available until after the view has been initialized. This means we need to
implement the AfterViewInit lifecycle hook to receive the data from the
child.
Parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";
@Component({
selector: 'app-parent',
template: `
Message: {{ message }}
<app-child></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child;
constructor() { }
message:string;
ngAfterViewInit() {
this.message = this.child.message
}
}
child.component.ts
import { Component} from '@angular/core';
@Component({
selector: 'app-child',
template: `
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message = 'Hola Mundo!';
constructor() { }
}
Child to Parent: Sharing Data via @output() and EventEmitter
Another way to share data is to emit data from the
child, which can be listed to by the parent. This approach is ideal when you
want to share data changes that occur on things like button clicks, form
entires, and other user events.
In the parent, we create a function to receive the
message and set it equal to the message variable.
In the child, we declare a messageEvent variable with
the Output decorator and set it equal to a new event emitter. Then we create
a function named sendMessage that calls emit on this event with the message
we want to send. Lastly, we create a button to trigger this function.
The parent can now subscribe to this messageEvent that’s
outputted by the child component, then run the receive message function
whenever this event occurs.
Parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hola Mundo!"
@Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
Unrelated Components: Sharing Data via Service
When passing data between components that lack a direct connection, such as siblings, grandchildren, etc,
you should you a shared service.
|
20.
What are http interceptors
Angular’s HTTP interceptors can be
used to pre- and postprocess HTTP requests. Preprocessing happens before
requests are executed. This can be used to change request configurations.
Postprocessing happens once responses have been received. Responses can be
transformed via postprocessing. Global error handling, authentication, loading
animations and many more cross-cutting concerns can be implemented with HTTP
interceptors. The following listing shows how a request (preprocessing) and
response (postprocessing) interceptor can be used.
const module = angular.module('interceptorTest', []);
module.config($httpProvider => {
$httpProvider.interceptors.push(
createInterceptor.bind(null, 'A'),
createInterceptor.bind(null, 'B')
);
});
module.run($http => {
$http.get('https://api.github.com')
.then(response =>; console.log('Response handler'));
});
angular.bootstrap(document.documentElement, [module.name]);
function createInterceptor(id) {
return {
request(config) {
console.log(`Interceptor ${id}: Request`);
return config;
},
response(response) {
console.log(`Interceptor ${id}: Response`);
return response;
}
};
}
// Generates the following output:
// Interceptor A: Request
// Interceptor B: Request
// Interceptor B: Response
// Interceptor A: Response
// Response handler
21. Encapsulation and abstraction (What is the practical usage of
closure?)
Encapsulation is a concept that binds together the data and functions
that manipulate the data, and that keeps both safe from outside interference
and misuse.
Through
the process of abstraction, a programmer hides all but the relevant
data about an object in order to reduce complexity and increase efficiency
const Dog = (name, breed, sound) => {
const bark = () => console.log(sound);
return {
name, breed, bark
};
}
const dog = Dog('Fido', 'Collie', 'Grrrr');
Now if you execute dog.bark(), you will
see Grrrr printed on the console. However, we dont have access to
the sound variable even though our barkmethod is using it. This
is also known as a closure in javascript, and it is how we implement
encapsulation and abstraction. We are binding together the barkmethod
and its data (sound), and we do not grant access to sound outside of
the constructor function scope.
Another Example : (This is also called Revealing Module
Pattern)
const encaps= (function(){
'use strict';
let _private= "Arun";
let _public= "My Public Variable";
function getprivate(){
return _private+" "+_public;
}
return {
_public,
getprivate: getprivate
};
})();
console.log(encaps.getprivate()); //Arun My Public Variable
console.log(encaps._public); //My Public Variable
console.log(encaps._private); //undefined protected by closure
Comments
Post a Comment