React and Js
React and Js
Javascript engine:
JavaScript is not understandable by computer but the only browser
understands JavaScript. So, we need a program to convert our
JavaScript program into computer-understandable language. A
JavaScript engine is a computer program that executes JavaScript
code and converts it into computer understandable language.
Google Chrome V8
● Interpreter
Interpreters are quick. We don’t have to go through that
whole compilation step before execution. It just starts
translating the first line and then executes it. the interpreter
runs the code and executes it line by line.
● Compiler
The source code is converted into machine code once and
then gets executed.
● JIT(Just in Time)
In short, a Just in time compiler is nothing but a
combination of an interpreter and a compiler.
With DOM, we can easily access and manipulate tags, IDs, classes,
Attributes, or Elements of HTML using commands or methods
provided by the Document object.
Why DOM?
DOM converts our file element into an object tree. javascript can not
understand the tags(<h1>H</h1>) in HTML documents but can
understand object h1 in DOM. Now, Javascript can access each of
the objects (h1, p, etc) by using different functions. With DOM, we
can easily access and manipulate tags, IDs, classes, Attributes, or
Elements of HTML using commands or methods provided by the
Document object.
a. Execution Context
The First thing the javascript engine does is to create this Global
Execution Context. And it gives you two things: window object and
this.
There are two types of execution contexts: global and function. The
global execution context is created when a JavaScript script first
starts to run, and it represents the global scope in JavaScript. A
function execution context is created whenever a function is called,
representing the function's local scope.
- Primitive types
String, Number, BigInt, Boolean, Undefined(variable is
declared but not assigned),
Null(It represents a non-existent or a invalid value), Symbol
- Non-primitive types
Object - Used to store collection of data.
var obj1 = {
x: 43,
y: "Hello world!",
z: function(){
return this.x;
}
}
4. Declare/Define?
Declare - creating a variable is called "Declaring" a variable
in JavaScript.
Define - assign a value to the variable
5. Hoisting?
All the variables and functions are declared, they are moved on top of
the scope before code execution. The scope can be both local and
global. Hoisting is the default behavior of javascript.
7. Scope
There are two types of scopes in JS:
● Global Scope: all the variables and functions having global
scope can be accessed from anywhere inside the code.
https://www.interviewbit.com/problems/var-vs-let-vs-
const/
8. Lexical Environment
When the JavaScript engine creates a global execution
context to execute global code, it also creates a new lexical
environment to store the variables and functions defined in the
global scope.
A lexical Environment is holds an identifier-variable mapping
10. NaN?
NaN property represents the “Not-a-Number” value. It indicates a
value that is not a legal number.
● non-primitive types:
var obj = #8711; // obj pointing to address of { name:
"Vivek", surname: "Bisht" }
var obj2 = obj;
var obj2 = #8711; // obj2 pointing to the same address
// changing the value of obj1
obj1.name = "Akki";
console.log(obj2);
// Returns {name:"Akki", surname:"Bisht"} since both the
variables are pointing to the same address.
12. strict mode?
a. Duplicate arguments are not allowed.
b. you won't be able to use the JavaScript keyword as
a parameter or function name..
c. not allowed to create global variables in 'Strict
Mode.
—-------------
function higherOrder(fn) {
fn();
}
higherOrder(function() { console.log("Hello world") });
—--------------
function higherOrder2() {
return function() {
return "Do something";
}
}
var x = higherOrder2();
x() // Returns "Do something"
14. Inheritance
inheritance is an object getting access to the properties and method
of another object
15. “This”
this keyword refers to an object. In a regular function, this changes
according to the way that function is invoked.
Simple Invocation: this refers to the global object or maybe
undefined if you are using strict mode.
Method Invocation: this refers to the parent functions.
Indirect Invocation: if you use call or apply then that time this refers
to the first argument.
Constructor Invocation: this refers to the newly created instance.
18. Callback
A callback function is a function that is
passed to another function as an argument and is executed after
some operation has been completed.
19. Closures?
Closure means that an inner function has access to the vars and
parameters of its outer function, even after the outer function has
returned. like variables remember their values even after a function
call. because the inner function retains a reference to the outer
function, even after the outer function has been executed.
When the function will be executed. Then all its variables will be used
and it will return a value, after the value is returned then all the
variables will be destroyed.
The function and the lexical environment reference are also returned.
function Counter()
{
var counter = 0;
function IncreaseCounter()
{
return counter += 1;
};
return IncreaseCounter;
}
var counter = Counter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
alert(counter()); // 4
22. promises?
Promises are used to handle asynchronous operations in javascript.
24. Currying?
transforms a function into a nested series of functions, each taking a
single argument. Instead of taking all the arguments at the same
time, the function takes one argument at a time and returns a new
function.
function multiply(a,b){
return a*b;
}
function currying(fn){
return function(a){
return function(b){
return fn(a,b);
}
}
}
var curriedMultiply = currying(multiply);
multiply(4, 3); // Returns 12
curriedMultiply(4)(3); // Also returns 12
It divides your function into multiple smaller functions that can handle
one responsibility.
25. Coercion?
Implicit type coercion in javascript is the automatic conversion of
value from one data type to another.
● String coercion
var x = 3;
var y = "3";
x + y // Returns "33"
var x = 3;
Var y = "3";
x - y //Returns 0 since the variable y (string type) is
converted to a number type
● If statements:
var x = 0;
var y = 23;
if(x) { console.log(x) } // The code inside this block will not
run since the value of x is 0(Falsy)
if(y) { console.log(y) } // The code inside this block will run
since the value of y is 23 (Truthy)
● Logical operators
OR ( | | ) operator - If the first value is truthy, then the first
value is returned. Otherwise, the second value always gets
returned.
Event Bubbling
1. Capturing Phase
2. Target Phase
3. Bubbling Phase
Let's say we add a button in our webpage and the button is wrapped
into another div ok. So button is a child element and div is parent
element. When you click on a button it automatically clicks on the
parent element also. So it calls Bubbling like an event call and
bubbles up all the elements
Cookie and Session
Cookie Session
Cookies are client-side files that are Sessions are server-side files that store user information.
stored on a local computer and contain session start() method
user information.
Cookies expire after the user specified The session ends when the user closes the browser or logs
lifetime. out of the program.
It can only store a limited amount of It is able to store an unlimited amount of information.
data .Like 4 KB
Cookies are used to store information The data is saved in an encrypted format during sessions.
in a text file.
event delegation
BFC.
In the webpage all the elements in the block box are right so
sometimes we face some issues like overlapping and all.
So BFC defines some rules like Root element should be HTML and
float is not null, display elements should be inline-box or table or flex
and grid.
React
Arrow Functions
Render
It is compulsory for each component to have a renader() function.
Render function returns the html which is to be displayed in a
component. If you need to render more than one element, all the
elements must be inside one parent tag.
Hooks
Hooks are the function component that let you “hook into” react
state and lifecycle features from the function component.
Why hooks?
● No more complex lifecycle method
● You don't want to worry about “this” keyword
● No more method binding
Initial render
componentDidMount()
usEffect(()=>{
},[])
update
Shouldcomponentupdate()
useMemo() // basically you can decide whether you can render this
component or not.
componentDidUpdate()
useState(() => {
})
useState(() => {
setUser(“Hemanhsi”);
},[props.user])
Unmount
useState(() => {
return () => {{cleanup}}
}, [])
State
The state is used to contain data or information about the
component. Every time the state of an object changes, React re-
renders the component to the browser
● The state object is initialized in the constructor
● A state can be modified based on user action or network
changes
● The state object can store multiple properties
● this.setState() is used to change the value of the state
object
Props
Props stand for "Properties." They are read-only components. Props
are used to store data that can be accessed by the children
component.
State vs Props
State Props
Example
HOC.js
Const HOC = (component) => {
const data = {
firstName: “Hemanshi”,
lastName: “Undhad”
}
return () => <component values={data} />
}
export default HOC;
App.js
Import HOC from “./HOC”;
const App = ({values}) => {
returns (
<div>
First Name: {values.firstName}
Last Name: {values.lastName}
<div>
)
}
Export default HOC(App);
Components
components are independent and reusable bits of code.
Functional
Class Components
Components
Pure Component
Pure Component compares current state and props with new props
and states to decide whether the component should re-render itself
or Not.
Lifecycle
iii. Updation
Store: it hold the state of the application, storing all of the states in a
single place called a store
Routing
React Routing is binding an URL to a component. React does not
support routing directly. So we can use third party library like react-
router-dom
React router provides four components to manage navigation
1.Router
2.Link
<Link to="/">Home</Link>
3. Route
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
<Router>
<Route path="/about" component={About} />
</Router>
Styling
● Inline styling
● Javascript object
const styleobj={
color: “white”,
margin: “8px”
}
<h1 style={styleobj} />
● create a css file and import it in the component.
filter: filter function filters all values on the array based on some
conditions.
reduce: reducer function executes each element of the array and
returns a single output value.
Debouncing
Debouncing it helps us to optimize how to call certain events.
Ex: in the input field we call some function and call API on onChange
event.
The debounce function makes sure that the code is only triggered
once user input pauses.
Throttling
Throttling is a technique to limit the execution of an event handle
function even when an event triggers continuously due to user
action.
Like you set the trigger limit as a 400 millisecond ok. And you trigger
events continuously so what happens is that the action only calls
every 400 milisecound.
ECMAScript
responsbility
Why React
From the start of my career I just worked with react only. So I think I
have good knowledge about react.
One-way data flow: React follows a one-way data flow model, where
the data flows in one direction, from the parent component to the
child component. This makes it easier to debug and understand the
flow of data within the application.
AXIOS
● Cancel requests
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
- Code Splitting
Split your code into smaller parts so that only the necessary parts are
loaded when needed.
- Debouncing concepts
Debouncing refers to ignoring the event handler call until the calls
have stopped for a certain amount of time.
- When data is 1000 of code then add Pagination and like you can
fetch first 50 record and then when you click on next then next 50
record fetch or you can fetch record scroll base when you scroll
down then api call and data will be fetch
Call ()
let car1 = {
color: "Red",
company: "Hundai"
}
content.fn = this;
content.fn(...args);
}
Apply()
let car1 = {
color: "Red",
company: "Hundai"
}
if(!Array.isArray(args)) {
throw new TypeError("Not Array")
}
content.fn = this;
content.fn(...args);
}
Bind()
let car1 = {
color: "Red",
company: "Hundai"
};
const fn = this;
return function (...newArgs) {
return fn.apply(content, [...args, ...newArgs]);
};
};
Project structure
Hooks
Curring
Clourser
LifeCycle
Diff React 16 - 18
Deployment
Lazy component
1. what is debouncing,
2. what is throtlling,
3. why should we use react js over other framework and libraries,
4. tell me a scenario where you found a solution for a blocker or problem
that you are really proud of,
5. explain all the hooks in reactjs,
6. explain component lifecycle and all the lifecycle methods in functional
component,
7. what is redux saga and redux thunk,
8. explain all the methods in react js for overall application speed
optimization,
9. what is polyfill using call, apply, bind for reusable logic in javascript,
10. explain prototype in javascript,
11. what are higher order components,
coding round:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
input : “[()]{}{[()()]()}” validate if the structure is correct if it is return
true or else return false
the validation should check if a opening braces have a closing
braces and also they are in the currect order
example: in javascript the correct order is [ { ( ) } ]
Que: what are the challenging roles that i can expect here? I m very
much interested this role so