You are on page 1of 17

What Is Scope Variable In Javascript?

Answer :
The scope is set of objects, variables and function and the JavaScript can have global scope variable and local
scope variable.
The global scope is a window object and its used out of function and within the functions.
The local scope is a function object and its used within the functions.

Question 19. What Is Javascript Hoisted?


Answer :
In the JavaScript, the variables can be used before declared, this kinds of mechanism is called Hoisted. It's a default
behavior of JavaScript.

Question 20. What Is Function Overloading In Javascript?

In the JavaScript, when we write more than one functions with same name that time JavaScript consider the last
define function and override the previous functions

Question 22. What Are Different Data-types Of Javascript?

Answer :
Following are different data-type in JavaScript.

1.String
2.Number
3.Boolean
4.Function
5.Object
6.Null
7.Undefined

Question 25. The Terms “scope” And “context” Refer To The Same Thing In Javascript ?

Answer :
False, Scope pertains to the visibility of variables, and context refers to the object to which a method belongs (which
can be changed by using call or apply)

Question 27. How Do You Determine If A Javascript Instance Object Was Created From A Specific Constructor Or
Not?

Answer :
Use the instanceof operato
Question 29. When You Create A Function Inside Of A Method, What Does The “this” Keyword Refer To When Used
In That Function?
Answer :
The “window” object, Inside of a function, the “this” keyword always refers to the window object. But when a funciton
is a property of on object, the “this” keyword always refers to the object that the function is a method of.

Question 31. Can A Javascript Constructor Return A Primitive Value (e.g. A Number Or A String)?
Answer :
No. A JavaScript constructor can only return an object. When no return value is specified, it returns an instance of
itself. If an object is specified as the return value, then that object is the return value. If any value other than an
object is specified as the return value, then it returns an instance of itself.

Question 33. What Is The Difference Between A Constructor Function And A Non-constructor Function With
Respect To The Word “this” ?
Answer :
In a non-constructor function, “this” refers to the global context or if the function is a method, it refers to the object
to which the method belongs. In the instance object that is returned by a constructor function, “this” refers to the
instance object itself.

Question 34. An Object Literal Can Be Used To Create Private Variables?


Answer :
False. Only functions can be used in JavaScript to create privacy.

Question 37. What Is The Difference Between Using Dot Notation And Bracket Notation When Accessing An Object’s
Property?
Answer :
If using dot notation, the property must be a string and refer to a property that exists.

When using bracket notation, any valid JavaScript expression that produces a value can be used inside the
brackets, such as a variable or an an array element.

Scope pertains to the visibility of variables and in contrast, context refers to the object to which a method
belongs (which can be changed by using call or apply).

Q10. Can you assign an anonymous function to a variable and pass it as an argument to another
function?
Yes! An anonymous function can be assigned to a variable. It can also be passed as an argument to another

function
Q13. What is the purpose of ‘This’ operator in JavaScript?
The JavaScript this keyword refers to the object it belongs to. This has different values depending on where it is

used. In a method, this refers to the owner object and in a function, this refers to the global object.

Q14. What is Callback?
A callback is a plain JavaScript function passed to some method as an argument or option. It is a function that

is to be executed after another function has finished executing, hence the name ‘call back‘. In JavaScript,

functions are objects. Because of this, functions can take functions as arguments, and can be returned by other

functions.

Q15. What is Closure? Give an example.


Closures are created whenever a variable that is defined outside the current scope is accessed from within

some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures

are created every time a function is created. To use a closure, simply define a function inside another function

and expose it

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like
this-
Syntax :

1document.cookie = "key1 = value1; key2 = value2; expires = date";

Q20. How to read a cookie using JavaScript?


Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie.

So you can use this string whenever you want to access the cookie.

•The document.cookie string will keep a list of name = value pairs separated by semicolons, where
name is the name of a cookie and value is its string value.

•You can use strings’ split() function to break the string into key and values.

Q22. What is the difference between Attributes and Property?


Attributes-  provide more details on an element like id, type, value etc.

Property-  is the value assigned to the property like type=”text”, value=’Name’ etc.
Q23. List out the different ways an HTML element can be accessed in a JavaScript code.

Here are the list of ways an HTML element can be accessed in a Javascript code:

(i) getElementById(‘idname’): Gets an element by its ID name

(ii) getElementsByClass(‘classname’): Gets all the elements that have the given classname.

(iii) getElementsByTagName(‘tagname’): Gets all the elements that have the given tag name.

(iv) querySelector(): This function takes css style selector and returns the first selected element.

Q26. What is a Typed language?

Typed Language is in which the values are associated with values and not with variables. It is of two types:

•Dynamically: in this, the variable can hold multiple types; like in JS a variable can take number, chars.
•Statically: in this, the variable can hold only one type, like in Java a variable declared of string can take
only set of characters and nothing else.

Q27. What is the difference between Local storage & Session storage?

Local Storage – The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS,

etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through

settings or program.

Session Storage – It is similar to local storage; the only difference is while data stored in local storage has no

expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will

leave when the browser is closed.

In case you are facing any challenges with these JavaScript Interview Questions, please comment on your

problems in the section belo


Undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null

is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null

are two distinct types: undefined is a type itself (undefined) while null is an object.

Q30. What is the difference between undeclared & undefined?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to

read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those

that are declared in the program but have not been given any value. If the program tries to read the value of an

undefined variable, an undefined value is returned.

Q32. What is the difference between window & document in JavaScript?

Window Document
JavaScript window is a global object which The document also comes under the window and can
holds variables, functions, history, location. be considered as the property of the window.

Q34. What is an event bubbling in JavaScript?

Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element

inside another element, and both elements have registered a handle for that event. With bubbling, the event is

first captured and handled by the innermost element and then propagated to outer elements. The execution

starts from that event and goes to its parent element. Then the execution passes to its parent element and so

on till the body element.

Q37. How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. It takes the string to be converted

as its first parameter, and the second parameter is the base of the given string.

For example-

1parseInt("4F", 16)
Q39. What are Exports & Imports?

Imports and exports help us to write modular JavaScript code. Using Imports and exports we can split our code

into multiple files

40. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict mode is a way to introduce better error-checking into your code.

•When you use strict mode, you cannot use implicitly declared variables, or assign a value to a read-only
property, or add a property to an object that is not extensible.

•You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function.

The call() method calls a function with a given this value and arguments provided individually.

Syntax-

1fun.call(thisArg[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value, and arguments provided as an array.

Syntax-

1fun.apply(thisArg, [argsArray])

OOPs refers to Object-Oriented Programming. It is the programming paradigm that is defined using objects. Objects can be

considered as real-world instances of entities like class, that have some characteristics and behaviors

What are the main features of OOPs?

OOPs or Object Oriented Programming mainly comprises of the below four features, and make sure
you don't miss any of these:
 Inheritance
 Encapsulation
 Polymorphism
 Data Abstraction
7. What are some advantages of using OOPs?

 OOPs is very helpful in solving very complex level of problems.


 Highly complex programs can be created, handled, and maintained easily using object-oriented
programming.
 OOPs, promote code reuse, thereby reducing redundancy.
 OOPs also helps to hide the unnecessary details with the help of Data Abstraction.
 OOPs, are based on a bottom-up approach, unlike the Structural programming paradigm, which uses a
top-down approach.
 Polymorphism offers a lot of flexibility in OOPs
9. What is a class?

A class can be understood as a template or a blueprint, which contains some values, known as member
data or member, and some set of rules, known as behaviors or functions. So when an object is created,
it automatically takes the data and functions that are defined in the class.
Therefore the class is basically a template or blueprint for objects. Also one can create as many objects
as they want based on a class.
For example, first, a car’s template is created. Then multiple units of car are created based on that
template.
10. What is an object?
An object refers to the instance of the class, which contains the instance of the members and behaviors
defined in the class template. In the real world, an object is an actual entity to which a user interacts,
whereas class is just the blueprint for that object. So the objects consume space and have some
characteristic behavior.
For example, a specific car
One can visualize Encapsulation as the method of putting everything that is required to do the job, inside a capsule and
presenting that capsule to the user. What it means is that by Encapsulation, all the necessary data and methods are bind together
and all the unnecessary details are hidden to the normal user. So Encapsulation is the process of binding data members and
methods of a program together to do a specific job, without revealing unnecessary details.

Encapsulation can also be defined in two different ways:

1) Data hiding: Encapsulation is the process of hiding unwanted information, such as restricting access to any member of an

object.
2) Data binding: Encapsulation is the process of binding the data members and the methods together as a whole, as a class

15. What is meant by Inheritance?

The term “inheritance” means “receiving some quality or behavior from a parent to an offspring.” In
object-oriented programming, inheritance is the mechanism by which an object or class (referred to as a
child) is created using the definition of another object or class (referred to as a parent). Inheritance not
only helps to keep the implementation simpler but also helps to facilitate code reuse

10. What is the ‘this’ keyword in JavaScript?

The ‘this’ keyword in JavaScript refers to the currently calling object. It is commonly used in constructors to assign
values to object properties.

A callback is a JavaScript function that is passed to another function as an argument or a parameter. This function is

to be executed whenever the function that it is passed to gets executed. 

A cookie is generally a small data that is sent from a website and stored on the user’s machine by a web browser that

was used to access the website. Cookies are used to remember information for later use and also to record the

browsing activity on a website.

22. What are the arrow functions in JavaScript?

Arrow functions are a short and concise way of writing functions in JavaScript. The general syntax of an arrow
function is as below:

const helloWorld = () => {

  console.log("hello world!");

};
23. What are the different ways an HTML element can be accessed in a

JavaScript code?

Here are the ways an HTML element can be accessed in a JavaScript code:

getElementByClass(‘classname’): Gets all the HTML elements that have the specified classname.

getElementById(‘idname’): Gets an HTML element by its ID name.

getElementbyTagName(‘tagname’): Gets all the HTML elements that have the specified tagname.

querySelector(): Takes CSS style selector and returns the first selected HTML element.

32. What is the difference between Event Capturing and Event Bubbling?

Event Capturing Event Bubbling

This process starts with capturing the event of the This process starts with capturing the event of the
outermost element and then propagating it to the innermost element and then propagating it to the
innermost element. outermost element.

36. What is the difference between Call and Apply?

Call Apply

In the call() method, arguments are provided In the apply() method, arguments are provided in the form
individually along with a ‘this’ value.  of an array along with a ‘this’ value.

39. How do you remove duplicates from a JavaScript array?

There are two ways in which we can remove duplicates from a JavaScript array:
By Using the Filter Method

To call the filter() method, three arguments are required. These are namely array, current element, and index of the
current element.

By Using the For Loop

An empty array is used for storing all the repeating elements.

uestion: Could you name some built-in methods in JavaScript?

Answer: Following are some of the inbuilt methods in JavaScript:

•anchor() – Creates an HTML anchor to be used as a hypertext target

•ceil() – returns the smallest integer that is greater than or equal to the given number

•concat() – Combines two strings and returns the newer string

•constructor() – Returns the function that created the corresponding instance of the object

•Date() – Returns the present date and time

•Date.parse() – Parses a string representation of a date and time and then returns the internal millisecond representation
for the same

•exec() – Searches for a match in the string parameter

•filter() – Creates a new array with all the elements of the array for which the filtering function returns true

•font color () – Displays a string in the specified color

•link() – Creates an HTML hypertext link that requests another URL

•localeCompare() – Returns a number that indicates whether a reference string comes before, after, or is the same as
the given string in the sort order

•match() – Used for matching a regular expression against a string

•pop() – Removes and returns the last element from an array

•reduce() – Applies a function simultaneously for two values of the array to reduce them to a single value

•round() – Rounds off the value of the given number to the nearest integer and returns the same
•slice() – Extracts a certain section of a string and returns the remaining string

•some() – returns true if at least one element of the array satisfies the provided testing function

•toLocaleString() – Return a string value of the current number in a format that depends on the browser’s locale
settings

•sup() – Displays a string as a superscript

•toSource() – Returns a string containing the source of the Boolean object

•toUpperCase() – Converts a text to uppercase

•valueOf() – Returns the primitive value of the specified object

Question: Explain the use of debuggers in JavaScript?

Answer: All modern browsers (Mozilla Firefox, Safari, Google Chrome, etc.) come with an inbuilt debugger that can be
summoned by pressing the F12 key. You need to choose the Console tab to view the result. Here you can set breakpoints as well
as view the value of the variables.

JavaScript also features a debugger keyword that replicates the function of using breakpoints using a debugger. However, it
works only when the debugging option is enabled in the web browser settings.

Question: What are the different types of Error Name values in JavaScript?

Answer: There are 6 types of Error Name values. Each one of them is briefly explained as follows:

•Eval Error – Thrown when coming across an error in eval() (Newer JS releases don’t have it)

•Range Error – Generated when a number outside the specified range is used

•Reference Error – It comes into play when an undeclared variable is used.

•Syntax Error – When the incorrect syntax is used, we get this error

•Type Error – This error is thrown when a value outside the range of data types is tried to be used.

•URI Error – Generated due to the use of illegal characters


Question: What role do deferred scripts play in JavaScript?

Answer: During page loading, the HTML code's parsing is paused by default until the script hasn’t stopped executing. This
results in a delay in displaying the web page if the server is slow or the script that is to be loaded is bulky.

Using deferred scripts results in a delay in the script's execution when the HTML parser is running. Hence, this results in a
reduction in the loading time of the webpage.

Q.1. How to create components in React?

Ans. There are two possible ways to create a component.


✅Functional Components: This is the simplest way to create a component. Those are pure JavaScript
functions that accept props object as first parameter and return React elements:
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>;
}
✅Class Components: You can also use ES6 class to define a component. The above function
component can be written as:
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>;
}
}

Q.2. What are the difference between a class component and functional component?

Ans.
✅Class Components
Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.
Class components extend from React.Component.
In here you have to use this keyword to access the props and functions that you declare inside
the class components.
✅Functional Components
Functional Components are simpler comparing to class-based functions.
Functional Components mainly focuses on the UI of the application, not on the behavior.
To be more precise these are basically render function in the class component.
Functional Components can have state and mimic lifecycle events using Reach Hooks
Q.3. What is difference between controlled vs uncontrolled component?

Ans.
✅Controlled Components
In HTML, form elements such as <input />, <textarea />, and <select /> typically maintain their own state and
update it based on user input. When a user submits a form, the values from the elements mentioned
above are sent with the form. With React it works differently. The component containing the form will
keep track of the value of the input in its state and will re-render the component each time the callback
function, e.g., onChange is fired as the state will be updated. An input form element whose value is
controlled by React in this way is called a "controlled component". You could also call this a "dumb
component".
✅Uncontrolled Components
A Uncontrolled Component is one that stores its own state internally, and you query the DOM using
a ref to find its current value when you need it. This is a bit more like traditional HTML.
Example
// Controlled:
<input type="text" value={value} onChange={handleChange} />

// Uncontrolled:
<input type="text" defaultValue="foo" ref={inputRef} />
// Use `inputRef.current.value` to read the current value of <input>

Q.5. What is prop drilling and how can you avoid it?

Ans. While passing a prop from each component to the next in the hierarchy from the source
component to the deeply nested component. This is called prop drilling.
To avoid prop drilling, a common approach is to use React context. This allows a Provider component
that supplies data to be defined, and allows nested components to consume context data via either
a Consumer component or a useContext hook.

Q.6. What is Pure Component?


Ans. React.PureComponent is exactly the same as React.Component except that it handles
the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a
shallow comparison on both props and state. Component on the other hand won't compare current
props and state to next out of the box. Thus, the component will re-render by default whenever
shouldComponentUpdate is called.
Q.7. Why should we not update the state directly?
Ans. If you try to update state directly then it won't re-render the component.
//Wrong ❌
this.state.message = 'Not Updated';
Instead use setState() method.
It schedules an update to a component's state object. When state changes,
the component responds by re-rendering.
//Correct ✅
this.setState({ message: 'Updated' });
📝 Note: You can directly assign to the state object either in constructor or using latest javascript's class
field declaration syntax.
Q.9. What are synthetic events in React?
Ans. Synthetic Event is a cross-browser wrapper around the browser's native event. It's API is same as
the browser's native event, including stopPropagation() and preventDefault(), except the events work
identically across all browsers.
Q.10. What is "key" prop and what is the benefit of using it in arrays of elements 🗝?
Ans. A key is a special string attribute you should include when creating arrays of elements.Key prop
helps React identify which items have changed, are added, or are removed.
Most often we use ID from our data as key:
const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
When you don't have stable IDs for rendered items, you may use the item index as a key as a last
resort:
const todoItems = todos.map((todo, index) => <li key={index}>{todo.text}</li>);
📝 Note:
1.Using indexes for keys is not recommended if the order of items may change. This can
negatively impact performance and may cause issues with component state.
2.If you extract list item as separate component then apply keys on list component instead
of li tag.
3.There will be a warning message in the console if the key prop is not present on list items.

Q.12. What is the difference between createElement and cloneElement?


Ans. JSX elements will be transpiled to React.createElement() functions to create React elements
which are going to be used for the object representation of UI. Whereas cloneElement is used to clone
an element and pass it new props.
Q.13. What is reconciliation?
Ans. When a component's props or state change, React decides whether an actual DOM update is
necessary by comparing the newly returned element with the previously rendered one. When they are
not equal, React will update the DOM. This process is called reconciliation.
Q.14. Is lazy function supports named exports?
Ans. No, currently React.lazy function supports default exports only. If you would like to import modules
which are named exports, you can create an intermediate module that reexports it as the default. It also
ensures that tree shaking keeps working and don’t pull unused components. Let's take a component file
which exports multiple named components,
Q.15. What are portals in React?
Ans. Portal is a recommended way to render children into a DOM node that exists outside the DOM
hierarchy of the parent component.
ReactDOM.createPortal(child, container);
The first argument is any render-able React child, such as an element, string, or fragment. The second
argument is a DOM element.

Q.17. What are stateful components?


Ans. If the behaviour of a component is dependent on the state of the component then it can be termed
as stateful component. These stateful components are always class components and have a state that
gets initialized in the constructor.

Q.20. Why we need to pass a function to setState()?


Ans. The reason behind for this is that setState() is an asynchronous operation. React batches state
changes for performance reasons, so the state may not change immediately after setState() is called. That
means you should not rely on the current state when calling setState() since you can't be sure what that
state will be. The solution is to pass a function to setState(), with the previous state as an argument. By
doing this you can avoid issues with the user getting the old state value on access due to the
asynchronous nature of setState().

Q.28. What are render props?


Ans. Render Props is a simple technique for sharing code between components using a prop whose
value is a function. The below component uses render prop which returns a React element.

Q4: 

What are Higher-Order components?
Junior  
  React  155  
Answer
A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is
derived from React’s compositional nature We call them as “pure’ components” because they can accept any dynamically provided
child component but they won’t modify or copy any behavior from their input components.

const EnhancedComponent = higherOrderComponent(WrappedComponent);


HOC can be used for many use cases as below,

1. Code reuse, logic and bootstrap abstraction

2. Render High jacking

3. State abstraction and manipulation

4. Props manipulation

Q7: 
What does it mean for a component to be mounted in React?

Junior  

  React  155  
Answer

It has a corresponding element created in the DOM and is connected to that.

Q8: 
What is the difference between state and props?

Junior  

  React  155  
Answer

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are
different in their functionality with respect to component. i.e,

• Props get passed to the component similar to function parameters

• State is managed within the component similar to variables declared within a function.

Q10: 
What's the difference between a Controlled component and an Uncontrolled one in React?

Junior  

  React  155  
Answer

This relates to stateful DOM components (form elements) and the React docs explain the difference:
• A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange.
A parent component "controls" it by handling the callback and managing its own state and passing the new values as props
to the controlled component. You could also call this a "dumb component".
• A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current
value when you need it. This is a bit more like traditional HTML.
Most native React form components support both controlled and uncontrolled usage:

Q13: 
React Hooks: Does React useState Hook update immediately?

Mid  

  React  155  
Problem

And how do you perform an action after useState hook has triggered?


Answer

React useState and setState don’t make changes directly to the state object; they create queues to optimize performance, which is why the
changes don’t update immediately. The process to update React state is asynchronous for performance reasons.
To perform side effects after state has change, you must use the useEffect

You might also like