Week-1_interview_Qs
Week-1_interview_Qs
Week-1
Q1 How would you differentiate between the actual web page and the DOM?
The actual web page and the Document Object Model (DOM) are two different entities. The web page is a static
HTML document that gets loaded by the browser, while the DOM is a dynamic representation of that web page in
memory. It’s an object-oriented model created by the browser after parsing the HTML document, allowing
JavaScript to interact with the content, structure, and style of the website. This interaction includes adding,
modifying, or deleting elements and attributes. Therefore, while the web page is the initial state of a site, the DOM
represents its live, interactive state.
In JavaScript, individual elements in the DOM can be selected using various methods. The most common are
‘getElementById’, ‘getElementsByClassName’, and ‘getElementsByTagName’. ‘getElementById’ is used to select
an element with a specific id. For example: let element = document.getElementById('myId');
Q3 Explain the key differences between `getElementById` an`getElementsByClassName` in the context of the
DOM.
Answer: - `getElementById`: This method is used to retrieve an element by its unique identifier. It returns a single
element, and the ID should be unique within the document.
- `getElementsByClassName`: This method retrieves a collection of elements that have a specified class name. It
returns a NodeList, and multiple elements can share the same class.
Q4 Error Finding:
html
<script>
console.log(elementById.innerHTML); // Correct
</script>
console.log(elementsByClass[0].innerHTML); // Correct
Q5 How would you create a new HTML element dynamically using JavaScript, and append it to the
document?
Answer:
```javascript
document.body.appendChild(newElement);
Output-based: After executing the above code, a new paragraph will be added to the end of the document body with
the specified text content.
Q7: How can you efficiently select multiple elements with a specific class and perform an action on each using
modern JavaScript?
Answer:
```javascript
elements.forEach(function(element) {
});
Asynchronous programming is a form of programming where code is executed in a non-blocking fashion. This
means that code can be executed without waiting for other code to finish running. This can be useful for tasks that
may take some time to complete, such as making network requests or accessing files. Asynchronous programming
can make code more responsive and improve performance.
Q9 Can you give me some examples of real-world use cases for asynchronous programming in JavaScript?
There are many real-world use cases for asynchronous programming in JavaScript. For example, if you are trying to
load data from a remote server, you will need to use asynchronous programming to ensure that the data is loaded
before your code tries to access it. Other examples include working with files or databases, where you need to wait
for the file or database operation to complete before moving on to the next step in your code.
Q10 How can you add a callback function to an asynchronous call in JavaScript?
In order to add a callback function to an asynchronous call in JavaScript, you will need to use the .then() method.
This method takes in a function as an argument, which will be executed once the asynchronous call has been
completed.
In synchronous programming, each line of code must be executed in order before the next line can run. This can lead
to issues if one line of code is taking a long time to execute, as it can hold up the rest of the code from running.
Asynchronous programming, on the other hand, allows for different lines of code to run at the same time. This can
make code run more efficiently, as long as the different lines of code don’t need to interact with each other
The Event Loop is a mechanism used by JavaScript to handle asynchronous events. It is a continuous loop that
checks for events and then processes them accordingly. This allows JavaScript to handle multiple events at the same
time and makes it possible for things like animations and user input to be processed without blocking the main
thread of execution.
Q13 Can you explain what the this keyword does in JavaScript?
The this keyword in JavaScript refers to the object that is currently being processed. It can be used to access
properties and methods of that object.
Event emitters are objects that emit events. When an event is emitted, all the registered event handlers for that event
are called.
Callbacks are not recommended for most applications because they can lead to code that is difficult to read and
debug. When using callbacks, it is easy to create a situation where your code is “callback hell” – a situation where
you have so many nested callbacks that it is difficult to follow the flow of execution. This can make your code
difficult to understand and maintain.
let x = { b: 1, c: 2 };
let y = Object.keys(x);
console.log(y.length);
Output
2
Explanation: The code first creates an object x with two properties b and c, and assigns it to the variable x. Then,
the Object.keys() method is used to retrieve an array of the keys of x, which are “b” and “c”. This array is
assigned to the variable y.
Finally, the length of the array y (which is the number of keys in x) is printed to the console using console.log().
Since y has two elements, the output of y.length will be 2.
Q17 Find Output
let x = false;
let y = "0";
let z = 0;
console.log(x == y);
console.log(x == z
Output
true
true
Explanation: In JavaScript, when you use the == operator to compare values of different types, the operands will
be converted to a common type before the comparison is made. This process is called type coercion.
In the first comparison (x == y), x is a Boolean (false) and y is a string (“0”). Since both false and “0” can be
coerced to the Boolean false, the comparison returns true.
In the second comparison (x == z), x is a Boolean (false) and z is a number (0). Since both false and 0 can be
coerced to the number 0, the comparison returns true.
Q18 Find Output
let x = [];
console.log(Boolean(x));
Output :true
Explanation: In JavaScript, an empty array [] is a truthy value when coerced to a Boolean. This means that when
you use Boolean(x) to convert x to a Boolean value, it will return true.
In general, any non-empty array (i.e., an array with one or more elements) is also truthy when coerced to a
Boolean.
Q19 Find Output
let x = "hello";
console.log(x == y);
true
false
Explanation: In JavaScript, the == operator performs type coercion, meaning it converts the operands to a
common type before comparing them. In this case, x is a string primitive (“hello”) and y is a string object (new
String(“hello”)). When you use the == operator to compare them, JavaScript will convert y to a primitive value
using the toString() method, so the comparison becomes “hello” == “hello”, which is true.
On the other hand, the === operator performs a strict comparison without any type coercion. In this case, x and y
are of different types, so the comparison will always be false, even if their values are the same.
Q20 Find Output
let x = [];
let y = [];
let z = x + y;
console.log(typeof z);
string
Explanation: In JavaScript, when you use the + operator with two arrays, or an array and any other object, both
operands will be converted to strings before concatenation occurs. This is called implicit type coercion.
In this case, x and y are both empty arrays, which means that z will be the empty string (“”) because both arrays
will be converted to empty strings before concatenation.
Therefore, when you use the typeof operator to check the type of z, it will return “string” because z is a string.
Q21 Explain the difference between let, const, and var when declaring variables.
Ans. 1.var is function-scoped and hoisted to the top of the function or global context. It can be reassigned and used
before declaration. 2. let is block-scoped, meaning it's limited to the block it's declared in (e.g., inside a loop or an if
statement). It's not hoisted and can be reassigned. 3.const is also block-scoped but represents a constant value that
cannot be reassigned after initialization. It's not hoisted and should be used when the variable's value won't change.
Ans. You can write comments in JavaScript using two methods: Single-line comments using //, e.g., // This is a
comment. Multi-line comments using /* */
Ans. The console.log() method is used for debugging and logging messages to the browser's console. It's a helpful
tool for developers to inspect values, variables, and the flow of their code during development.
Ans. The typeof operator is used to determine the data type of a value or expression in JavaScript. It returns a string
representing the data type, such as "number", "string", "object", "function", or "undefined".
Ans. "You can create a function in JavaScript using the function keyword or by using arrow functions (introduced in
ES6). For example: Function declaration:
Javascript
function add(a, b) {
return a + b;
}
Arrow function:const add = (a, b) => a + b;
Q26. What is a JavaScript event handler, and how do you use it?
Ans. A JavaScript event handler is a function that responds to specific events, such as user interactions (e.g., clicks,
keypresses). You can attach event handlers to HTML elements using event attributes (e.g., onclick, onmouseover) or
through JavaScript code using methods like addEventListener().
Question 27. How do you select an HTML element in JavaScript using its id attribute?
Ans. You can select an HTML element by its id attribute using the getElementById() method, like this: const
element = document.getElementById('myElementId');
Ans. An anonymous function is a function that does not have a name. It can be defined and used without assigning it
a name. Anonymous functions are often used as callbacks or for immediately invoked function expressions
Question 29. How can you prevent the default behavior of an HTML form submit event?
Ans. To prevent the default behavior of an HTML form submit event, you can use the event.preventDefault()
method within an event handler. This prevents the form from being submitted, allowing you to perform custom
actions instead.
Ans. "You can concatenate strings in JavaScript using the + operator or the concat() method. Here are examples of
both methods: 1. Using the + operator:
Javascript
Q31 Output
Number 1: Odd
Number 2: Even
Number 3: Odd
Number 4: Even
Number 5: Odd
Ans. Scope refers to the context in which variables are declared and accessed. JavaScript has function scope and
block scope. Function scope means variables declared inside a function are only accessible within that function.
Block scope (introduced with let and const in ES6) restricts variable access to the block in which they are defined.
Q33 Among the following given JavaScript snipped codes, which is more efficient:
Code A
for(var number=10;number>=1;number--)
{
document.writeln(number);
}
Code B
var number=10;
while(number<=1)
{
document.writeln(number);
number++;
}
Answer: A
Explanation: Code 1 will be more efficient. In fact, the second code may encounter a runtime error because the value
of "number" is never going to be equal to or less than one.
Q34 In the following given syntax of the switch statement, the Expression is compared with the labels using which
one of the following operators?
switch(expression)
{
statements
}
In a switch statement in JavaScript, the expression is compared with the labels using the "strict equality" operator
(===). The strict equality operator (===) compares both value and type, ensuring that the expression matches a case
label exactly.
Question 15
What will happen, if the following JavaScript code is executed?
var count =0;
while (count <10)
{
console.log(count);
count++; }
The value of count from 0 to 9 is displayed in the console
Q36 Which of the following is the correct output for the following JavaScript code:
Int x=8;
if(x>9)
{
document.write(9);
}
else
{
document.write(x);
}
Error
Q37 How to empty an array ?
var ArrayList=[1,2,4,6];
//ArrayList=[]
//ArrayList.length=0;
//rrayList.splice(0,ArrayList.length);
/*While(ArrayList.length)
{
ArrayList.pop();
}
console.log(ArrayList);*/
Q39 What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How
can this pitfall be avoided?
Although typeof bar === "object" is a reliable way of checking if bar is an object, the surprising gotcha in
JavaScript is that null is also considered an object!
Therefore, the following code will, to the surprise of most developers, log true (not false) to the console:
var bar = null;
console.log(typeof bar === "object"); // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar is null:
console.log((bar !== null) && (typeof bar === "object")); // logs false
Q40 What will the code below output to the console and why? (function(){
var a = b = 3;
})();
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with
the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above
example.
However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b
= 3; to be shorthand for:
var b = 3;
var a = b;
But in fact, var a = b = 3; is actually shorthand for:
b = 3;
var a = b;
As a result (if you are not using strict mode), the output of the code snippet would be:
a defined? false
b defined? true
Q41 What is the significance, and what are the benefits, of including 'use strict' at the beginning of a
The short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing
and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored
or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.
Q42 What will be the output when the following code is executed? Explain.
console.log(false == '0')
true
false
Q43 Consider the code snippet below. What will the console output be and why?
( function ( x ){
return ( function ( y ){
console . log ( x );
})( 2 )
})( 1 );
An important feature of closures is that an inner function still has access to the outer function’s variables.
Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched
for a defined variable x , which is found to have a value of 1 .
Closure means that an inner function always has access to the vars and parameters of its outer function, even after
Q45. How do you add an element at the begining of an array? How do you add one at the end?
a[ 10 ]= 99 ;
It will not crash. The JavaScript engine will make array slots 3 through 9 be “empty slots.”
string
typeof 1 will return "number" and typeof "number" will return string.
Q47. What will the code below output to the console and why ?
Q49 What will the code below output? Explain your answer.
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);
Hide answer
An educated answer to this question would simply be: “You can’t be sure. it might print out 0.3 and true, or it might
not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the
expected results.”
The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out:
0.30000000000000004
false
The output is false because of the way computers represent floating-point numbers. In simple terms, computers use
a finite number of bits to store numbers with decimals, and this can lead to tiny errors in representation. When you
add 0.1 and 0.2 in JavaScript, the result is a tiny bit more than 0.3 due to these representation limitations. So, while
mathematically it should be equal to 0.3, in the computer's representation, it's a bit off, leading to false when you
check for equality using ==
Marquee is used for scrolling text on a web page. It scrolls the image or text up, down, left, or right automatically.
To apply for a marquee, you have to use </marquee> tags.
<br> tag – It is used to separate the line of text. It breaks the current line and shifts the flow of the text to a new
line.
<p> tag–This tag is used to write a paragraph of text.
<blockquote> tag–This tag is used to define large quoted sections.
Ordered list–The ordered list uses <ol> tag and displays elements in a numbered format.
Unordered list–The unordered list uses <ul> tag and displays elements in a bulleted format.
Definition list–The definition list uses <dl>, <dt>, <dd> tags and displays elements in definition form like in a
dictionary.
While indents can be helpful for visually organizing your HTML code, they don't actually affect the alignment of
list elements on the rendered webpage.
Here are the main ways to align list elements in HTML and CSS:
Q54. Are the HTML tags and elements the same thing?
No, HTML tags are used to define the structure of a web page, while HTML elements are made up of a set of tags
that define a specific part of a web page.
Void elements in HTML are tags that do not require a closing tag. They are used to insert images, line breaks, and
other content that does not require additional information.
Collapsing white space in HTML can help to reduce the size of web pages and make them load faster. It involves
removing unnecessary white space between HTML elements.
You can insert a copyright symbol by using © or © in an HTML file.
We use the anchor tag <a> to create a hyperlink in HTML that links one page to another page. The hyperlink can be
added to images too.
Semantic HTML is a coding style. It is the use of HTML markup to reinforce the semantics or meaning of the
content.
For example: In semantic HTML <b> </b> tag is not used for bold statement as well as <i> </i> tag is not used for
italic. Instead of these we use <strong></strong> and <em></em> tags.
Q60 What would happen if there is no text between the HTML tags?
There would be nothing to format if there is no text present between the tags. Therefore, nothing will appear on the
screen.
Some tags, such as the tags without a closing tag like the <img> tag, do not require any text between them.
The alt attribute is used for displaying a text in place of an image whenever the image cannot be loaded due to any
technical issue.
CSS
Q62.Why background and color are the separate properties if they should always be set together?
o The background property is indeed quite versatile. It can define color, image, position, size, repeat
style, and more. Combining it with a separate color property keeps stylesheets cleaner and easier to read
o You're correct that color inherits, meaning if you set a color for an element, its child elements will inherit
that color unless explicitly overridden. This is useful for creating consistent color schemes throughout a
page. On the other hand, background does not inherit
The universal selector matches the name of any of the element type instead of selecting elements of a specific type.
Q64 Name the property for controlling the image repetition of the background.
The background-repeat property repeats the background image horizontally and vertically. Some images are
repeated only horizontally or vertically.
The CSS float property is used to move the image to the right or left along with the texts to be wrapped around it. It
doesn't change the property of the elements used before it.
Q66 Explain the difference between visibility: hidden and display: none?
visibility: hidden hides the element, but it occupies space and affects the layout of the document.
Visibility: hidden:
Hides the element: The element becomes invisible to the user, but it still takes up space in the document flow.
Space allocation: The browser reserves space for the hidden element, affecting the layout of other elements around
it. Imagine a table with a hidden row; the empty space remains, potentially causing gaps or misalignments.
Accessibility: The element remains accessible to screen readers and other assistive technologies.
Use cases: Hiding elements temporarily for animations, showing/hiding content based on user
interaction, preserving layout for later display.
display: none also hides the element but not occupy space. It will not affect the layout of the document.
Display: none:
Removes the element: The element completely disappears from the document flow, both visually and in terms of
layout.
No space allocation: The browser ignores the element, as if it doesn't exist, so it doesn't affect the layout of other
elements.
Accessibility: The element becomes inaccessible to screen readers and assistive technologies.
Use cases: Temporarily removing elements that are not needed on the page, creating collapsible sections, hiding
elements for performance optimization.
GIT
A repository is a file structure where git stores all the project-based files. Git can either stores the files on the local
or the remote repository.
The command creates a copy (or clone) of an existing git repository. Generally, it is used to get a copy of the remote
repository to the local repository.
This command adds files and changes to the index of the existing directory.
You can add all changes at once using git add . command.
You can add files one by one specifically using git add <file_name> command.
You can add contents of a particular folder by using git add /<folder_name>/ command.
JAVASCRIPT
Q75. What are global variables? How are these variables declared, and what are the problems associated
with them?
In contrast, global variables are the variables that define outside of functions. These variables have a global
scope, so they can be used by any function without passing them to the function as parameters.
Intentional absence: Unlike undefined, which indicates a variable without a value assigned, null is explicitly
assigned to a variable to represent a lack of value.
Primitive data type: null is a primitive data type in JavaScript, similar to numbers, strings, and booleans.
Falsy value: In conditional statements, null is considered a "falsy" value, similar to 0, false, and "" (empty
string). This means it evaluates to false.
Set 1: React.js
1. Question: Explain the React component lifecycle and the methods associated with each phase.**
- *Answer: The React component lifecycle consists of three main phases: Mounting, Updating, and Unmounting.
Associated methods include `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`
respectively.*
2. **Question: How does React handle state management, and what are the differences between state and
props?**
- *Answer: React manages state through the `useState` hook or `this.state` in class components. State represents
the internal data of a component, while props are external inputs received from a parent component.*
3. **Question: Discuss the differences between functional components and class components in React. When
would you prefer one over the other?**
- *Answer: Functional components are simpler and more concise, while class components have additional features
like state and lifecycle methods. With the introduction of hooks in React 16.8, functional components became
preferable for most use cases.*
4. **Question: Elaborate on the concept of higher-order components (HOCs) in React and provide an
example of their usage.**
- *Answer: HOCs are functions that take a component and return a new component with enhanced functionality.
For example, a `withAuthentication` HOC could add authentication logic to a component.*
5. **Question: How does React Router work, and how would you implement client-side routing in a React
application?**
- *Answer: React Router enables client-side routing in a single-page application by rendering different
components based on the URL. It uses the `<Route>` component to define routes and the `<Link>` component for
navigation.*
- *Answer: CSS specificity determines which style rule takes precedence when there are conflicting styles. Inline
styles have the highest specificity, followed by IDs, classes, and element selectors.*
7. **Question: Explain the concept of responsive design in web development and how media queries are
utilized for achieving it.**
- *Answer: Responsive design ensures a seamless user experience across different devices and screen sizes. Media
queries in CSS are used to apply different styles based on conditions such as screen width, enabling developers to
create responsive layouts.*
8. **Question: Discuss the advantages and disadvantages of using CSS frameworks like Bootstrap in web
development.**
- *Answer: CSS frameworks like Bootstrap provide pre-built components and styles, saving development time.
However, they may introduce unnecessary styles and increase the overall file size. Customization can also be
limited.*
9. **Question: How do CSS Flexbox and CSS Grid differ, and in what scenarios would you prefer using one
over the other?**
- *Answer: Flexbox is designed for one-dimensional layouts, such as a row or column, while Grid is for two-
dimensional layouts with rows and columns. Flexbox is suitable for components within a layout, while Grid is ideal
for overall page structure.*
10. **Question: Describe the purpose and usage of CSS preprocessors (e.g., Sass or Less) in web
development.**
- *Answer: CSS preprocessors enhance the functionality of CSS by introducing variables, nesting, and functions.
They allow developers to write more maintainable and modular styles, which can be compiled into standard CSS for
browser compatibility.*
Set 3: Git
11. **Question: Can you explain the difference between a git commit and a git push? What happens during
each operation?**
- *Answer: `git commit` records changes to the local repository, creating a new commit. `git push` then uploads
these commits to a remote repository, making them accessible to others.*
12. **Question: In a scenario where you accidentally commit sensitive information, how would you remove it
from the Git history?**
- *Answer: You can use `git filter-branch` or `git filter-repo` to remove sensitive information from the Git history.
It involves creating a new commit history without the sensitive data.*
13. **Question: How does Git handle conflicts during a merge operation, and what strategies can be
employed to minimize conflicts in a collaborative environment?**
- *Answer: Git marks conflicting changes and asks the user to resolve them. Minimizing conflicts involves
regularly pulling changes, creating feature branches, and communicating with team members to avoid overlapping
modifications.*
14. **Question: Explain the concept of Git submodules and provide a use case where they might be
beneficial.**
- *Answer: Git submodules allow including external Git repositories within another repository. This is useful
when you want to use a specific version of an external library in your project.*
15. **Question: Discuss the purpose and advantages of Git hooks in the software development process.
Provide examples of scenarios where Git hooks can be useful.**
- *Answer: Git hooks are scripts that run automatically at certain points in the Git workflow. Examples include
pre-commit hooks to run tests before a commit and post-receive hooks for triggering deployment scripts after
receiving changes.*