Angular and Javascript interview questions and answers

Angular and Javascript interview questions and answers

Table of contents

In this article I would like to share some common interview questions that could help you, once you decide to apply to a new job.

What is Angular?

Angular is a Javascripting binding framework which binds the HTML UI with the model. This way it helps you to reduce your effort on writing those lengthy lines of code for binding. It also helps you to build SPA (single page application) by using the concept of routing. This means there is only one .html page loads once you open a webpage, and after that only the data is transferred through the server communication. Angular also has a lot of other features like HTTP, and DI, lazy loading (load javascript on demand) etc.

Differences between AngularJs and Angular 2+?

AngularJs was a very new concept and had big advantages back in 2010. However, since then Js frameworks involved and AngularJs is no longer supported by the creators - Google. Currently the latest Stable release of Angular is 14. Let's see some differences between the two

Screenshot 2022-07-17 at 15.24.00.png

What are directives in Angular?

According to the original Angular documentation

Change the appearance or behavior of DOM elements and Angular components with attribute directives.

There are three types of directives in Angular:

  1. Structural directives
  2. Attribute directives
  3. Component directives

Structural directives

Structural directives are for example NgIf, NgForOf, NgSwitch. When structural directives are applied they generally are prefixed by an asterisk, , such as ngIf. These type of directives change the DOM layout by adding and removing elements.

Attribute directives

Attribute directives do not add or remove elements of the HTML structure, they change the appearance of the HTML elements.

Component directives

Component directives are special directives, because they have template too. It is like a user control, a customized user control.

Explain the importance of NPM and node_modules

NPM stands for node package manager. NPM is a package manager which makes installations of javascript dependencies easy. NPM is a huge code base where anybody can upload their own ideas and source codes and other developers can use it. Package.json file contains all the references / dependencies for a Javascript project. This way we can install all packages in one go. Using the npm install command, you can download those dependencies and the packages will be placed in node_modules folder.

What is typescript and why do we need it?

Typescript is superset of Javascript. It adds types to JavaScript. You can write your code in typescript, but at the end of the day the code will be converted into JavaScript. Originally JavaScript is not an OOP, but a prototyped language, which is different. Since JavaScript is still getting better and better, it tries to solve the OOP needs, however it is not the same as an OOP language. TypeScript helps us to work in OOP way, which means we can have classes, the classes can implement interfaces and so on. And so as TypeScript is strongly typed, we will have less errors and because we can do OOP with JS our productivity, quality and scalability also increases.

What is a decorator in Angular

Decorator signals for the framework. Decorators defines what kind of Angular class it is. For example if you have a decorator "@Component" then it says it is an Angular component. If you have @NgModule, it signals an Angular module. If you do not have a decorator above a class in Angular, then Angular does not know what is that class for.

Types of bindings in Angular

Angular provides three categories of data binding according to the direction of data flow:

  • From source to view - One-way from data source to view target - interpolation, property, attribute, class, styke - {{expression}} [target]="expression
  • From view to source - Events - One-way from view target to data source - (target)="statement"
  • In a two-way sequence of view to source to view - Two way - [(target)]="expression"

What is SPA

SPA stands for Single page application. SPAs are page applications where the main UI gets loaded once and then the needed UI is loaded on demand.

How do we implement SPA in Angular?

To implement SPAs, we need to use something called Routing. Routing is a simple collection which has two things. URL and the URL related component. So Routing helps you to define the navigation for your Angular app. If you want to move from one screen to other screen and you want to respect SPA that means not loading and refreshing the whole UI routing is needed.

How to implement Routing in Angular?

Very simple example

const routes: Routes = [
  {
    path: 'Items',
    component: ItemsComponent
  },
 {
    path: 'Cars',
    component: CarsComponent
  }
];

You need to have an array of object. This object must contain at least a path, and a related component to it. You have to add this routing to the module as forRoot() and then you have to use the

<router-outlet></router-outlet>

What is lazy-loading in Angular?

Lazy-loading means on demand loading or loading what is essential and necessary. This means that only the current route related javascript modules are downloaded by the browser. This way you can minimize the main.js bundle and make your application loading faster. There is a correlation between the application fastness and the bundle size in JS applications.

How to implement lazy-loading?

An example from Angular docs

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  }
];

what loadChildren callback is doing, is to load only the CustomersModule, when it is neccessary (when the user routes to "/customers". But this also means that you application must have at least two different modules!

What are services?

When you are working with data, you do not want to work them right with your components. You should add another layer to you application - a service. Services are good, because you can share common logic across Angular projects. This can be very useful when you have to modify for example the same GET request, and you have to do it only at one place, instead of every component

What is Dependency Injection

Dependency injection is an application design pattern where rather than creating object instances from within the component, Angular injects it via constructor.

How to implement Dependency Injection?

To implement DI you need something in the @NgModule defined as providers attribute array. This way you can inject the service in your components.

What is the benefit of DI?

DI helps to decouple class dependencies, so that when you add new dependencies you do not change it everywhere.

What is the difference between ng serve and ng build?

"ng serve" builds in memory while "ng build" builds on the hard disk. So when you want to go for production, "ng build" command is used.

What is the difference between "constructor" and "ngOnInit"?

Constructor

Construct is a concept or event of typescript class, while ngOnInit() is a concept of angular. Constructor can be used to initialize class variables and do DI. It should NOT be used to access any UI elements /DOM or angular objects because they will not be available during this event.

ngOnInit()

ngOnInit() event fires after your UI is binded with the component and at this stage the component is initialized, so you have access to DOM elements and you can write any logic of initialisation.

What is Authguard in Angular?

It is a business logic which runs before the navigation happens in an Angular app

{
    path: '/dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard],
    children:[
        {path: '', component: DashboardHomeComponent, canActivate: [AuthGuard]},
        {path: '/jobs', component: JobsComponent, canActivate: [AuthGuard]}
    ]
  },

in the example above you can only go navigate to /dashboard if the Authguard lets you to navigate to it.

What are pipes in Angular?

Pipes are used for data transfer in Angular. Pipes are used to transform strings, currency amounts, dates, and other data for display. Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once. For example, you would use a pipe to show a date as April 15, 1988 rather than the raw string format. Some built-in angular pipes:

  • Datepipe
  • UpperCasepipe
  • LowerCasePipe
  • CurrencyPipe
  • DecimalPipe
  • PercentPipe

example for usage:

<p>The hero's birthday is {{ birthday | date }}</p>

Compare Template-driven forms and Reactive forms

Template-driven

Rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They're straightforward to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.

Reactive forms

Provide direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.

Reactive forms are more scalable than template-driven forms. They provide direct access to the underlying form API, and use synchronous data flow between the view and the data model, which makes creating large-scale forms easier. Reactive forms require less setup for testing, and testing does not require deep understanding of change detection to properly test form updates and validation.

Data flow in reactive forms

  1. The user types a value into the input element, in this case the favorite color Blue.
  2. The form input element emits an "input" event with the latest value.
  3. The control value accessor listening for events on the form input element immediately relays the new value to the FormControl instance.
  4. The FormControl instance emits the new value through the valueChanges observable.
  5. Any subscribers to the valueChanges observable receive the new value.

Data flow in template-driven forms

  1. The user types Blue into the input element.
  2. The input element emits an "input" event with the value Blue.
  3. The control value accessor attached to the input triggers the setValue() method on the FormControl instance.
  4. The FormControl instance emits the new value through the valueChanges observable.
  5. Any subscribers to the valueChanges observable receive the new value.
  6. The control value accessor also calls the NgModel.viewToModelUpdate() method which emits an ngModelChange event.
  7. Because the component template uses two-way data binding for the favoriteColor property, the favoriteColor property in the component is updated to the value emitted by the ngModelChange event (Blue).

And now lets see some NOT Angular related interview questions you can face during an Angular interview 😊

Difference between abstract class an interface

An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces

What is Event-bubbling?

Event bubbling is the method of event propogation in which event travels from innermost element to the outermost parent element.

Like if we have below structure

<section onclick="alert('section')">
   <div onclick="alert('div')">
     <p onclick="alert('paragraph')"> 
        This is paragraph
     </p>
   </div>
</section>

If click event of paragraph invoked it will call click handlers of all in below order

p>div>section

Event bubbling is also known as Event Propagation or Event Delegation

What is Closure in JS?

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.

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() {
    // displayName() is the inner function, a closure
    console.log(name); // use variable declared in the parent function
  }
  displayName();
}
init();

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

What is specificity in CSS?

Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element, which in turn, determines the property value to apply to the element. The specificity algorithm calculates the weight of a CSS selector to determine which rule from competing CSS declarations gets applied to an element.

What is the difference between display none and visibility hidden?

Visibility:hidden means that unlike display:none , the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just is not seen on the page

What is the difference between function expression, and function declaration?

Example of function expression

const getRectArea = function(width, height) {
  return width * height;
};

Example of a function declaration

function calcRectArea(width, height) {
  return width * height;
}

Difference between localStorage and sessionStorage:

localStorage

This read-only interface property provides access to the Document’s local storage object, the stored data is stored across browser sessions. Similar to sessionStorage, except that localStorage data gets cleared when the page session ends – that is when the page is closed. It is cleared when the last “private” tab of a browser is closed (localStorage data for a document loaded in a private browsing or incognito session). Localstorage has four methods:

  1. setItem()
  2. getItem()
  3. removeItem()
  4. clear()

    sessionStorage

    Session Storage objects can be accessed using the sessionStorage read-only property. The difference between sessionStorage and localStorage is that localStorage data does not expire, whereas sessionStorage data is cleared when the page session ends. Closing a window/tab ends the session and clears sessionStorage objects. Sessionstorage has four methods:
  5. setItem()
  6. getItem()
  7. removeItem()
  8. clear()

    What is event loop in javascript?

    JavaScript has a runtime model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java. The event loop is a constantly running process that monitors both the callback queue and the call stack.

If the call stack is not empty, the event loop waits until it is empty and places the next function from the callback queue to the call stack. If the callback queue is empty, nothing will happen:

console.log('Hi!');

setTimeout(() => {
    console.log('Execute immediately.');
}, 0);

console.log('Bye!');

Code language: JavaScript (javascript) In this example, the timeout is 0 second, so the message 'Execute immediately.' should appear before the message 'Bye!'. However, it doesn’t work like that.

The JavaScript engine places the following function call on the callback queue and executes it when the call stack is empty. In other words, the JavaScript engine executes it after the console.log('Bye!').

console.log('Execute immediately.');

Here’s the output:

Hi!
Bye!
Execute immediately.

What are microtasks in JS?

A microtask is a short function which is executed after the function or program which created it exits and only if the JavaScript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's execution environment.

This event loop may be either the browser's main event loop or the event loop driving a web worker. This lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask.

What is the difference between Set and Map in JS?

A Set is an interface in Collection hierarchy that cannot contain duplicate elements whereas a Map is an interface that maps unique keys to values.

What is RxJS?

RxJS is an acronym that full form is Reactive Extension for Javascript. It is a JavaScript library that uses observables to work with reactive programming and deals with asynchronous data calls, callbacks and event-based programs. RxJS has introduced the concept of "reactive programming" to the web. It implements a reactive extension for TypeScript and JavaScript.

What are the most outstanding terms in RxJS?

Following is the list of some most important features of RxJS that are used to handle the concept of RxJS or reactive programming:

Observer

The Observer is an object with next(), error(), and complete() methods, which are called when we have to interact with the observable, i.e., the source interacts for an example button click, Http request, etc.

Observable

In RxJS, an observable function is used to create an observer and attaches it to the source where values are expected. For example, clicks, mouse events from a DOM element or an Http request, etc.

Subscription

The role of subscription comes in the scene when the observable is created. To execute the observable, we need to subscribe to it. It can also be used to cancel the execution.

Operators

Operators are a very important part of RxJS. An operator is a pure function that takes observable input and emits the result in the output form. Input and output both are observable.

Subject

A subject is observable that can multicast, i.e., talk to many observers. Suppose we have a button with an event listener. The function attached to the event using addlistener is called every time the user clicks on the button. Similar functionality goes for the subject too.

Schedulers

A scheduler controls the execution of when the subscription has to start and be notified.

What are subjects in RxJS?

RxJS subject is a special type of observable that allows values to be multicast to many observers. RxJS subjects are multicast instead of plain observables, which are unicast. The subject is the equivalent of an event emitter and the only way of multicast in a value or event to multiple observers. Subject implements both observable and observer interfaces. Every subject is observable so that you can subscribe to it. Every subject is an observer. It means that you have next, error, and complete methods, so you can send values, error subject or completed.

Types of subjects:

  • Subject
  • ReplaySubject
  • BehaviorSubject
  • AsyncSubject

What are the differences between Subject, BehaviorSubject and ReplaySubject in RxJS?

Subject

In the RxJS Subject, Observers who are subscribed later do not obtain the data values emitted before their subscription.

ReplaySubject

In RxJS ReplaySubject, Observers who are subscribed at a later point receives data values issued before their subscription. It operates by using a buffer that holds the values emitted and re-emits them once new Observers are subscribed.

BehaviorSubject

BehaviorSubject functions similar to ReplaySubject but only re-issues the last emitted values. So, it should be used when you are interested in the observer's last/current value.

What is hoisting in javascript?

According to the JS documentation JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared. Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended.

var hoisting

Here we declare then initialize the value of a var after using it. The default initialization of the var is undefined.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num; // Declaration
num = 6; // Initialization
console.log(num); // Returns 6 after the line with initialization is executed.

The same thing happens if we declare and initialize the variable in the same line.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num = 6; // Initialization and declaration.
console.log(num); // Returns 6 after the line with initialization is executed.

If we forget the declaration altogether (and only initialize the value) the variable isn't hoisted. Trying to read the variable before it is initialized results in ReferenceError exception.

console.log(num); // Throws ReferenceError exception - the interpreter doesn't know about `num`.
num = 6; // Initialization

let and const hoisting

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

console.log(num); // Throws ReferenceError exception as the variable value is uninitialized
let num = 6; // Initialization

Note that it is the order in which code is executed that matters, not the order in which it is written in the source file. The code will succeed provided the line that initializes the variable is executed before any line that reads it.

What are Closures in javascript?

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.

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() {
    // displayName() is the inner function, a closure
    console.log(name); // use variable declared in the parent function
  }
  displayName();
}
init();

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

What is strict mode in JS?

Strict mode makes it easier to write "secure" JavaScript. Strict mode changes previously accepted "bad syntax" into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties. In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error. Using a variable, without declaring it, is not allowed:

"use strict";
x = 3.14;                // This will cause an error

What is difference between var and let?

let was introduced in es6 has block scope does not get hoisted

var is there in JS from the beginning has function scope - does not respect blocks, only function blocks gets hoisted at the top of it's function

example code

let x = function(){
    if( true ) {
      var v = 2
      let l = 1
    }
    console.log(v)
    console.log(l)
}
x()

You will get ReferenceError on l , but not on v.

What is the difference between null and undefined?

They both represent empty value. The difference is when you define a variable, but not assign a value to it, it automatically gets a placeholder for it by JS. Null - you are doing it. typeOf(undefined) is undefined typeOf(null) is object

What is the prototypal inheritance?

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain. It is possible to mutate any member of the prototype chain or even swap out the prototype at runtime, so concepts like static dispatching do not exist in JavaScript. Prototypal Inheritance: A prototype is a working object instance. Objects inherit directly from other objects.

What is WeakMap in ES6?

The WeakMap is same as ?ap where it is a collection of key/value pairs, however in WeakMap, the keys are objects and the values can be arbitrary values.

What is Babel?

Babel is the one of the most poplular JS transpier and becomes the industry standard. It allows us to write ES6 and convert it back in pre-ES6 JS, that browsers support.

What is WeakSet?

WeakSet object lets you store weakly held objects in a collection.

What is the use of pop() method?

pop() method is used to remove the last element from an array and returns that element.

What are iterators in ES6?

An iterator accesses the items from a collection one at a time, while keeping track of its current position within that sequence. It provides next() method which returns the next item in the sequence. This method returns an object with two properties: done and value.

Can you explain the spread operator in ES6?

It provides a new way to manipulate array and objects in ES6. A spread operator is represented by ... following the variable name

let a = [6,7,8,9]
let b = [1,2,3,...a,10]

b is equal to [1,2,3,6,7,8,9,10]

What is Encapsulation?

The notion of encapsulation (or OOP Encapsulation) refers to the bundling of data, along with the methods that operate on that data, into a single unit. A class is a program-code-template that allows developers to create an object that has both variables (data) and behaviors (functions or methods). A class is an example of encapsulation in computer science in that it consists of data and methods that have been bundled into a single unit.

What is inheritance?

Inheritance is one of the core concepts of object-oriented programming (OOP) languages. It is a mechanism where you can to derive a class from another class for a hierarchy of classes that share a set of attributes and methods.

What is Polymorphism?

Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

What is the difference between an abstract class and an interface?

Interface and abstract class both are special types of classes that contain only the methods declaration and not their implementation. But the interface is entirely different from an abstract class. The main difference between the two is that, when an interface is implemented, the subclass must define all its methods and provide its implementation. Whereas when an abstract class is inherited, the subclass does not need to provide the definition of its abstract method, until and unless the subclass is using it. Also, an abstract class can contain abstract methods as well as non-abstract methods.

Did you find this article valuable?

Support Renátó Bogár by becoming a sponsor. Any amount is appreciated!