Categories
AJAX Angular CSS CSS3 HTML HTML5 JavaScript jQuery NodeJS UI

UI Architect Interview Questions and Answers

what is tail call optimization ?
TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space.

Recursive function approach has a problem. It builds up a call stack of size O(n), which makes our total memory cost O(n). This makes it vulnerable to a stack overflow error, where the call stack gets too big and runs out of space. Tail Cost Optimization (TCO) Scheme. Where it can optimize recursive functions to avoid building up a tall call stack and hence saves the memory cost.

what is Map, Set, WeakMap and WeakSet ?
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

A Set is a collection of values, where each value may occur only once means it will contain unique set of keys. 

WeakSet is a special kind of Set that does not prevent JavaScript from removing its items from memory. WeakMap is the same thing for Map.
WeakMap does not support iteration and methods keys(), values(), entries(), so there’s no way to get all keys or values from it.

Map – is a collection of keyed values.

The differences from a regular Object:

Any keys, objects can be keys.
Iterates in the insertion order.
Additional convenient methods, the size property.
Set – is a collection of unique values.

Unlike an array, does not allow to reorder elements.
Keeps the insertion order.
Collections that allow garbage-collection:

WeakMap – a variant of Map that allows only objects as keys and removes them once they become inaccessible by other means.

It does not support operations on the structure as a whole: no size, no clear(), no iterations.
WeakSet – is a variant of Set that only stores objects and removes them once they become inaccessible by other means.

Also does not support size/clear() and iterations.
WeakMap and WeakSet are used as “secondary” data structures in addition to the “main” object storage. Once the object is removed from the main storage, if it is only found in the WeakMap/WeakSet, it will be cleaned up automatically.

how to do peer to peer communication in ANgular ?

what is directive & components in angular ?

if loop functions are removed from script, how can you achieve same functionality ?

how to drop both data and collection in mongodb ?

what is generic types in Typescript ? advantages ?

how to define custom types in Typescript ?

how to capture the process specific exceptions in NodeJS ?

how do you print name of file currently executing in NodeJS ?

how to use custom pipes in Angular ? can you pass additional parameters in custom pipes ?

what is the max data can be stored in a mongodb document ?

how to acheieve variable length documents in mongodb ?

how do you set autoincrement field in mongodb ?

what is the difference between throttling & debouncing ?
Throttling enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 100 milliseconds.”
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 100 milliseconds have passed without it being called.”

what is event bubbling ? how to stop ?
what is digest cycle in angularJS ?
how to stop propgation ?
what is interpolation ? how does it work ?
what is shadow dom ?
what is webworker ?
how to cache the page/data in HTML 5 ?
how to give offline view expereince in HTML5 ?
what is lazyloadng? how it works ?
what are pure / impure pipes ?
what is redux ? how does it work ?
unit testing code coverage how to check ?
what tool used for unit test ?
streaming , how does it work ?
any custom video/audio player developed?
how does cache works in HTML5 ?
what is method chaining ?
difference between canvas vs SVG ?
what is XSS and how to avoid it ?

difference between Responsive and Adaptive design ?
diff b/w flexbar & grid designs ?
what is cors ? how to allow ?
symmetric & asymetric keys ?
scope usage in OAuth token ?
explain component lifecycle
how to use service in Angular ?
what is event emitters ?
latest ECMA version ?
INPUT & OUTPUT variables usage in Angular
explain Digest Lifecycle in Angular ?
difference between Angular 1.x & Angular 2.x
what is SASS & SCSS ?
what is ViewChild ? OR ViewCildren ?

Explain the following :

Directives,
decorators,
Services,
Modules,
Data Binding,
Components,
Filters,
DOM ,
Events ,
Routing,
Dependency injection.

Categories
Agile AJAX Angular CSS CSS3 HTML HTML5 JavaScript jQuery NodeJS UI

Javascript / UI / Angular Architect Questions and Answers

1.Difference between var let and const. ?

a. Var is hoisted in JS, let and const are not hoisted.

b. Let, const are block level, var is function level The candidate has to tell at least one of these apart from any other difference he tells.

2. What is a closure and how does it work

a. A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.

3. What is a JavaScript class

a. ES 6 standard introduced classes in JS, which internally use the prototypal approach to implement Class .

4. How does JS implement inheritance

a. JS uses prototypal inheritance in which objects inherit properties from other objects (or) JS uses prototypes to implement inheritance

5. What is the difference between == and === in JS

a. == checks only for the value, where === checks for both value and data type

6. What is the use of hasOwnProperty method in JS

a. This method returns true, only when the passed property is present directly on the object.

7. Explain call, apply and bind

a. Call and apply are used to invoke a method, by setting the context of ‘this’ keyword. Call takes comma separated individual parameters, and apply takes array of parameters as arguments

b. Bind method does the same operation as call and apply, but returns a new function definition instead of invoking the method

8. What is ‘arguments’ keyword in JS

a. Arguments is a special property in every function, that holds all the parameters passed to that function. Its an array-like object.

9. What is arrow function

a. Arrow function is introduced in ES 6 standard of JS, and does implicit binding of this property.

10. What are benefits of TypeScript

a. * TS provides type safety for the variables

Skills checked:

JS core – Intermediate / Advanced

  1. What is a closure and how it works in JavaScript
  2. What is a ‘hosting’ , How this works in JavaScript ?
  3. call, apply and bind with example
  4. Event bubbling and Event capturing
  5. event delegation
  6. prototypical inheritance / prototypical chain
  7. strict mode and usual mode
  8. What is EventLoop?

ECMA

  1. Difference between var, let and const?
  2. What is a promise and how it works?
  3. What is a arrow function and its difference from function syntax?
  4. Generator and how it works
  5. JS modules, export and export default
  6. async/await

Angular – Intermediate / Advanced

  1. Virtual DOM concept.
  2. Subscribe, Observables and Promises.
  3. Different ways of data bindings.
  4. Sequence of Angular Lifecycle Hooks
  5. Routing
  6. Reactive Forms.

React JS and Redux – Novice / Intermediate

  1. Virtual DOM concept.
  2. Explain lifecycle of React component.
  3. Difference between state and props.
  4. Redux
  5. Role of reducer

HTML – Novice / Intermediate

  1. What is a Doctype?
  2. quirks mode and standart mode
  3. new features in html5
  4. Html storage Localstorage and sessionstorage

CSS – Novice

  1. Difference between adaptive and responsive design?
  2. What is a repaint and reflow?
  3. Media query.
  4. Layout Methodology.
  5. How browser search selector?

Networking – Intermediate

  1. What is REST?
  2. REST principles.
  3. Difference between POST and PUT requests

Design Patterns – Advanced

  1. Factory Patterns
  2. Singleton Patterns

Unit testing

  1. TDD/BDD
  2. jasmine/karma

Processes

  1. GIT
  2. Code review process and tools
  3. CI/CD
  4. SOLID
  5. SCRUM
  6. Webpack
  7. IDE

Categories
Angular JavaScript NodeJS UI

BARCO – MEAN Architect – NodeJS developer Interview Questions and Answer

BARCO – MEAN Architect – NodeJS developer Interview Questions and Answer

what is tail call optimization ?
TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space.

Recursive function approach has a problem. It builds up a call stack of size O(n), which makes our total memory cost O(n). This makes it vulnerable to a stack overflow error, where the call stack gets too big and runs out of space. Tail Cost Optimization (TCO) Scheme. Where it can optimize recursive functions to avoid building up a tall call stack and hence saves the memory cost.

what is Map, Set, WeakMap and WeakSet ?
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

A Set is a collection of values, where each value may occur only once means it will contain unique set of keys. 

WeakSet is a special kind of Set that does not prevent JavaScript from removing its items from memory. WeakMap is the same thing for Map.
WeakMap does not support iteration and methods keys(), values(), entries(), so there’s no way to get all keys or values from it.

Map – is a collection of keyed values.

The differences from a regular Object:

Any keys, objects can be keys.
Iterates in the insertion order.
Additional convenient methods, the size property.
Set – is a collection of unique values.

Unlike an array, does not allow to reorder elements.
Keeps the insertion order.
Collections that allow garbage-collection:

WeakMap – a variant of Map that allows only objects as keys and removes them once they become inaccessible by other means.

It does not support operations on the structure as a whole: no size, no clear(), no iterations.
WeakSet – is a variant of Set that only stores objects and removes them once they become inaccessible by other means.

Also does not support size/clear() and iterations.
WeakMap and WeakSet are used as “secondary” data structures in addition to the “main” object storage. Once the object is removed from the main storage, if it is only found in the WeakMap/WeakSet, it will be cleaned up automatically.

how to do peer to peer communication in ANgular ?

what is directive & components in angular ?

if loop functions are removed from script, how can you achieve same functionality ?

how to drop both data and collection in mongodb ?

what is generic types in Typescript ? advantages ?

how to define custom types in Typescript ?

how to capture the process specific exceptions in NodeJS ?

how do you print name of file currently executing in NodeJS ?

how to use custom pipes in Angular ? can you pass additional parameters in custom pipes ?

what is the max data can be stored in a mongodb document ?

how to achieve variable length documents in mongodb ?

how do you set auto increment field in mongodb ?

Categories
Angular JavaScript UI

Infosys – UI Developer / Angular Developer Interview Questions

UI Developer / Angular Developer interview questions asked in INFOSYS :

what is closure property ?
Difference between Var and Let ?
AngularJS directives ?
what is Observable vs Promises with difference ?
what is Polyfills ?
What is webworker ? have you used it in your project ?
what is HTML APIs ? local storage, session storage, GeoLocation, Drag&Drop WebWorker ?
how does web page gets displayed in the browser ? what happens in the background ?
how do you remove dulicates from array ?
3 types :
* using forloop , get unique values from one array and pass it to second array using indexof function
* set operator in ECMA script 6 will give unique values
* for let i of array { object[i] = true }

how do you share data between components ?
* parent to child using @input decorator
* from child to parent @output decorator along with event emitter
* between components use services to share the data
* local & session storage

what is NaN ? where do you encounter ?
what is the difference between JavaScript , Type Script and ECMA Script ?
What is the different AngularJS and Angular ?

Categories
Angular JavaScript UI

Oracle Angular Interview Questions

Oracle Angular Interview Questions listed here :

what is web worker? how it works ?
HTML 5 APIs ?
explain transform vs transition difference in css ?
what new features in HTML5 ?
explain Observables vs Promises differences ?
Pseudo classes and Pseudo elements differences explain ?
what is the significance of DELETE keyword in JS ?
explain closure property ?
what are child selectors ? explain with example

what is digest cycle explain ?
what are the differences between Emit vs Broadcast ?
How to prototype inheritance ?
explain == vs === difference ?
explain closure property ?
Apply and Call method diff in Angular ?

Categories
Angular JavaScript UI

Angular Interview Questions Quiz with Key Answers

Angular Quiz :

1) Which command enables a number of optimizations that drastically reduces the size of the project?
A. ng build
B. ng build –optimize
C. ng build –prod
D. ng build –bundle

2) What Is an Angular Service?

A. It is the root AppComponent that Angular creates and inserts into the “index.html” host web page.
B. It is a tool to initialize, develop, scaffold and maintain Angular applications.
C. It is a class that encapsulates some HTTP methods and provides it result as a service for across your application.
D. It is a type of injection and attackers inject your web applications using the client side scripts and malicious code into web pages.

3) Which structural directive used to repeat a given HTML template once for each value in an array, each time passing it the array value as context for string interpolation or binding?
A. ngIf
B. ngFor
C. ngSwitch
D. ngRepeat

4) The format for defining Property Binding in a template is
A.
B.
C.
D.

5) Which is a tool to initialize, develop, scaffold and maintain Angular applications?
A. Service Worker
B. Angular CLI
C. Angular Bootstrap
D. Angular App

6) What are the main building blocks of Components?
A. Template
B. Class
C. Metadata
D. All of the above

7) Which is enables navigation from one view to the next as users perform application tasks?
A. Navigator
B. Router
C. Direction-finder
D. Path-finder

8) Which allows us to easily achieve data binding in two directions: from the view to the model and from the model to the view.
A. {{ngModel}}
B. [ngMode]
C. ([ngModel])
D. [(ngModel)]

9) The first animation-specific function that we use is _________. This allows us to define the name of the animation in the first parameter, and then an array of other animation-specific functions in the next.
A. transition()
B. animatronics ()
C. trigger()
D. animation()

10) Which is an animation-specific function that is designed to be used inside of Angular’s animation DSL language. If this information is new, please navigate to the component animations metadata page to gain a better understanding of how animations in Angular are used?
A. state()
B. transition()
C. animatronics ()
D. trigger()

11) What is Bootstrap?
A. Use to declare the application components.
B. Every application must import BrowserModule to run the app in a browser.
C. There are none to start.
D. This is a root AppComponent that Angular creates and inserts into the index.html host web page.

12) Which is the correct format for defining interpolation in a template?
A.
B.
C.
D.

13) Which allows you to define properties in a component class, and communicate these properties to and from the template?
A. Interpolation
B. Class Binding
C. Event Binding
D. Two way binding

14) List the types of Binding in Angular from the list :
A. Interpolation
B. Property Binding
C. Two-Way Data Binding
D. Event Binding

A. A,B,C
B. B,C,D
C. A,C,D
D. A,B,C,D

15) In some situation we want data values as boolean or other than string then we should go for _________ binding
A. Interpolation
B. Property
C. Template
D. Both A and B

16) True or False: The styles specified in @Component metadata apply only within the template of that component.
A. TRUE
B. FALSE

17) True or False: Component templates are not always fixed. An application may need to load new components at runtime.
A. TRUE
B. FALSE

18) The Bootstrap is the _______ AppComponent that Angular creates and inserts into the “index.html” host web page.
A. child
B. additional
C. root
D. module

19) Which defines the Layout of the View and defines what is rendered on the page. Without this, there is nothing for Angular to render to the DOM?
A. Selector
B. Class
C. Template
D. Style

20) ___________ configure the injector and the compiler and help organize related things together.
A. @NgModule
B. @Component
C. @Directive
D. @Module

Answers :

1)  C. ng build –prod
2)  C. It is a class that encapsulates some HTTP methods and provides it result as a service for across your application.
3) B. ngFor
4) B. [value]=”username”
5) B. Angular CLI
6) D.  All of the above
7) B. Router
8)  D.  [(ngModel)]
9)  C. trigger()
10) B. transition()
11) D. This is a root AppComponent that Angular creates and inserts into the index.html host web page.
12)  D. value={{username}}
13)  A. Interpolation
14)  B. B,C,D
15)  B. Property
16)  A. TRUE
17)  A. TRUE
18)  C. root
19)  C. Template
20) A. @NgModule

Categories
Angular JavaScript UI

SAP UI Architect Interview Questions – Angular

SAP UI Architect Interview Questions – Angular

1) XSS attack types?
XSS is a web-based attack performed on vulnerable web applications.
In XSS attacks, the victim is the user and not the application.
In XSS attacks, malicious content is delivered to users using JavaScript.

An XSS vulnerability arises when web applications take data from users and dynamically include it in web pages without first properly validating the data. XSS vulnerabilities allow an attacker to execute arbitrary commands and display arbitrary content in a victim user’s browser. A successful XSS attack leads to an attacker controlling the victim’s browser or account on the vulnerable web application.

There are 3 types of XSS ( 2 server side and 1 client side)

Stored XSS (Persistent XSS)
An attacker uses Stored XSS to inject malicious content, most often JavaScript code, into the target application. If there is no input validation, this malicious code is permanently stored (persisted) by the target application, like in a database.
When a victim opens the affected web page in a browser, the XSS attack payload is served to the victim’s browser as part of the HTML code. This means that victims will end up executing the malicious script once the page is viewed in their browser.

Reflected XSS (Non-persistent XSS)
the attacker’s payload has to be a part of the request that is sent to the web server. It is then reflected back in such a way that the HTTP response includes the payload from the HTTP request. Attackers use malicious links, phishing emails, and other social engineering techniques to lure the victim into making a request to the server. The reflected XSS payload is then executed in the user’s browser.

DOM-based XSS
DOM-based XSS is an advanced XSS attack. It is possible if the web application’s client-side scripts write data provided by the user to the Document Object Model (DOM). The data is subsequently read from the DOM by the web application and outputted to the browser.A DOM-based XSS attack is often a client-side attack and the malicious payload is never sent to the server. This makes it even more difficult to detect for Web Application Firewalls (WAFs) and security engineers who analyze server logs because they will never even see the attack.

2) CORS , how to manage? How to secure the requests? explain Proxy concept
A website from one origin cannot access resources from a foreign origin, and to make that possible, CORS comes into the picture. In short, CORS is standard of sharing cross-origin resources. This allows restricted resources on a web page to be requested from another domain.

A proxy, in general, is a server or a service which can introduce additional layers in our communication to obfuscate or modify content, based on the configuration. In the context of web development, our primary goal to use a proxy is to avoid CORS (Cross-Origin Resource Sharing) “issues” which occur because the browsers enforce Same-Origin Policy to protect the users from XSS among several other types of attacks.

3) What is Virtual polymorphism ?
Static polymorphism is polymorphism that occurs at compile time, and dynamic polymorphism is polymorphism that occurs at runtime (during application execution).
Object-oriented programming languages, allows you to implement multiple methods within the same class that use the same name but a different set of parameters. That is called method overloading and represents a static form of polymorphism.

Within an inheritance hierarchy, a subclass can override a method of its superclass. That enables the developer of the subclass to customize or completely replace the behavior of that method.
It also creates a form of polymorphism. Both methods, implemented by the super- and subclass, share the same name and parameters but provide different functionality.

4) Sql query for each products total price sold in a quarter ?
Here is the simple queries to get total price of each product sold in a quarter

select ProductID, count(*) x ProductPrice as TotalPriceSales from Orders where DATE BETWEEN '01/01/2019 00:00:00' and '03/30/2019 11:59:59'  group by ProductID
select ProductID, sum(ProductPrice) as TotalPriceSales from Orders where DATE BETWEEN '01/01/2019 00:00:00' and '03/30/2019 11:59:59'  group by ProductID

5) Factorial number function use any previous cached number data if exist ?

Memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. Memoizing in simple terms means memorizing or storing in memory. A memoized function is usually faster because if the function is called subsequently with the previous value(s), then instead of executing the function, we would be fetching the result from the cache. So in this case we can use Memoization technic as that return values are the same for same inputs every time

let cache = [1];
function factMemoize(key) {
if (!cache[key]) {
cache[key] = key * factMemoize(key – 1)
} else { // just to demo cache:
console.log(“cache hit:”, key)
}
return cache[key]
}

// only hits cache at the end
console.log(“6! = “, factMemoize(6))

// second call benefits from cache:
console.log(“8! = “, factMemoize(8))

6) Types of protocols & requests which can be sent through browser ?

HTTP, HTTPS, FILE, and FTP protocols based requests can be sent through browser.

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.
Following HTTP requests are supported by browser :

GET
The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

HEAD
The HEAD method asks for a response identical to that of a GET request, but without the response body.

POST
The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

PUT
The PUT method replaces all current representations of the target resource with the request payload.

DELETE
The DELETE method deletes the specified resource.

CONNECT
The CONNECT method establishes a tunnel to the server identified by the target resource.

OPTIONS
The OPTIONS method is used to describe the communication options for the target resource.

TRACE
The TRACE method performs a message loop-back test along the path to the target resource.

PATCH
The PATCH method is used to apply partial modifications to a resource.

7) What is promise? Advantages?
JavaScript promises let your async call return a value like synchronous function, that value is an object that promises success or failure value.
ex:
get(“/someURL”)
.then(“some processing”)
.catch(e => console.log(“Error 1”))

Advantages :
Better error handling
Reduced coupling
Improved readability
Better definition of control flow of asynchronous logic

The promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.

8) what is Multi tenancy?
Multi-tenancy is an architecture in which a single instance of a software application serves multiple customers. Each customer is called a tenant. Tenants may be given the ability to customize some parts of the application, such as color of the user interface (UI) or business rules, but they cannot customize the application’s code.

9) how do you improve the Performance of webpage?
there are multiple ways to improve the performance of webpage ,

Reduce / Optimize image size
Reduce the number of HTTP requests
Load JavaScript asynchronously
Clean up the HTML/JS/CSS Document
Minify CSS, JS and HTML
Enable Prefetching like Link Prefetching , DNS Prefetching , Prerendering etc..
Increase Speed With a CDN and Caching
Enable compression / Implement Gzip Compression
Lazy Load of content/images
Combine the files ex: CSS sprites

10) Request/response taking too much time? How to keep alive the request ?
HTTP persistent connection, also called HTTP keep-alive, or HTTP connection reuse, is the idea of using a single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new connection for every single request/response pair.
Enabling the keep-alive header allows you to serve all web page resources over a single connection. Keep-alive also reduces both CPU and memory usage on your server.

11) In DB, 2 queries same record update? How to manage? How to intimate the second request to update itself?
Locking performed within the DB server itself to manage contention for table contents by multiple sessions. This type of locking is internal because it is performed entirely by the server and involves no other programs.

Row-Level Locking

MySQL uses row-level locking for InnoDB tables to support simultaneous write access by multiple sessions, making them suitable for multi-user, highly concurrent, and OLTP applications.

Table-Level Locking

MySQL uses table-level locking for MyISAM, MEMORY, and MERGE tables, permitting only one session to update those tables at a time. This locking level makes these storage engines more suitable for read-only, read-mostly, or single-user applications.

Using Transactions – commit queries

Here it is to use a transactional database (so there’s no clashes)

Tentative Allocation
To do a tentative allocation of the data to you that expires after some length of time (e.g., 10 minutes for kiosks) that gives you enough time to pay. If the (customer-visible) transaction falls through or times out, the data allocation can be released back into the pool.

12) Lot of requests , how to manage?
There are three main strategies for handling the load:

The site can invest in a single huge machine with lots of processing power, memory, disk space and redundancy.
The site can distribute the load across a number of machines. [like load balancer ]
The site can use some combination of the first two options.

13) Same application, for 2 different companies but for all users, request to come, how to manage?
The incoming requests for pages are spread across all of the machines in one of two ways:

The Domain Name Server (DNS) for the site can distribute the load. DNS is an Internet service that translates domain names into IP addresses. Each time a request is made for the Web server, DNS rotates through the available IP addresses in a circular way to share the load. The individual servers would have common access to the same set of Web pages for the site.

Load balancing switches can distribute the load. All requests for the Web site arrive at a machine that then passes the request to one of the available servers. The switch can find out from the servers which one is least loaded, so all of them are doing an equal amount of work. This is the approach that HowStuffWorks uses with its servers. The load balancer spreads the load among three different Web servers. One of the three can fail with no effect on the site.

14) Bind, apply and call difference in angular ?

The bind() method creates a new function that, when called, has its this keyword set to the provided value.
let helloLeo = greeting.bind(customer1);
helloLeo(‘Hello’);

The call() method calls a function with a given this value and arguments provided individually.
The method Call invokes the function and allows you to pass in arguments one by one using commas.
ex: greeting.call(customer1, ‘Hello’);
The method Apply invokes the function and allows you to pass in arguments as an array.
ex: greeting.apply(customer1, [‘Hello’, ‘How are you?’]);

call() and apply() serve the exact same purpose. The only difference between how they work is that call() expects all parameters to be passed in individually, whereas apply() expects an array of all of our parameters.

The main differences between bind() and call() / apply() is that the call() / apply() method:

  • Accepts additional parameters as well
  • Executes the function it was called upon right away.
  • The call()/ / apply() method does not make a copy of the function it is being called on.

Call and Apply are interchangeable. You can decide whether it’s easier to send in an array or a comma separated list of arguments. Bind is different. It always returns a new function.

15) Globalization or internationalization , how to do in angular?

Internationalization is the process of designing and preparing your app to be usable in different languages. Localization is the process of translating your internationalized app into specific languages for particular locales.

Angular simplifies the following aspects of internationalization:

Displaying dates, number, percentages, and currencies in a local format.
Preparing text in component templates for translation.
Handling plural forms of words.
Handling alternative text.
For localization, you can use the Angular CLI to generate most of the boilerplate necessary to create files for translators, and to publish your app in multiple languages. After you have set up your app to use i18n, the CLI can help you with the following steps:

Extracting localizable text into a file that you can send out to be translated.
Building and serving the app for a given locale, using the translated text.
Creating multiple language versions of your app.

i18n pipes
Angular pipes can help you with internationalization: the DatePipe, CurrencyPipe, DecimalPipe and PercentPipe use locale data to format data based on the LOCALE_ID.

Template translations
The i18n template translation process has four phases:
Mark static text messages in your component templates for translation.
Create a translation file: Use the Angular CLI xi18n command to extract the marked text into an industry-standard translation source file.
Edit the generated translation file: Translate the extracted text into the target language.
Merge the completed translation file into the app. To do this, use the Angular CLI build command to compile the app, choosing a locale-specific configuration, or specifying the following command options.

–i18nFile=path to the translation file
–i18nFormat=format of the translation file
–i18nLocale= locale id
The command replaces the original messages with translated text, and generates a new version of the app in the target language.

You need to build and deploy a separate version of the app for each supported language.

The Angular i18n attribute marks translatable content. Place it on every element tag whose fixed text is to be translated.
ex: <h1 i18n> Hello i18n! </h1>

Pluralization :
Pluralization categories include (depending on the language):

=0 (or any other number)
zero
one
two
few
many
other
After the pluralization category, put the default English text in braces ({}).

ex: Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}

16) how to avoid same button multiple clicks ?
There are multiple ways to handle this

  • disable the button after the first click
  • The standard way to avoid multiple clicks is to save the last clicked time and avoid the other button clicks within time span
  • Detect the double click and just return false
  • Debounce Events :
    With the click event we can call event.preventDefault(); and event.stopPropagation();. These two lines prevent the click event from bubbling up to the parent component. SO using certain span of time we can debounce or delay the event for next click.
Categories
AJAX Angular HTML HTML5 JavaScript jQuery NodeJS UI VueJS

Angular Interview Questions and Answers | UI Architect Advanced Level Questions

Angular Interview Questions and Answers | UI Architect Advanced Level Questions

How to write Custom Filter in Angular ?

Angular exposes a simple API for creating a filter. similiar to controller declaration with syntax  app.controller(‘myCtrl', function(){});, you can create a new filter by appending .filter(‘filterName', function(){}) to your Angular application. A filter is very similar to a factory or service but has a global scope once its created.You can invoke a filter on both the data binding in your html or directly inside of your controller or directive by using the $filter service.

Function to find the longest word in a sentence ?
First take string sentence and convert this into a array using split()  with separator as space (‘ ‘).

const stringArray = str.split(" ");

And than pass this array into custom sort function to sort based on the word length.

function findLongestWord(str) {
  const stringArray = str.split(" ");
  const orderedArray = stringArray.sort((a, b) => {
    return a.length < b.length;
  });
  return orderedArray;
}

Now just return the  first word (0-index of the array) of the array which contains longest word of the sentence.

Difference between service & factory in Angular ?

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function’s return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)
  • Singleton and will only be created once
  • Reusable components
  • Factory are a great way for communicating between controllers like sharing data.
  • Can use other dependencies
  • Usually used when the service instance requires complex creation logic
  • Cannot be injected in .config() function.
  • Used for non configurable services
  • If you’re using an object, you could use the factory provider.
  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)
  • Singleton and will only be created once
  • Reusable components
  • Services are used for communication between controllers to share data
  • You can add properties and functions to a service object by using the this keyword
  • Dependencies are injected as constructor arguments
  • Used for simple creation logic
  • Cannot be injected in .config() function.
  • If you’re using a class you could use the service provider
  • Syntax: module.service(‘serviceName’, function);

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

Explain CSS position attribute ?

The position property specifies the type of positioning method used for an element (static, relative, absolute, fixed, or sticky).

static Default value. Elements render in order, as they appear in the document flow
absolute The element is positioned relative to its first positioned (not static) ancestor element
fixed The element is positioned relative to the browser window
relative The element is positioned relative to its normal position
sticky The element is positioned based on the user’s scroll position
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

Explain Isolate Scope in Angular ?
Scope in AngularJS inherits from Parent Scope by default. Isolated scope does not inherit from the parent scope by default. It can access its parent scope through the $parent property.  So, Directive has three options for isolating its scope from parent scope. The following are the three options:

  1. scope: false  It is default in Directive. It lets to reuse the scope from the place where the component is being used.
  2. scope: true – It creates a child scope. This child scope prototypically inherits from the scope where the component is being used.
  3. scope: {…} – It creates Isolates scope. It does not prototypically inherit from the scope where the component is being used.

Isolated scope completely decouples component or template from the rest of the application or a place where it is being used.

There are three types of interface to specify between the element’s attributes and the isolated scope:
  1. interpolate (@)
  2. data bind (=)
  3. expression (&)
Attributes or Interpolate (@)
An Isolated scope property can be bind with DOM attributes. Interpolate or attribute sets up a one-way data binding from the Parent scope to the Isolated Scope of Directive.
Binding (=)
Binding works almost exactly like the attribute except that it provides two-way mode binding.
Expression (&)
Expression is used to call a function on the Parent scope from the Isolated Scope.

Explain angular Prototype ? 

 

Difference between async and defer tags in Javascript ?
Defer and Async tags are available only for external scripts (with src=”” tag). If you will try to use them for internal scripts like <script>…</script> tags, defer and async will be ignored.
Adding an async tag to the JavaScript code , so that creation of the DOM model happens in parallel, and won’t be interrupted while the JavaScript is loading and executed.
Adding a defer tag with JavaScript code, it will not stop loading the DOM and CSSOM models. All scripts with a defer tag will be loaded and run immediately after the DOM and CSSOM models are completed. Any scripts will be loaded in the order you code.

What is Event delegation in JS ?
JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.

What is Closure in JS ?
A closure is basically when an inner function has access to variables outside of its scope. Closures can be used for things like implementing privacy and creating function factories.

What is Debouncing & Throttling in JS ?
Debouncing is one way to solve the issue of same function calling multiple times on event action, by limiting the time that needs to pass by until a function is called again.

Throttling is another technique that’s is similar to debouncing, except that instead of waiting for some time to pass by before calling a function, throttling just spreads the function calls across a longer time interval.
So if an event occurs 10 times within 100 milliseconds, throttling could spread out each of the function calls to be executed once every 2 seconds instead of all firing within 100 milliseconds.

Difference between  TDD vs BDD ?
In TDD (Test Driven Development), the test is written to check the implementation of functionality, but as the code evolves, tests can give false results. BDD (Behavior Driven Development) is also a test-first approach, but differs by testing the actual behavior of the system from the end users perspective.

 

Categories
Angular CSS CSS3 HTML HTML5 JavaScript NodeJS UI

UI Developer / Lead / Architect Interview Question and Answers – Part 2

UI Developer / Lead / Architect Interview Question and Answers – Part 2

Type of components in Angular ? 

There are two types of components in Angular 


– Declarative components  

these components are  which are included in the template


– Entry components 

Any component that Angular loads imperatively and you’re not referencing it in the template. 



what is entry components in modules  ?


An entry component is any component that Angular loads imperatively, (which means you’re not referencing it in the template), by type. 

You specify an entry component by bootstrapping it in an NgModule, or including it in a routing definition. 


There are two main kinds of entry components:


The bootstrapped root component.

A component you specify in a route definition.


Explain the process to do for popup in Angular material design ?   

The Angular Material library offers support for displaying modal dialogs in Material Design. 

To enable Angular Material Dialogs in your Angular application you need to import MdDialogModule in your main application module.

Next, make sure to also add MdDialogModule to the imports array of @NgModule

Make use of the MdDialog service which is part of MdDialogModule in our components

create a new component using cmd “ng g component DialogDemo”

which creates 4 files  html / css / ts / spec.ts  as below 


src/app/dialog-demo/dialog-demo.component.css

src/app/dialog-demo/dialog-demo.component.html

src/app/dialog-demo/dialog-demo.component.spec.ts

src/app/dialog-demo/dialog-demo.component.ts



In dialog-demo.component.html file add html code for modal popup display code using MdDialog, MdButton and MdCard elements and directives. 

import {MdCardModule} from ‘@angular/material’;

import {MdButtonModule} from ‘@angular/material’;

import {MdDialogModule} from ‘@angular/material’;


And add the types to the imports array also :

imports: [

BrowserModule,

BrowserAnimationsModule,

MdCardModule,

MdButtonModule,

MdDialogModule

  ],

  

  

add the component selector to the markup code of our main application component in file app.component.html. 

<app-dialog-demo></app-dialog-demo>

Now you can customize the code based on the actions/events/data sharing etc.. in the modal (Dialog) popup component/services in ts files. 



what is the criteria to choose on JS frameworks ? 

There are many criteria when it comes to choosing a JS framework like 

Functionality , Usability, Reliability, Efficiency, Maintainability and Portability 

and also finalize based on the 

Project requirements suitability 

Browser Support {typically with Safari on the Mac} 

Strength of development team supporting the framework.

Maturity of the framework

Frequency of public updates and releases.

Documentation quality.

Existence of an active community.

Benchmark tests on performance aspects

Extensibility of the framework with Plugin support 

API Style Support 

Commericial Support availablity 

and functionalitywise support like 


DOM navigation/manipulation

Basic UI components support

Advanced UI widget library

Themes and skinning support

Validations support

Ease of server interaction

Multiple data exchange formats support 

how to trigger LazyLoading feature in AngularJS ?

we need lazy loading to improve the performance of loading time of the application. 

Instead of loading all components at first time , in angular we can split this into children and load it whenever required.

Lazy Loading is load only what we need to use when first starting up the application. 

If user navigate to a new page, then the component for that page will load immediately.


Lazy loading is performed by allowing the router config to provide the module to load on route execution. 

To utilize lazy loading you must split your code into modules.

In the app.router.ts you will have the special router called loadChildren, this is used for lazy loading module 

and it accepts value as a string. 

The path of the loadChildren is based on src directory, you need to provide the full path of your feature module 

and put the ‘#’ sign then your export module class name.

Finally, we need to import the app.router.ts that is root router of the application to the app.module.ts.


how to do State Management in AngularJS  ? 

State Management OR Managing state means need to coordinate multiple backends, web workers, and UI components, all of which update the state concurrently. 

Patterns like Redux and Flux are designed to address this problem by making this coordination more explicit.

A typical web application has the following six types of state:


Server state

Persistent state

The URL and router state

Client state

Transient client state

Local UI state


Backend manages the server state, persistent state (the talks) and the client state (the filters).

The router manages the URL and the router state.

WatchService manages the transient client state (watched talks).

The individual components manage the local UI state.


and maintaining / synchronizing these states across the application using custom observers OR usnig tools like Redux. 


what is content in angular ?

Transclusion in AngularJS OR Content Projection in Angular is a way to let you define a fixed view template, and 

at the same time allow you to define a slot for dynamic content by using <ng-content> tag.

and using the type of selector like Attribute, HTML tag, or CSS class etc.. you can load the dynamic content in the ng-content directive section. 

Whenever some libraries conflict issues are coming , how do you solve ?

You can avoid the conflicts with other libraries using namespaces OR Alias like jQuery noConflict method. 

OR 

if libraries are managed using packages.json than using peerDependencies package attribute you can manage multiple versions of files.


Difference between routing and templating ? 

Routing -> To navigate to different pages in the application with no page reloading we use Angular Routing using ngRoute module.

The ngRoute module routes your application to different pages without reloading the entire application.


Templating -> templating allows you to create one master page for the structure and then just replace pieces of the page with different content based on the url.


AngularUI Router -> The UI-Router is a routing framework for AngularJS provides a different approach than ngRoute in that it changes your application views based on state of the application and not just the route URL. 



Difference between unidirectional data binding and bidirectional data binding ? 

One way binding is bind the data from model to view. 

Where as two way binding is bind the data from model to view and view to model. 

Data flows from the Scope/Controller to the View and from the View to the scope/controller). 

‘ng-model’ is an angular directive used for achieving two-way data binding.



Difference between responsive and adaptive design ? 

Responsive sites and adaptive sites are the same in that they both change appearance based on the browser environment , size, device etc…


Responsive Web Design makes your web page look good on all devices (desktops, tablets, and phones). 

Responsive Web Design is about using HTML and CSS to resize, hide, shrink, enlarge, or move the content to make it look good on any screen. 

Fluid grids, flexible images, and media queries are the three technical ingredients for responsive web design.


Adaptive design detects the device and other features and then

provides the appropriate feature and layout based on a predefined set of viewport sizes and other characteristics 



Difference b/w Javascript vs ES5 or ES6 ? 

scripting language is a programming language designed specifically for acting on an existing entity or system. 

ECMA means European Computer Manufacturer’s Association  ECMAScript (ES)  –>  Is the specification defined in ECMA-262 for creating a general purpose scripting language. 

ECMAScript provides the rules, details, and guidelines that a scripting language must observe to be considered ECMAScript compliant.


JavaScript (JS)  –> A general purpose scripting language that conforms to the ECMAScript specification. 

JavaScript mostly implements the ECMAScript specification as described in ECMA-262. 


A JavaScript engine –> A program or interpreter that understands and executes JavaScript code. 

JavaScript engines are commonly found in web browsers, including V8 in Chrome, SpiderMonkey in Firefox, and Chakra in Edge. 


ECMAScript 5 –> 

It is the fifth edition of the ECMA-262 standard, and major features of the ECMAScript specification. 


ECMAScript 6  –> 

It is the sixth edition of the ECMA-262 standard, and features major changes and improvements to the ECMAScript specification.


Babel

A transpiler that can convert ES6 code to ES5 code.



Which is First ? Chicken or  Egg — ECMAScript or JavaScript 

A confusing bit of history is that JavaScript was created in 1996. It was then submitted to Ecma International in 1997 for standardization, which resulted in ECMAScript. At the same time, because JavaScript conformed to the ECMAScript specification, JavaScript is an example of an ECMAScript implementation.

ECMAScript is based on JavaScript, and JavaScript is based on ECMAScript.

To read more on this topic, here is the best article resource : https://www.toptal.com/angular/angular-components-overview-101

Categories
AJAX Angular CSS CSS3 HTML HTML5 JavaScript jQuery NodeJS UI Uncategorized VueJS

SAP – UI Architect – Angular Interview Questions and Answers

List and explain XSS attack types?

Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user’s browser.

XSS attacks are of three types:

  • Persistent XSS, where the malicious string originates from the website’s database.
  • Reflected XSS, where the malicious string originates from the victim’s request.
  • DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.

Methods of preventing XSS

  • Encoding, which escapes the user input so that the browser interprets it only as data, not as code.
  • Validation, which filters the user input so that the browser interprets it as code without malicious commands.

What is CORS , how to manage? How to secure the requests?

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

two response headers are most important for security:  

  • Access-Control-Allow-Origin specifies which domains can access a site’s resources. For example, if ABC Corp. has domains ABC.com and XYZ.com, then its developers can use this header to securely grant XYZ.com access to ABC.com’s resources. 
  • Access-Control-Allow-Methods specifies which HTTP request methods (GET, PUT, DELETE, etc.) can be used to access resources. This header lets developers further enhance security by specifying what methods are valid when XYZ accesses ABC’s resources. 

As CORS can lead to multiple security vulnerabilities , so instead of allowing CORS use a trusted server as a proxy / reverse proxy and allow all requests/resources to be served  from that dedicated server.

What is Virtual polymorphism ?

Polymorphism is the ability for objects of different classes related by inheritance to respond differently to the same member function call.

virtual function allows a programmer to call a function and let the program determine dynamically which version of the function to use.
To enable this type of behavior, the function will be declared in the base class as a virtual function and then be redefined in each of the derived classes.
To declare a virtual function, precede the function’s prototype with the keyword virtual in the base class.
Combination of both Virtual Function with polymorphism concept is called Virtual Polymorphism.

Write a Sql query for products table to get total price of products sold in a quarter ?

 SELECT
  productname, 
  SUM(price) as total_count
  FROM products
  WHERE `date` >= startdate AND `date` <= enddate
  GROUP BY productname
  ;

Write a Sql query for products table to get total price of products sold in a quarter ?

To calculate any factorial in real-time, you can speed it with a cache, saving the numbers you’ve calculated before.

factorial = (function() {
    var cache = {},
        fn = function(n) {
            if (n === 0) {
                return 1;
            } else if (cache[n]) {
                return cache[n];
            }
            return cache[n] = n * fn(n -1);
        };
    return fn;
})();

Types of requests which can be handled through browser?

HTTP, HTTPS, FILE, and FTP protocols are supported by most of the commonly used browsers.

What is promise? Advantages of it ?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

Advantages of promises are

  • Callbacks will never be called before the completion of the current run of the JavaScript event loop.
  • Callbacks added with then() even after the success or failure of the asynchronous operation, will be called, as above.
  • Multiple callbacks may be added by calling then() several times. Each callback is executed one after another, in the order in which they were inserted.
  • One of the great things about using promises is chaining.

How to improve the Performance of webpage?

  • Reduce External HTTP Requests
  • Minify CSS, JS and HTML
  • Compress Components with Gzip
  • Optimize Your Images
  • Add CSS at top/header section
  • Add JS at bottom section
  • Reduce DNS Lookups
  • Use CDN and Cache
  • Make Fewer HTTP Requests
  • Avoid empty src or href
  • Add Expires Headers
  • Avoid CSS Expressions
  • Avoid URL Redirects
  • Remove Duplicate JavaScript and CSS
  • CleanUP the unecessary code
  • Configure Entity Tags (ETags)
  • Reduce the Number of DOM Elements
  • Avoid HTTP 404 (Not Found) Error
  • Do Not Scale Images in HTML
  • Make favicon Small and Cacheable

IF Request/Response taking too much time than How to keep alive the request ?

A Request/Gateway Timeout response code indicates that the server did not receive a complete request from the client within a specific period of time tracked by the server.
You can set custom timeout for your http request in the second parameter of http.get() method:
$http.get(‘request-path’, {timeout: 300000});
This will set timeout to 300 seconds = 5 minutes. Increasing it to something much larger should help.
OR
req.setTimeout(0) for no timeout for all requests
Another solution is doing a long polling or short polling to keep alive the request.

DB 2 queries same record update? How to manage? How to intimate the second request to update itself?

Use SQL transaction statements like BEGIN and COMMIT to avoid concurrent updates to same record.
OR
You may have additional field which indicates that column is being edited. When first user starts work, the field would be updated. The second user would query object with ‘on hold’ status and your code would handle this.

Lot of requests , how to manage?

  • Use CDN for optimized content delivery
  • Use Cache Layers like memcache , redis etc..
  • Use Load Balancing techniques for Application Servers / Cache Layers
  • Use Master / Salve configuration for DB Servers

Same application, for 2 different companies but for all users, request to come, how to manage?

Use Proxy / Reverse proxy configuration along with a flag specific to company to manage the requests to handle internally from different servers.

Bind, apply and call difference in angular ?

The bind() method creates a new function that, when called, has its “this” keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
fun.bind(thisarg[, arg1[,arg2[,….]]])

Function.call allows us to set the this value of a function manually. Instead of simply calling a function like fn(), we use fn.call(param), passing in the object we want this to equal as the parameter.
call also allows us to pass in parameters to the function being called. Anything given after the object to be bound to thiswill be passed along to the function.

Function.apply works the same exact way as call, except instead of passing in arguments one by one, we pass in an array of arguments that gets spread into the function.

In call method parameter will be passed separately. whereas in apply you can pass parameters as Array arguments.

Globalization or internationalization , how to do in angular?

Internationalization (i18n) is the process of developing products in such a way that they can be localized for languages and cultures easily. Localization (l10n), is the process of adapting applications and text to enable their usability in a particular cultural or linguistic market.
internationalizing an application means abstracting all of the strings and other locale-specific bits (such as date or currency formats) out of the application. Localizing an application means providing translations and localized formats for the abstracted bits.
AngularJS supports i18n/l10n for date, number and currency filters.
Localizable pluralization is supported via the ngPluralize directive.
All localizable AngularJS components depend on locale-specific rule sets managed by the $locale service.

How to avoid same button multiple clicks  ?

There are multiple ways to avoid multiple clicks of a same button

  • Once the click event is fired , disable the button till event response is processed
  • Unbind the click event on first click event
  • Provide a time interval for between the same object click event