0% found this document useful (0 votes)
5 views12 pages

CSS and JavaScript Q&A Guide

The document provides detailed explanations for CSS and JavaScript questions, covering topics such as pseudo-classes, grid layout, flexbox, event handling, and JavaScript functions. Each question includes an analysis, code examples, and the correct answers. The CSS section addresses questions 15-24, while the JavaScript section covers questions 29-50.

Uploaded by

karangadekar00
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

CSS and JavaScript Q&A Guide

The document provides detailed explanations for CSS and JavaScript questions, covering topics such as pseudo-classes, grid layout, flexbox, event handling, and JavaScript functions. Each question includes an analysis, code examples, and the correct answers. The CSS section addresses questions 15-24, while the JavaScript section covers questions 29-50.

Uploaded by

karangadekar00
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Explain remaining all

Here are detailed explanations for all the remaining questions (Questions 15-24 for CSS and
Questions 29-50 for JavaScript) that were mentioned but not fully detailed in the previous
response:

CSS Questions (Continued)


Question 15: Keyboard Focus Pseudo-class
Question: Which pseudo-class applies only to keyboard navigation focus?
Analysis: The :focus pseudo-class applies when an element receives focus through any
method (mouse click, keyboard navigation, etc.). However, :focus-visible is specifically
designed to show focus indicators only when the browser determines it would be helpful for
accessibility, which is primarily during keyboard navigation. [1]
Code Example:
button:focus-visible {
outline: 2px solid blue;
}
/* This outline only shows when navigating with Tab key, not on mouse click */

Correct Answer: :focus-visible.

Question 16: CSS Grid fr Unit


Question: In a 600px tall grid container with grid-template-rows: 1fr 2fr auto;, which row
will receive the most height?
Analysis: The fr (fractional) unit distributes available space proportionally. The auto row
takes only the space needed for its content. The remaining space is divided between 1fr
and 2fr in a 1:2 ratio, so the second row gets twice as much space as the first. [1]
Code Example:
.grid-container {
height: 600px;
display: grid;
grid-template-rows: 1fr 2fr auto;
}
/* If auto row needs 60px, remaining 540px is split 1:2 (180px : 360px) */

Correct Answer: The Second Row receives the most height.


Question 17: Descendant Selector
Question: Which is the correct syntax to select all span elements inside a div element?
Analysis: The descendant combinator uses a space between selectors. It selects all
elements that are descendants (children, grandchildren, etc.) of another element. [1]
Code Examples:
/* Correct - descendant selector */
div span { color: red; }

/* Incorrect alternatives */
div > span { } /* Direct child only */
div + span { } /* Next sibling */
div ~ span { } /* General sibling */

Correct Answer: div span.

Question 18: opacity Property


Question: What is the effect of opacity: 0.5; on an element?
Analysis: The opacity property affects the transparency of the entire element, including its
background, borders, and all content. Unlike setting color: rgba() which only affects text,
opacity makes everything semi-transparent. [1]

Code Example:
.semi-transparent {
opacity: 0.5; /* 50% transparent */
background-color: red;
color: black;
}
/* Both background AND text become 50% transparent */

Correct Answer: The entire element (background + text) becomes semi-transparent.

Question 19: Flexbox order Property


Question: Given flex items with order: 2 and order: 1, what will be the visual order?
Analysis: The order property controls the visual sequence of flex items regardless of their
HTML source order. Items are arranged in ascending order of their order values. [1]
Code Example:
<div class="flex-container">
<div class="item1" style="order: 2;">One</div>
<div class="item2" style="order: 1;">Two</div>
</div>

.flex-container { display: flex; }


/* Visual order: "Two" (order: 1) then "One" (order: 2) */
Correct Answer: "Two" then "One" (ascending by order value).

Question 20: Selecting First Paragraph in a Section


Question: How would you write a CSS rule to apply a red background only to the first
paragraph inside each section?
Analysis: The :first-of-type pseudo-class selects the first element of its type among
siblings. For targeting the first <p> within each <section>, this ensures only the first
paragraph gets styled. [1]
Code Example:
section p:first-of-type {
background-color: red;
}
/* Alternative with :first-child if <p> is always first */
section p:first-child {
background-color: red;
}

Correct Answer: section p:first-of-type { background-color: red; }.

Question 21: Responsive Grid with auto-fit


Question: What does grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); do?

Analysis: This creates a responsive grid that automatically adjusts the number of columns
based on available space. auto-fit creates as many columns as can fit, while minmax(200px,
1fr) ensures each column is at least 200px wide but can grow to fill extra space. [1]

Code Example:
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
}
/* On 800px container: 4 columns of 200px each
On 1200px container: 4 columns of 300px each (grows to fill) */

Correct Answer: Creates as many columns as fit, each at least 200px, can grow.

Question 22: ::before and ::after Content


Question: What text will be rendered for <p class="text">Hello</p> with ::before content
"Start" and ::after content "End"?
Analysis: Pseudo-elements ::before and ::after insert content before and after the
element's main content, respectively. They become part of the element's rendered content.
[1]

Code Example:
.text::before {
content: "Start";
}
.text::after {
content: "End";
}
/* <p class="text">Hello</p> renders as: StartHelloEnd */

Correct Answer: "StartHelloEnd".

Question 23: flex: 0 1 auto


Question: What is the result of setting flex: 0 1 auto on a flex item?
Analysis: This is shorthand for flex-grow: 0 (won't grow), flex-shrink: 1 (can shrink), and
flex-basis: auto (size based on content). The item maintains its content size but can shrink
if space is limited. [1]
Code Example:
.flex-item {
flex: 0 1 auto;
/* Equivalent to: */
flex-grow: 0; /* Won't grow larger */
flex-shrink: 1; /* Can shrink if needed */
flex-basis: auto; /* Size based on content */
}

Correct Answer: It doesn't grow but can shrink if needed.

Question 24: Absolute Positioning Context


Question: What will be the position of .box with position: absolute inside .container with
position: relative?

Analysis: Absolutely positioned elements are positioned relative to their nearest positioned
ancestor (any element with position other than static). The .container with position:
relative becomes the positioning context. [1]

Code Example:
.container {
position: relative;
width: 300px;
height: 200px;
}
.box {
position: absolute;
top: 20px;
left: 20px;
}
/* .box is positioned 20px from top and left edges of .container */

Correct Answer: The box will be positioned relative to the .container.


JavaScript Questions (29-50)
Question 29: this in Regular vs. Arrow Functions
Question: What's the output when calling a regular function and an arrow function from an
object?
Code:
const obj = {
id: 42,
fn1: function() { return [Link]; },
fn2: () => [Link]
};
[Link](obj.fn1(), obj.fn2());

Analysis: Regular functions have dynamic this binding - when called as obj.fn1(), this
refers to obj. Arrow functions inherit this from their lexical scope (the global scope here),
where [Link] is undefined.
Correct Answer: 42 and undefined.

Question 30: setTimeout and the Event Loop


Question: What will be logged by [Link](count) in the given snippet?
Code:
let count = 0;
function increment() {
count++;
setTimeout(increment, 1000);
}
increment();
[Link](count);

Analysis: The first increment() call executes synchronously, setting count to 1. The
setTimeout schedules the next call for later but doesn't block execution. [Link](count)
runs immediately after the synchronous execution, when count is 1.
Correct Answer: 1.

Question 31: Shallow Copying an Array


Question: Which option correctly creates a shallow copy of an array?
Analysis: Several methods create shallow copies of arrays. slice() with no arguments is a
classic method. The spread operator [...arr] is modern. [Link](arr) also works.
Simply let copy = arr only copies the reference, not the array.
Code Examples:
const arr = [1, 2, 3];
const copy1 = [Link](); // ✓ Shallow copy
const copy2 = [...arr]; // ✓ Shallow copy
const copy3 = [Link](arr); // ✓ Shallow copy
const copy4 = arr; // ✗ Reference copy

Correct Answer: let copy = [Link]();.

Question 32: Duplicate Keys in Object Literals


Question: What is the output for const obj = { a: 1, b: 2, a: 3 };?

Analysis: When an object literal has duplicate property keys, the last declaration overwrites
previous ones. This is valid JavaScript syntax.
Code:
const obj = { a: 1, b: 2, a: 3 };
[Link](obj); // { a: 3, b: 2 }

Correct Answer: {a: 3, b: 2}.

Question 33: Disabling Click Events


Question: Which CSS property can be used to disable click events on an element?
Analysis: The pointer-events: none CSS property makes an element non-interactive to all
pointer events, including clicks, hovers, and touches. Events will pass through to elements
behind it.
Code Example:
.disabled {
pointer-events: none;
/* Element becomes non-clickable */
}

Correct Answer: pointer-events: none;.

Question 34: Event Loop Order (Microtasks vs. Macrotasks)


Question: What is the output order for code involving setTimeout and [Link]()?
Code:
[Link]('start');
setTimeout(() => [Link]('timeout 1'), 0);
[Link]().then(() => [Link]('promise 1'));
setTimeout(() => [Link]('timeout 2'), 0);
[Link]().then(() => [Link]('promise 2'));
[Link]('end');

Analysis: JavaScript execution follows this order: 1) Synchronous code, 2) Microtasks


(Promise callbacks), 3) Macrotasks (setTimeout callbacks).
Correct Answer: start, end, promise 1, promise 2, timeout 1, timeout 2.
Question 35: [Link]() Method
Question: What does the [Link]() method do?
Analysis: [Link]() is a built-in method that converts a JSON string into a JavaScript
value (object, array, string, number, boolean, or null).
Code Example:
const jsonString = '{"name": "John", "age": 30}';
const obj = [Link](jsonString);
[Link](obj); // { name: "John", age: 30 }

Correct Answer: Parses JSON to a JavaScript value.

Question 36: Prototype Inheritance


Question: What is the output of calling a method added to a constructor's prototype?
Code:
function A() {}
[Link] = function() { return "Hi"; };
const obj = new A();
[Link]([Link]());

Analysis: When [Link]() is called, JavaScript doesn't find greet on obj itself, so it looks
up the prototype chain to [Link] where it finds the method.
Correct Answer: Hi.

Question 37: let and the Temporal Dead Zone (TDZ)


Question: What is the output when a function accesses a variable re-declared with let?
Code:
let anime = 'Naruto';
function getAnime() {
[Link](anime); // TDZ violation
let anime = 'Demon Slayer';
}
getAnime();

Analysis: The let anime declaration inside getAnime creates a block-scoped variable that
shadows the outer one. Accessing it before the declaration line results in a ReferenceError
due to the Temporal Dead Zone.
Correct Answer: ReferenceError.

Question 38: setTimeout in a for loop with let


Question: What is the output of setTimeout with [Link](i) inside a for loop using let?
Code:
for (let i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100);
}

Analysis: Using let creates a new block scope for each iteration. Each setTimeout callback
captures the value of i from its specific iteration, creating closures over different values.
Correct Answer: 0, 1, 2.

Question 39: async/await and Event Loop


Question: Predict the output of the script with async/await and promises.
Code:
[Link]('script start');
async function foo() {
[Link]('foo start');
await [Link]();
[Link]('foo end');
}
foo();
[Link]().then(() => [Link]('promise'));
[Link]('script end');

Analysis: await pauses the function and schedules the continuation as a microtask. All
synchronous code runs first, then microtasks are processed in order.
Correct Answer: script start, foo start, script end, foo end, promise.

Question 40: Type Coercion


Question: What is the output of [Link](2 + '2' - 2)?

Analysis: JavaScript evaluates left to right. 2 + '2' performs string concatenation (result:
'22'). Then '22' - 2 performs numeric subtraction, coercing '22' to 22, resulting in 20.

Code:
[Link](2 + '2' - 2);
// Step 1: 2 + '2' = '22' (concatenation)
// Step 2: '22' - 2 = 20 (numeric coercion and subtraction)

Correct Answer: 20.

Question 41: ES Module Exports


Question: Given export const value = 10;, what is true?
Analysis: This is a named export. To import it, you must use the destructuring syntax with
the exact name.
Code Example:
// [Link]
export const value = 10;

// [Link]
import { value } from './[Link]'; // ✓ Correct
import value from './[Link]'; // ✗ Incorrect (default import)

Correct Answer: You can import as: import { value } from './[Link]'.

Question 42: Promise Chaining with .catch


Question: What will the promise chain print?
Code:
[Link](1)
.then(x => x + 1)
.then(x => { throw new Error("Oops"); })
.catch(err => [Link]([Link]));

Analysis: The chain resolves to 1, then 2, then throws an error. The .catch() handles the
rejection and logs the error's message property.
Correct Answer: Oops.

Question 43: JavaScript Video Control


Question: How can we play/pause a video using JavaScript?
Analysis: HTML5 video elements provide .play() and .pause() methods for programmatic
control.
Code Example:
const video = [Link]('video');
[Link](); // Start playback
[Link](); // Stop playback

Correct Answer: [Link]('video').play() and


[Link]('video').pause().

Question 44: Set Object for Uniqueness


Question: What is the output of new Set()? [2] [3] [4] [1]

Analysis: A Set automatically removes duplicate values while preserving insertion order of
unique values.
Code:
const set = new Set([1, 4, 3, 2, 1, 1, 2, 3, 4]);
[Link](set); // Set {1, 4, 3, 2}

Correct Answer: {1, 4, 3, 2}.


Question 45: Rest Parameter Syntax
Question: What is the output of a function with incorrect rest parameter placement?
Code:
function getElements(firstElement, ...elements, secondElement) {
return elements;
}

Analysis: Rest parameters (...elements) must be the last parameter in a function definition.
Placing another parameter after it violates JavaScript syntax rules.
Correct Answer: SyntaxError.

Question 46: this in Event Listeners


Question: What happens when you add an event listener that alerts [Link]?
Code:
[Link]('btn').addEventListener('click', function() {
alert([Link]);
});

Analysis: In regular function event handlers, this is automatically bound to the element that
triggered the event.
Correct Answer: Alerts "btn".

Question 47: Arrow Functions and this


Question: Which statement about arrow functions is true?
Analysis: Arrow functions don't have their own this binding. Instead, they lexically inherit
this from the enclosing scope where they were defined.

Code Example:
const obj = {
name: 'Object',
regular: function() { return [Link]; }, // Dynamic this
arrow: () => [Link] // Lexical this
};

Correct Answer: They inherit this from the parent scope.

Question 48: Return Value of [Link]()


Question: What is the output of code involving [Link]()?
Code:
let array = [1, 2, 3].push(4);
[Link]([Link](5));
Analysis: The .push() method returns the new length of the array, not the array itself. So
array becomes 4 (the length), and calling .push() on a number causes an error.

Correct Answer: Error (TypeError: [Link] is not a function).

Question 49: Event Delegation


Question: What is the primary advantage of using event delegation?
Analysis: Event delegation places a single listener on a parent element instead of multiple
listeners on children. It leverages event bubbling to handle events efficiently and
automatically works with dynamically added elements.
Code Example:
// Instead of this (multiple listeners):
[Link](btn => [Link]('click', handler));

// Use this (single delegated listener):


[Link]('click', (e) => {
if ([Link]('button')) handler(e);
});

Correct Answer: It reduces the number of event listeners in the application.

Question 50: [Link]() with Implicit Return


Question: What is logged from the .map() operation?
Code:
const result = [1, 2, 3].map(n => {
if (n === 2) return;
return n * 2;
});
[Link](result);

Analysis: The .map() method creates a new array from return values. For n = 1: returns 2.
For n = 2: executes return; which implicitly returns undefined. For n = 3: returns 6.
Correct Answer: [2, undefined, 6].

This completes the detailed analysis of all remaining questions from both versions of the test,
covering fundamental concepts in HTML, CSS, and JavaScript with practical code examples
and comprehensive explanations.

1. [Link]
2. [Link]
3. [Link]
4. [Link]

Common questions

Powered by AI

repeat(auto-fit, minmax(200px, 1fr)) is used in CSS Grid to create a flexible, responsive layout where the number of columns adjusts depending on the container's size. auto-fit fills the grid with as many tracks as can fit based on available space, while each track retains a minimum width of 200px but can expand (1fr) if more space is available. This makes the layout responsive to viewport changes, maintaining usability across devices.

The event loop processes synchronous code first, then microtasks (from Promises), and finally macrotasks (from setTimeout). In the example, initial synchronous code executes first, logging 'start' and 'end'. Promise.then() handlers, classified as microtasks, execute next, before setTimeout callbacks as macrotasks. This sequencing highlights JavaScript's prioritization of shorter-lived tasks (microtasks) before longer tasks (macrotasks), ensuring efficient execution.

The order property determines the visual sequence of flex items, allowing us to alter the default source order. By default, items have an order value of 0, but changing this value will rearrange items in ascending order based on their order values rather than their placement in the HTML. Hence, items with lower order values appear first.

repeat(auto-fit, minmax(200px, 1fr)) configures the grid to automatically fit as many columns within the available space as possible, while each column adapts between a minimum width of 200px and expanding to equally fill the container using available space (1fr). During resizing, the grid recalculates the ideal number of columns and sizes dynamically, preserving layout structure and fluidity on varying screen sizes.

JSON.parse() converts a JSON string into the respective JavaScript object or value, able to handle objects, arrays, strings, numbers, booleans, and null from JSON format. Providing a well-structured JSON string results in the equivalent JavaScript structure, preserving all types except functions and undefined.

The TDZ is a behavior of let and const where variables are in a 'dead zone' from the start of their scope until they are initialized. Accessing such variables before initialization results in a ReferenceError. This prevents the use of variables before their declaration and initialization, ensuring that code follows a logical and predictable sequence.

JavaScript follows specific rules for type coercion: 2 + '2' concatenates to '22' due to '2' being a string, placing precedence on string conversion. Subsequently, '22' - 2 coerces '22' back to a number for subtraction, yielding 20. This behavior illustrates JavaScript's dynamic coercion depending on operation types, showcasing its flexibility yet potential for unintended consequences.

In a regular function, 'this' refers to the object it was called on if invoked using object.method(). Therefore, in the context of obj.fn1(), 'this' points to obj. However, for arrow functions, 'this' is lexically bound to the scope where the function is defined, typically the global scope if not explicitly bound. Thus, obj.fn2() results in 'this' being the global object or undefined in strict mode.

opacity: 0.5; in CSS impacts the transparency of an element as a whole—its content, background, and borders are made 50% transparent. This differs from properties like color, which affect only the text color without impacting element's overall transparency. Opacity allows for consistent visual effects, but requires understanding of how underlying elements may also become visible.

Event delegation leverages the event bubbling phase, combining a single event listener at a common ancestor to manage events for child elements. This reduces memory usage and enhances performance, particularly in dynamic environments where elements are added post-load. The parent listens for events from children, using conditions or selectors to decide actions. This approach eliminates the need for separate listeners on specific target elements, simplifying maintenance and improving scalability.

You might also like