1. Hosting in JS:- In JavaScript, a variable can be declared after it has been used.
2. Hoisting: It means variable declarations are put into memory during compile time.
e.g.
console.log(num); // Returns undefined, as only declaration was hoisted, no initialization
has happened at this stage
var num; // Declaration
num = 6; // Initialization
3. Function declarations are hoisted, while function expressions are not. This means that function
declarations are available to be called before they are defined, while function expressions are not.
4. Function declarations must have a name, while function expressions do not. This is due to the fact
that function expressions are stored in variables.
Function Declaration:-
function myFunction() { // do something}
Function Expression:-
let myFunction = function() { // do something}
5. Function declarations should be used when you want the function to be available throughout your code.
Function expressions should be used when you want to create a function that is anonymous or when you
want to control when the function is executed.
2. Difference between Let and var and const
var and let are both used for variable declaration in javascript but the difference
between them is that var is function scoped and let is block scoped. It can be said that a variable declared
with var is defined throughout the program as compared to let.
Let and const declarations are hoisted but they are never initialized even with undefined.
Const declarations must be initialized and once initialized, we can’t re-assign new value.
e.g.
function run() {
var foo = "Foo";
let bar = "Bar";
Public
console.log(foo, bar); // Foo Bar
{
var moo = "Mooo"
let baz = "Bazz";
console.log(moo, baz); // Mooo Bazz
}
console.log(moo); // Mooo
console.log(baz); // ReferenceError
}
run();
3. Difference between ==,===
== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing
two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands
without considering their type. ... == will not compare the value of variables at all.
e.g.:
console.log(2=='2') // true
console.log(2==='2')// false here it is checking the datatype that is why it is giving false
4.Difference between slice and splice in JS
Split()
Split is a function that split the given string into an array of substrings. The split method doesn't change
the original string array and will return the new array.
Public
Slice()
Slice method doesn't change the original array. It is method of both arrays and strings. Slice method can
take two arguments. First argument is required, second argument is optional.
First argument that represent where to start selection.
Second argument that represent where to end selection.
Splice()
Splice method changes the original array. It can remove element, replace existing elements, or add new
elements to array. It can take 3+ arguments.
First argument is index and requried.
Second argument is optional and represent the number of items be removed.
Third argument is optional and represent the number of items be added. Argument can be increased.
5.What is NaN in JS
NaN is of type number and therefore can be used in calculations. If you ever use NaN in a calculation, the
result is also NaN. Think of NaN as like an error in a mathematical context
6.Array destructing
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties
from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them
to variables.
Suppoose you are getting JSON response in an Array form you wanted to use few elements or objects from
that array.
Public
7.Difference between Local Storage and Session Storage
LocalStorage
Data is shared between all tabs and windows from the same origin.
The data will not expire. It will remain even after browser restart and survive OS reboot too.
Limits the size of data you can store (~5MB across all major browsers).
e.g:- we can store the results in array and displayed into UI checptickets.nl, search count
SessionStorage
The sessionStorage exists only within the current browser tab. Another tab with the same page will have
different session storage.
It is shared between iframes in the same tab (assuming they come from the same origin).
The data survives page refresh, but not closing/opening the tab.
Limits the size of data you can store (5MB to 10MB).
8.use Strict in JS
The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps
you write safer JavaScript code by throwing an error if a global variable is created by mistake. For
example, the following program will throw an error:
function doSomething(val) {
"use strict";
x = val + 10;
}`
9.typof in JS
Typeof is an operator used to detect the type of our variables.
10.Difference between map and filter
Filter is a function that operates over an array of elements and creates a new array with the elements that
pass the callback test, that is, when the callback returns true the element is retrieved in the new array.
Map takes an array of elements and returns a new array of elements transformed by the callback.
Reduce operates over an array and returns a single value. It performs operations over each element and
saves the result using an accumulated value. Then it returns that accumulated value.
Public
Public
11. What is IIFEs (Immediately Invoked Function Expressions)?
It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s
created:
(function IIFE(){
console.log( "Hello!" );
})();
// "Hello!"
This pattern is often used when trying to avoid polluting the global namespace, because all the variables
used inside the IIFE (like in any other normal function) are not visible outside its scope.
12.Closure in JS
function makeFunc() {
var name = 'test';
function display() {
alert(name);
}
return display;
}
Function inside the function called closure in JS, here var name has lexical scope if we move it out it will
throw the reference error.
Public
13.LexicalScope in JS
var name has lexical scope if we move it out it will throw the reference error.
Public
Public
Public
Public
Public
Public
14. What is Redux
Redux is an open-source JavaScript library for managing application state.
Components trigger the call-to-action creator and create the action and then dispatch to reducer.
Public
ACTION CREATOR:
A function that creates an action
ACTION:
An object that contains information about how we want to change
some data within our central state
action: {
type: [describes what change we want to make to our data],
payload: [context of what change we want to make]
}
DISPATCH:
A function that takes in an action, makes copies of the action, and
sends them out to the reducers.
REDUCER:
A function that takes in an action and some existing data, changes the
Public
data according to the type and payload of the action, and then sends
the updated data to the state.
STATE:
An object that serves as the central repository of all data from
the reducers.
15.useState
UseState is a built-in function in React. It takes a single argument and returns an array of two elements
when executed.
It is used to manage the state of the component.
When the state of a component changes, React re-renders that
component and all of its child components automatically.
It takes the initial value of the state as an argument.
It returns an array of two elements.
The first element is the value of the state.
The second element is a function that you can use to set the
value of the state
You can name these elements whatever you like, but the
common practice is to name them as var and setVar. For
instance, in the above example, we named it
as count and setCount.
E.g.
import React, { useState } from "react"
function Counter() {
const [count, setCount] = useState(0)
function increment() {
setCount(count + 1)
}
return (
<button onClick={increment}>{count}</button>
)
}
This renders a simple button that shows the value of count. Initially, it
is 0. Whenever you click on the button, the count value is increased by
Public
1 by using setCount. And as soon as the state changes, the component
rerenders and the new value of count is shown in the button.
16.useCallback
The useCallback hook is very useful when creating an application where some of the functions created are
complex and re-rendering the component might make such function run which we don't want, probably
because it might slow down the run time.
In our application when we are authenticating user through okta, we are calling callback function that
validates if this user has valid rights or not according to that it generates the token and allow the user to
access the application.
A callback function is a function passed into another function as an argument, which is then invoked inside
the outer function to complete some kind of routine or action.
17.useEffect
useEffect runs anytime something changes. This could be the user interacting with a form, a button, etc.
State changing, like counter in my Timer app, counting down every second or start being set from false to
true when the user hits START. Or the component itself is loaded (mounted) or unloaded (unmounted) from
the screen.
e.g.
useEffect(() => {
if (counter === 0) {
setStart(false)
}
}, [counter, setStart])
Note:- if you want a useEffect to run only once, you place an empty array [] at end of your useEffect
function, because there aren't any dependencies, it won't know to run when state changes again
18.UseRef
useRef returns a mutable ref object whose .current property is initialized to the passed argument
(initialValue). The returned object will persist for the full lifetime of the component.
If you wanted to store the previous value of your state you can use Refs.
Refs persist the value throughout the component without re-rendering the component.
refs are: managing focus, text selection, or media playback, triggering animations, and integrating with
third-party DOM libraries.
19.useContext
Public
In React, context is more like a global variable that can be used across all components in an application.
An example of when to use the context hook is to set the preferred theme or to store the currently signed-
in user.
You should use the context hook only when you need some data to be accessible by many components.
working with useContext
To understand useContext better we'll be creating a context that stores a user's details and we'll be
showing some things to the user if their details are stored in the context.
20.UseReducer
The useReducer hook is very similar to the useState hook, it allows you to manage a state and rerender
the component whenever your state changes, It accepts a reducer and an initial state (like the example
below) and returns a new version of the state and a dispatch method based on the action performed in the
reducer.
e.g.
const initialState = {
loading: false,
error: false,
names: [],
};
const reducer = (state = initialState, action) => {
switch(action.type) {
case "loading":
return { ...state, loading: true };
case "error":
return { ...state, error: true, loading: false };
case "success":
return { ...state, names: action.payload };
default:
return state;
}
}
21. Promise
A promise gives you an assurance that something will be done. Whether they(who made the promise) will
do it themselves or they get it done by others is immaterial. They give you an assurance based on which
you can plan something.
✔️.then( ) - for resolved:
If the Promise success, then something will happen next depends on what we do with the resolved
Promise
❌ .catch( ) - for rejected:
What if the Promise fails? it will jump to the catch( ), therefore we need to use the catch( ) method.
Public
Public
22. Difference between state and props
State - This is data maintained inside a component. It is local or owned by that specific component. The
component itself will update the state using the setState function.
Props - Data passed in from a parent component. props are read-only in the child component that receives
them. However, callback functions can also be passed, which can be executed inside the child to initiate
an update.
The difference is all about which component owns the data. State is owned locally and updated by the
component itself. Props are owned by a parent component and are read-only. Props can only be updated if
a callback function is passed to the child to trigger an upstream change.
The state of a parent component can be passed a prop to the child. They are referencing the same value,
but only the parent component can update it.
23.Single Page Application
single-page application is an app working inside a browser and not requiring page reloading when being
used. Some of them are used by millions and billions of users every day without even noticing it.
24. Design patters
25. Virtual DOM
Public
Virtual DOM is a representation of real DOM. Whenever states are changed new virtual DOM will be
created and will be compared with previous virtual DOM. And then DOM operations will be applied for
those specific changes. The cost of virtual DOM is calculating diff with another virtual DOM. For a big
project with lots of components, diff calculation will take time.
Frequent DOM manipulations are expensive.
Virtual DOM is a virtual representation of DOM in memory.
Virtual DOM is synced with real DOM with ReactDOM library. This process is called Reconciliation.
React compares the Virtual DOM and pre-updated Virtual DOM and only marks the sub-tree of
components that are updated. This process is called diffing.
26. Lazy Loading in React
27. Difference between key and refs
28. Difference between call and apply and bind?
Public
Public
Public
29. What is function currying
Public
Difference between async and await
Public
Public
SetTimeout and Event Loop:-
Analogy created by me to explain how event loop and seTimeout work in Javascript.
You visited a restaurant and gave the order bring tomato soup and then after some time your friend also
said bring one tomato soup for me as well.
Then you were told to bring this starter after 5 minutes of serving Soup.
1. When execution starts it will print 1st Console statement(call goes to the kitchen directly and soup will
be served)
2. when you said to bring this starter after 5 minutes he will keep the starter ready but will serve after 5
minutes completed(call goes to the kitchen with some instructions and then wait).
3. Your friend also ordered Soup then 3rd console will be printed (call goes to the kitchen directly and soup
will be served)
Here, the waiter is the event loop will wait for 5 minutes in the callback queue and check call stack is
empty or not.
Public
Public
29. Difference between functional component and class component in react?
30. Fragment in react
Fragment allow us to bind all the component in one fragment node and faster the renderinf of the
components.
<>
<div>a1</div>
<div>a2</div>
</>
<fragment>
<div>a1</div>
<div>a2</div>
</fragment>
31.difference between defer and async.
Async downloads the file during HTML parsing and will pause the HTML parse to execute it when it has
finished downloading.
Defer downloads the file during HTML parsing and well only execute it after the parser has completed.
Defer scripts are also guaranteed to execute in the order that they appear in the documents.
React LifeCycle:
In class component:
Public
component did mount ---> render ---> component did update ---> component will unmount
In Functional Component:-
render method then useEffect
useEffect writes inside the component, by doing that we can use props and state of this
component without writing additional code.
component did mount can be achieved by passing empty array as second parameter to useEffect.
useEffect(()=>{
},[])
component will umount can be achieved by returning another function inside useEffect.
useEffect(()=>{
return()=>{
}
},[])
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
window.removeEventListener('unhandledRejection', handler);
}
}, [])
component will unmount:- it used to unmount the component after render.
Component Did Update:-
Public
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array
If you include this array, make sure to include all values from the component scope that change over time
(props, state), or you may end up referencing values from previous renders.
we can write multiple useEffect inside one functional component to segregate functionality like
lifecycle hooks.
controlled components: when we are passing some value to a text field according to that we are getting
the response or response gets changed after clicking on submit button. Components are controlled by us.
All form elements are called controlled components e.g. input type text or button.
Public
Public
Bubble Sort:-
Public
const arr = [1, 2, 3, 4, 5, 2, 3, 1, 1, 2, 7, 9, 1, 2]
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
console.log(arr[i]);
}
Remove duplicate
const arr = [1, 2, 3, 4, 5, 2, 3, 1, 1, 2, 7, 9, 1, 2]
for (let i = 0; i < arr.length; i++) {
let exists = false
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
exists = true;
break;
}
}
if (!exists) {
arr.push(arr[i]);
}
console.log(arr[i]);
}
Flatter array:-
function flatten() {
Public
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat
}
console.log(flatten(1, [2, 3, [4,[99,[8,11],9], 5]]))
function flatten(arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
res = res.concat(flatten(arr[i]));
} else {
res.push(arr[i]);
}
}
return res;
}
console.log(flatten([1, 2, [3, [4, 5, [6]]], 7, 8])); // [1, 2, Array(2), 7, 8]
const flatten = function(arr, result = []) {
for (let i = 0; i < arr.length; i++) {
const value = arr[i];
if (Array.isArray(value)) {
flatten(value, result);
} else {
result.push(value);
}
}
return result;
};
Array two sum problem
Public
const nums=[1,3,4,5,9,8];
const target = 9;
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
}
console.log(function twoSum(nums, target))
Public
Difference between useMemo and useCallback?
useMemo doesn’t return the function it returns the value of the function.
useCallBack return entire function
Custom hooks.
1.
import { useState } from "react";
export default function useCustomHooks(value){
const[name,setName]=useState(value);
return[name,setName];
// if we add use keyword before any function will convert that function as
custom hook.
//this is not neccsaary if we are passing argument to the function it can
also behave as a custom hooks as well.
}
2.
import { useEffect } from "react";
export default function useUpdateLogger(value){
useEffect(()=>{
console.log(value)
},[value])
}
Hooks are introduced in react 16.8
useEffect is Asynchronous while useLayoutEffect is synchronous
Monolithic Architecture:
1. All the api reside inside the one repository or we can say that it resides as single microservice.
2. If any api call goes fail entire system gets down.
3. Monolithic, we create one war file for deployment.
4. Entire application run on single server, if anything happen or server downs, entire application will
stop responding.
Microservice Architecture:
1. Each Microservice will be deployed into different server. We can achieve high availability, if one
microservice gets down entire application will work as is.
2. Each microservice has their own war file to deploy into the server.
3.
Public