Javascript/Angular Interview Questions
Interview Purpose — Basic Level.
Javascript:
- Data-types, Hoisting, Operators
- Callback
- Promise
- Async/Await
- call() and apply()
- Scope
- Closure
- Arrow Function
- Var, Let, Const
- Rest, Spread operator
- Object Destructure.
Angular:
- Basic building blocks
- Modules
- Components
- Services
- Directives
- Interpolation, Data binding
- Component Interaction(@input, @output, @viewchild)
- Interceptors
- Lifecycle Hooks
- Rxjs/store, State Management
- Content Projection
- Forms
- Singleton Services
- Pipes
- Unit Testing
- Authentication and Authorization
Data-types, Hoisting, Operators:
Data-types:
Javascript engine dynamically set data types according to the variable.
Two types of data types in Javascript.
1. Primitive — String, Number, Boolean, Undefined, BigInt, Symbol, Null
2. Non-primitive — Object, Array
String — Group of characters.
Number — It is a numeric data type. -infinity to +infinity. It has a limit. -2⁵³-1 to -2⁵³-1.
Boolean — True/false. Usually, we use it in conditional statements.
Undefined — The variable that has no value is called undefined.
BigInt — bigInt has no limit. We can use it for large numbers such as complex timestamps. BigInt always has ’n’ in the suffix.
Symbol — The only immutable primitive data type (unchangeable) is a symbol. Usually, we use symbols data-type in the object’s key. Mostly, third-party libraries use this data type to prevent confusion among ids. Ids should be unique. Symbols are unique. So, no one can overwrite or duplicate it.
Null — Null is an empty single value.
Array — [] –A group of data.
Object — { key: value} –A group of data with a key, value pairs.
Hoisting:
Javascript usually moves the variable declarations on top of the scope. It is called hoisting.
Operators:
1. Logical — AND(&&), OR(||), NOT(!)
2. Comparison — equal(==), Equal value(===), not equal(!=), Not equal value(!==), Greater than(>), less than(<), Greater than or equal(>=), Less than or equal(<=)
3. Conditional(Ternary) — Condition ? true : false;
Note:
Console Output:
- [] == {} value is False.
- [] === {} value is False.
- var x; x+’a’ value is ‘undefineda’.
- 1+’a’ value is ‘1a’.
Callback:
The function which has another function as an argument.
Usually, Javascript runs the code sequentially in the top to down order. In some cases, we may need to execute the code after something else happens and also not sequentially.
Callbacks are very useful for asynchronous programming.
Examples: setTimeout(), setInterval(), document.addEventListener()
In above examples, we pass function as an argument.
Promise:
let promise = new Promise(function(resolve, reject) { // executor
});
One of the way to handle asynchronous operations in javascript.
A promise is an object. It has 3 states.
- Pending — Initial state.
- Resolved — Completed
- Rejected— Failed.
Example:
Requesting data from the server.
- Pending — Until we receive data or error response.
- Resolved — Data received.
- Rejected — Error Response.
Callback vs Promise: Initially, callbacks are used for most of asynchronous operations. Obviously, it work. But, it will be complex for multiple asynchronous operations. Nested callbacks are complex to understand and it leads to “Callback Hell”. Promises are good way to use for such cases.
Async/Await:
A function with an async keyword that permits the await keyword within them. Those keywords enable asynchronous behavior.
Call() and Apply():
using call() and apply(), an object can use a method belonging to another object.
call()
takes arguments separately.
apply()
takes arguments as an array.
Scope:
- Block scope(after ES6) — variables declared within the blocks such as for loop if conditions.
- Function scope(local) — variables declared within the functions
- Global scope — variables declared outside the function
Closure:
Closures are function inside another function. It gives you permission to access outer function scope variables on the inner function.
¼function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
Arrow Function:
Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions.
¼x = function(x, y) { return x * y; }
Var, Let, and Const:
- var — function scope
- let and const — block scope. const value is not changeable.
Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function.
Rest and Spread:
The rest operator allows us to call a function with any number of arguments and then access those excess arguments as an array. The rest operator also allows us in destructuring arrays or objects.
The spread operator allows us to expand an iterable array into its individual elements.
Destructure:
Destructuring Assignment is a JavaScript expression that allows unpacking values from arrays, or properties from objects.
¼let a, b;
[a, b] = [10, 20]; //Array Destructure
({a, b} = {a: 1, b: 2}); //Object Destructure
Building Blocks:
Various building blocks in angular.
- Modules
- Components
- Decorators
- Directives
- Templates
- Meta Data
- Pipe
- Data Binding
- Dependency Injection
- Services
Modules:
Modules are the group that contains similar components, directives, services, and pipes.
The angular module is a javascript class that is decorated by @NgModule Decorator. This decorator has a parameter as an object and it has some metadata such as declarations, imports, providers, and bootstrap. Metadata defines the module.
¼@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Components:
Usually, components have 4 files inside them.
- Template file — Defines the view(HTML File)
- Style File — CSS file
- Class File — View related business logic(TS file)
- Unit test File — Testing logic
components are javascript classes like modules and it is decorated by @component decorator. This decorator has some metadata such as selector, template, templateurl, style, styleurl, encapsulation, provider. Metadata defines the components.
¼@Component({
selector: 'app-hero-list',
templateUrl: './hero-list.component.html',
providers: [ HeroService ]
})
export class HeroListComponent{}
Decorators:
A Decorator is a special kind of declaration that can be attached with any class, method, accessor, parameter, or property. Decorators use the @ symbol in prefix.
- Class Decorators — @Component, @NgModule, @Directive
- Method Decorators — @HostListener
- Property Decorators — @Input, @Output
- Parameter Decorators — @Inject
- Accessor Decorators
Directives:
- Attribute Directives — ngClass, ngStyle
- Structural Directives — *ngIf, *ngFor
Attributes directives only change or modify HTML attributes.
Structural directives manipulate the DOM. It removes/adds HTML selectors.
Services:
Services allow you to define code that’s accessible and reusable throughout multiple components. Common use case of service is to communicate with backend web service and send/receive data.
Data Binding:
- Interpolation — It is a one-way data-binding, class file to template file.
- Property Binding — It is a one-way data-binding, class file to template file.
- Event Binding — It is a one-way data-binding, template file to class file.
- Two-way data binding — [(ngmodel)], class file to template file and template file to class file.
Component Interaction:
- @Input() — parent to child data binding.
- @Output() — child to parent data binding.
- @Viewchild(), @viewchildren() — access child components properties from the parent components.
- Template reference variable — Access immediate child’s properties.
- Services
Lifecycle hooks:
- ngOnChanges() — whenever one or more data-bound input properties change.
- ngOnInit() — Called only once after ngOnChanges()
- ngDoCheck() — Called immediately after
ngOnChanges()
on every change detection run - ngAfterContentInit() — Called once after the first
ngDoCheck()
. - ngAfterContentChecked() — Called after
ngAfterContentInit()
and every subsequentngDoCheck()
. - ngAfterViewInit() — Called once after the first
ngAfterContentChecked()
. - ngAfterViewChecked() — Called after the
ngAfterViewInit()
and every subsequentngAfterContentChecked()
. - ngOnDestroy() — Called immediately before Angular destroys the directive or component.
Interceptors:
Interceptors are a unique type of Angular Service that we can implement. Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient. By intercepting the HTTP request, we can modify or change the value of the request.
Content Projection:
We use <ng-content> to project the content.
- Single-slot content projection — A component accepts content from a single source.
- Multi-slot content projection — A component accepts content from multiple sources.
- Conditional content projection — Components that use conditional content projection render content only when specific conditions are met.
Singleton services:
A singleton service is a service for which only one instance exists in an application.
There are two ways to make a service a singleton in Angular:
- Set the
providedIn
property of the@Injectable()
to"root"
. - Include the service in the
AppModule
or in a module that is only imported by theAppModule.
Pipes:
To transform strings to currency amounts, dates, and other data for display.
In-Built Pipes:
DatePipe
: Formats a date value according to locale rules.UpperCasePipe
: Transforms text to all upper case.LowerCasePipe
: Transforms text to all lower case.CurrencyPipe
: Transforms a number to a currency string, formatted according to locale rules.DecimalPipe
: Transforms a number into a string with a decimal point, formatted according to locale rules.PercentPipe
: Transforms a number to a percentage string, formatted according to locale rules.JsonPipe
: Transforms string to JSON.
Dependency Injection:
Dependency injection allows us to inject the dependent component or services into our current class constructor. because of that, we can use all dependencies throughout the class.
Angular Forms:
- Template Driven Forms
- Reactive Forms
Differences:
- Template-driven forms make use of the “FormsModule”, while reactive forms are based on “ReactiveFormsModule”.
- Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous.
- In a template-driven approach, most of the logic is driven from the template, whereas in a reactive-driven approach, the logic resides mainly in the component or typescript code
Unit and Functional Testing:
Unit Testing
This is sometimes also called Isolated testing. It’s the practice of testing small isolated pieces of code. If your test uses some external resource, like the network or a database, it’s not a unit test.
Functional Testing
This is defined as the testing of the complete functionality of an application. i.e. via clicks on a page.
This is also called End to End or E2E testing.
Authentication and Authorization:
Authentication is the process of matching the visitor of a web application with the pre-defined set of user identity in the system(login).
Authorization is the process of giving permission to the user to access certain resources in the system.
Usually, we use auth-guard to authenticate users and inbuild route-guards to authorize users
RouteGuards:
- canActivate()
- canActivateChild()
- canLoad()
- resolve()
- canDeactivate()
State Management:
The NgRx Store is a state management system that enables you to use observables to manage states in an Angular application. The primary advantage to using the NgRx Store is the ability to store all-state in a single tree that is accessible from any part of the application.
Using state management we can decrease unnecessary web service calls and we can increase web application performance.