FrontEnd - FAQs - Part 1
Front End FAQS – Part 1
HTML
1. What
is HTML?
Answer :HTML (Hypertext Markup Language) is a
markup language used to create and structure content for the web. HTML code
consists of a series of tags that define different elements, such as headings,
paragraphs, images, links, and more. HTML is the backbone of the web and is
used in conjunction with CSS and JavaScript to create dynamic and interactive
web pages.
Answer :The latest version of HTML is HTML5.
Answer :
<html>: This tag indicates the start of an HTML
document.
<head>: This tag contains meta information about
the document, such as the page title and links to CSS files.
<title>: This tag specifies the title of the
document, which appears in the browser tab.
<body>: This tag contains the visible content of
the document.
<h1>, <h2>, <h3>, <h4>,
<h5>, <h6>: These tags specify headings of different levels.
<p>: This tag specifies a paragraph of text.
<a>: This tag creates a hyperlink to another page
or website.
<img>: This tag embeds an image in the document.
Answer : HTML and XHTML are both markup languages
used for creating web pages. The main difference between the two is that XHTML
is stricter in its syntax and requires well-formed XML code, while HTML is more
lenient and allows for more flexible syntax. XHTML also requires closing tags
for all elements, while in HTML some tags can be left unclosed. However, in
practice, HTML and XHTML are very similar, and most modern web browsers treat both
as interchangeable.
Answer :A DOCTYPE declaration is a statement at
the beginning of an HTML document that specifies which version of HTML or XHTML
the document is written in. The DOCTYPE declaration tells the web browser which
rules to follow when rendering the page, such as which tags are allowed and how
they should be interpreted. For example, the DOCTYPE declaration for HTML5 is:
<!DOCTYPE
html>
Answer : Semantic HTML is a practice of using HTML
tags to convey the meaning and structure of the content, rather than just its
appearance. Semantic HTML helps search engines and assistive technologies
understand the content of the web page better, and makes the code more readable
and maintainable. For example, instead of using a <div> tag to create a
block of content, it is better to use a semantic tag such as <article>,
<section>, or <aside>, depending on the purpose of the content.
<section>
<h2>What is Semantic HTML?</h2>
<p>Semantic HTML is the practice of
using HTML tags to convey the meaning and structure of the content.</p>
</section>
7. What
is an HTML element?
Answer : An HTML element is a basic building block
of an HTML document. An element is defined by a start tag, content, and an end
tag, and may also have attributes that provide additional information about the
element. Examples of HTML elements include headings (<h1>, <h2>,
etc.), paragraphs (<p>), images (<img>), links (<a>), tables
(<table>), and more.
<h1>This
is a heading</h1>
Answer : An HTML attribute, on the other hand, is
a modifier that provides additional information about an element. Attributes
are used to customize the behavior or appearance of an element, such as setting
the color of text or specifying the target of a link.
<a
href="https://www.google.com"
target="_blank">Google</a>
Answer : An HTML tag is a code that is used to
define an HTML element, while an HTML attribute is a code that is used to
provide additional information about an HTML element. Tags are used to define
the structure and content of the document, while attributes are used to modify
the behavior or appearance of an element.
<img
src="example.jpg" alt="Example Image">
In this example, the <img> tag is used to embed an
image in the document, and the "src" and "alt" attributes
are used to specify the source URL of the image and provide alternative text
for users who cannot see the image.
Answer : An ordered list is a list of items where
each item is numbered, while an unordered list is a list of items where each
item is marked with a bullet point or other marker. The <ol> tag is used
to create an ordered list, and the <ul> tag is used to create an unordered
list.
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item
3</li>
</ul>
11. What
is a form in HTML?
Answer : A form is an HTML element that is used to
collect data from the user. Forms can contain various types of input elements,
such as text boxes, radio buttons, checkboxes, and more. When the user submits
the form, the data is sent to a server for processing. Forms are commonly used
in web applications for user registration, login, and data entry.
<label
for="username">Username:</label>
<input type="text"
id="username" name="username"><br><br>
<label
for="password">Password:</label>
<input
type="password" id="password"
name="password"><br><br>
<input type="submit"
value="Submit">
</form>
In this example, the <form> element is used to
create a form, and the "action" and "method" attributes are
used to specify where the data should be sent and how it should be sent. The
form contains two input elements for the username and password, and a submit
button to submit the form. When the user clicks the submit button, the data is
sent to the server via a POST request.
Answer : An HTML entity is a special code that is
used to represent a character that has a special meaning in HTML, such as <,
>, &, ", and '. Entities are used to ensure that the special
characters are displayed properly in the browser, even if they are part of the
content of the web page.
<Hello>
& “world”
Answer : The <div> element is used to group
block-level elements together, while the <span> element is used to group
inline elements together. Block-level elements take up the entire width of
their container and create a new line after themselves, while inline elements
only take up as much width as necessary and do not create a new line.
<div>
<h1>Hello</h1>
<p>This is a paragraph.</p>
</div>
<span>
<b>This is bold text.</b>
<i>This is italic text.</i>
</span>
In this example, the <div> element is used to group
the <h1> and <p> elements together, while the <span> element
is used to group the <b> and <i> elements together. When rendered
in a browser, the code above will display as:
This is a paragraph.
CSS
Answer : CSS (Cascading Style Sheets) is a style
sheet language that is used to define the presentation of a web page. CSS is
used to style HTML elements, such as changing the font size, color, background,
and layout of the content.
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
text-align: center;
}
p {
font-family: Arial, sans-serif;
font-size: 16px;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<h1>My Web Page</h1>
<p>This is a paragraph of
text.</p>
<p class="highlight">This
paragraph has a yellow background.</p>
</body>
</html>
In this example, CSS is used to style the <h1> and
<p> elements. The color and text alignment of the <h1> element are
changed using the "color" and "text-align" properties, while
the font family and size of the <p> element are changed using the
"font-family" and "font-size" properties. The <p>
element with the "highlight" class is given a yellow background using
the ".highlight" selector and the "background-color"
property.
Answer : Padding is the space between the content
of an element and its border, while margin is the space between the border of
an element and the adjacent elements. Padding is used to add space inside an
element, while margin is used to add space outside an element.
div {
width: 200px;
height: 100px;
border: 1px solid black;
padding: 20px;
margin: 50px;
}
In this example, a <div> element is styled with a
width and height of 200px and 100px, a black border of 1px, 20px of padding,
and 50px of margin. When rendered in a browser, the <div> element will be
displayed with a total width of 340px (200px for the width, 20px of padding on
each side, and 50px of margin on each side).
Answer : The box model in CSS is a way of
representing the layout of an element on a web page. It consists of four
layers: content, padding, border, and margin. The content layer is where the
text or images of an element are displayed. The padding layer is the space
between the content and the border. The border layer is a line that surrounds
the content and padding. The margin layer is the space between the border and
the adjacent elements.
div {
width: 200px;
height: 100px;
padding: 20px;
border: 1px solid black;
margin: 50px;
}
In this example, a <div> element is styled with a
width and height of 200px and 100px, respectively, 20px of padding, a black border
of 1px, and 50px of margin. When rendered in a browser, the <div> element
will be displayed with a total width of 340px (200px for the width, 20px of
padding on each side, a 1px border on each side, and 50px of margin on each
side).
Bootstrap
Answer : Bootstrap is a popular front-end
framework that is used to build responsive and mobile-first web pages.
Bootstrap provides a set of CSS and JavaScript files that contain pre-built
styles and components, such as buttons, forms, and navigation menus, that can
be easily added to a web page.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div
class="container">
<h1>My Web Page</h1>
<p>This
is a paragraph of text.</p>
<button type="button"
class="btn btn-primary">Click me</button>
</div>
</body>
</html>
In this example, Bootstrap is used to style the web page
with a container class, a heading element, a paragraph element, and a button
element. The button element is styled with the "btn" and
"btn-primary" classes to give it a blue color and a rounded border.
When rendered in a browser, the code above will display as:
My Web Page
This is a paragraph of text.
Click me
JavaScript
Answer : JavaScript is a programming language that
is used to create dynamic and interactive web pages. JavaScript can be used to
add functionality to a web page, such as creating animations, validating forms,
and handling user input.
<!DOCTYPE html>
<html>
<body>
<button
onclick="alert('Hello World!')">Click me</button>
</body>
</html>
In this example, JavaScript is used to create an alert box
that pops up when the button is clicked. The onclick event handler is used to
execute the alert function when the button is clicked. When rendered in a
browser, the code above will display a button that says "Click me".
When the button is clicked, an alert box will pop up with the message
"Hello World!".
Answer : An event in JavaScript is an action or
occurrence that takes place on a web page, such as a user clicking a button,
scrolling the page, or submitting a form. JavaScript can be used to respond to
events by executing code in response to the event.
<!DOCTYPE html>
<html>
<body>
<button
onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert("Hello World!");
}
</script>
</body>
</html>
In this example, JavaScript is used to create a function
called "myFunction" that displays an alert box when called. The
function is then called in response to the onclick event of the button element.
When rendered in a browser, the code above will display a button that says
"Click me". When the button is clicked, an alert box will pop up with
the message "Hello World!".
Answer : The DOM (Document Object Model) in
JavaScript is a representation of a web page as a hierarchical tree of objects.
Each object in the tree represents an element on the web page, such as a
paragraph, a button, or an image. JavaScript can be used to access and
manipulate the properties and content of these objects, allowing for dynamic
and interactive web pages.
<!DOCTYPE html>
<html>
<body>
<p id="demo">This
is a paragraph of text.</p>
<script>
var x =
document.getElementById("demo");
x.style.color =
"red";
x.innerHTML = "Hello
World!";
</script>
</body>
</html>
In this example, JavaScript is used to access a <p>
element on the web page with the id "demo". The color style property
of the element is then changed to red, and the content of the element is
changed to "Hello World!" using the innerHTML property. When rendered
in a browser, the code above will display a paragraph of text that says,
"Hello World!" in red font.
Answer : AJAX (Asynchronous JavaScript and XML) in
JavaScript is a technique for making asynchronous requests to a web server from
a web page, without requiring the page to reload. AJAX can be used to retrieve
data from a server, update a portion of a web page, or submit data to a server.
<!DOCTYPE html>
<html>
<body>
<div
id="demo">
<button
type="button" onclick="loadDoc()">Click
me</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 &&
this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET",
"ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
In this example, JavaScript is used to create a function
called "loadDoc" that makes an AJAX request to retrieve data from a
text file called "ajax_info.txt". When the response is received from
the server, the content of the <div> element with the id "demo"
is updated with the response using the innerHTML property. When rendered in a
browser, the code above will display a button that says "Click me".
When the button is clicked, the content of the <div> element will be
replaced with the content of the "ajax_info.txt" file.
Answer : A callback function in JavaScript is a
function that is passed as an argument to another function and is called by
that function. Callback functions can be used to create asynchronous code,
handle events, and pass data between functions.
Example code for using a callback function in JavaScript:
function multiply(a, b,
callback) {
var result = a * b;
callback(result);
}
function
displayResult(result) {
console.log("The
result is: " + result);
}
multiply(5, 10,
displayResult);
In this example, JavaScript is used to create two
functions: "multiply" and "displayResult". The
"multiply" function takes two numbers and a callback function as
arguments, multiplies the numbers together, and then calls the callback
function with the result as an argument. The "displayResult" function
is used as the callback function, and simply logs the result to the console.
When the "multiply" function is called with the arguments 5, 10, and
"displayResult", the "displayResult" function is called with
the result of 50 as an argument, and logs "The result is: 50" to the
console.
Answer : A closure in JavaScript is a function
that has access to variables in its outer (enclosing) function, even after the
outer function has returned. Closures can be used to create private variables
and functions, and to create functions with state.
Example code for using a closure in JavaScript:
function counter() {
var count = 0;
function increment() {
count++;
console.log(count);
}
return increment;
}
var myCounter = counter();
myCounter(); // logs 1
myCounter(); // logs 2
myCounter(); // logs 3
1
2
3
Answer : A Promise in JavaScript is an object that
represents the eventual completion (or failure) of an asynchronous operation
and its resulting value. Promises provide a way to handle asynchronous code
that is more readable and maintainable than traditional callback functions.
Example code for using a Promise in JavaScript:
function getData() {
return new
Promise(function(resolve, reject) {
var data =
fetchDataFromServer();
if (data) {
resolve(data);
} else {
reject("Failed to
fetch data.");
}
});
}
getData()
.then(function(data) {
console.log("Data
received:", data);
})
.catch(function(error) {
console.log("Error
occurred:", error);
});
In this example, JavaScript is used to create a function
called "getData" that returns a Promise object. Inside the Promise,
an asynchronous operation is performed to fetch data from a server, and if the
operation is successful, the Promise is resolved with the data. If the
operation fails, the Promise is rejected with an error message. The Promise is
then used with the "then" and "catch" methods to handle the
resolved value or the rejected error, respectively.
Answer : An event in JavaScript is an action or
occurrence that happens in the browser, such as a user clicking a button, a
page finishing loading, or a timer running out. JavaScript can be used to
respond to events by attaching event listeners to elements on a web page.
Example code for using an event in JavaScript:
<!DOCTYPE html>
<html>
<body>
<button
onclick="displayMessage()">Click me</button>
<script>
function displayMessage()
{
alert("Button clicked!");
}
</script>
</body>
</html>
In this example, JavaScript is used to create a function
called "displayMessage" that displays an alert when called. The
function is attached to a button element on a web page using the
"onclick" attribute. When the button is clicked, the
"displayMessage" function is called and the alert is displayed.
Answer : Event bubbling and capturing in
JavaScript are two mechanisms for handling events that occur on nested HTML
elements. Event bubbling is the default behavior in which the event is first
captured by the innermost element and then propagated up through its ancestors.
Event capturing is the opposite behavior, where the event is captured first by
the outermost element and then propagated down through its descendants.
<!DOCTYPE html>
<html>
<body>
<div
id="outer" style="padding: 20px; background-color:
red;">
<div id="inner"
style="padding: 20px; background-color: green;">
<button id="button"
style="padding: 20px; background-color: blue;">Click
me</button>
</div>
</div>
<script>
document.getElementById("outer").addEventListener("click",
function() {
console.log("Outer clicked.");
}, true);
document.getElementById("inner").addEventListener("click",
function() {
console.log("Inner clicked.");
}, true);
document.getElementById("button").addEventListener("click",
function() {
console.log("Button clicked.");
}, true);
</script>
</body>
</html>
In this example, JavaScript is used to attach event
listeners to three elements on a web page: an outer <div> element with a
red background, an inner <div> element with a green background, and a
button element with a blue background. The event listeners use the
"addEventListener" method and have a third parameter set to
"true", which enables event capturing.
If the button is clicked, the output of this code would
be:
Button clicked.
Inner clicked.
Outer clicked.
Answer : In JavaScript, "==" and
"===" are both comparison operators that can be used to check if two
values are equal. However, "==" is a loose equality comparison
operator that allows type coercion, while "===" is a strict equality
comparison operator that does not allow type coercion.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
In this example, the "==" operator is used to compare the number 5 to the string "5". Because JavaScript performs type coercion when using "==", the two values are considered equal and the output is "true". However, when using the "===" operator, the two values are not equal because they have different types, and the output is "false".
27. What is a closure in JavaScript?
A closure in JavaScript is a function that has access to
variables in its outer (enclosing) scope, even after the outer function has
returned. Closures are a powerful feature of JavaScript that can be used to
create private variables and methods, as well as to implement functional
programming concepts such as currying and partial application.
Example code for using a closure in JavaScript:
function makeCounter() {
var count = 0;
return function() {
count++;
console.log(count);
};
}
var counter =
makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3
In this example, JavaScript is used to create a function called "makeCounter" that returns another function. The returned function has access to the "count" variable in the outer function's scope and increments it each time it is called. The "makeCounter" function is called to create a new counter function, which is then called three times to log the values 1, 2, and 3 to the console.
28. What is the "this" keyword in JavaScript?
Answer : The "this" keyword in
JavaScript refers to the object that the current code is executing in. The
value of "this" is determined dynamically at runtime, based on how
the function is called.
Example code for using the "this" keyword in JavaScript:
var person = {
firstName:
"John",
lastName: "Doe",
fullName: function() {
console.log(this.firstName
+ " " + this.lastName);
}
};
person.fullName();
// John Doe
In this example, JavaScript is used to create an object called "person" with three properties: "firstName", "lastName", and "fullName". The "fullName" property is a function that logs the person's full name to the console, using the "this" keyword to refer to the "person" object. When the "fullName" function is called using the dot notation on the "person" object, the output is "John Doe".
29. What is a callback function in JavaScript?
Answer : A callback function in JavaScript is a
function that is passed as an argument to another function, and is called by
that function when a specific event or condition occurs. Callback functions are
a common way to handle asynchronous code and to implement event-driven
programming.
Example code for using a callback function in JavaScript:
function getData(callback)
{
var data =
fetchDataFromServer();
callback(data);
}
function displayData(data)
{
console.log
("Data
retrieved:", data);
}
getData(displayData);
In this example, JavaScript is used to create a function called "getData" that takes a callback function as an argument. Inside the "getData" function, data is retrieved from a server using the "fetchDataFromServer" function. Once the data is retrieved, the callback function is called with the data as an argument. A second function called "displayData" is defined to log the data to the console. The "getData" function is called with the "displayData" function as the callback, and when the data is retrieved, the "displayData" function is called to log the data to the console.
30. What is an immediately invoked function expression (IIFE) in JavaScript?
Answer : An immediately invoked function
expression (IIFE) in JavaScript is a function that is defined and executed at
the same time. IIFEs are commonly used to create private scopes and to avoid
naming conflicts with other code.
Example code for using an IIFE in JavaScript:
(function() {
var privateVariable =
"Hello World";
console.log(privateVariable);
})();
In this example, JavaScript is used to define an anonymous function that is immediately executed using parentheses. Inside the function, a variable called "privateVariable" is defined and logged to the console. Because the function is immediately executed, the variable is not accessible outside of the function's scope.
31. What is the "use strict" directive in JavaScript?
Answer : The "use strict" directive in
JavaScript is a statement that enables strict mode, which is a way to enforce
stricter parsing and error handling rules in JavaScript code. When strict mode
is enabled, certain code constructs are disallowed or produce errors that would
otherwise be ignored.
Example code for using the "use strict" directive in JavaScript:
"use strict";
function myFunction() {
x = 10;
console.log(x);
}
myFunction();
Answer : In JavaScript, "var",
"let", and "const" are all keywords used to declare
variables. However, they have different scoping rules and behaviors:
"let" variables are block-scoped and can be
reassigned, but not redeclared in the same block.
"const" variables are block-scoped and cannot
be reassigned or redeclared.
Example code for using "var", "let",
and "const" in JavaScript:
function myFunction() {
var x = 1;
let y = 2;
const z = 3;
if (true) {
var x = 4;
let y = 5;
const z = 6;
console.log(x, y, z);
}
console.log(x, y, z);
}
myFunction();
In this example, JavaScript is used to define a function
called "myFunction" that declares variables using "var",
"let", and "const". Inside the function, an if statement is
used to declare new variables with the same names. Because "var"
variables are function-scoped, the first console.log statement outputs 4, 5,
and 6. However, because "let" and "const" variables are
block-scoped, the second console.log statement outputs 1, 2, and 3.
Answer : Hoisting in JavaScript is the behavior
where variable and function declarations are moved to the top of their
respective scopes during compilation, regardless of where they are actually
declared in the code. This allows variables and functions to be used before
they are declared.
console.log(x);
var x = 10;
In this example, a variable called "x" is
logged to the console before it is declared. However, because of hoisting, the
variable is still defined and initialized to undefined at the beginning of the
scope.
A closure in JavaScript is a function that has access to
its parent function's variables and parameters, even after the parent function
has returned. Closures are often used to create private variables and methods
in JavaScript.
function outerFunction() {
var x = 1;
function innerFunction() {
console.log(x);
}
return innerFunction;
}
var myFunction =
outerFunction();
myFunction();
In this example, a function called
"outerFunction" is defined that declares a variable called
"x" and defines a nested function called "innerFunction"
that logs the value of "x" to the console. The outer function then
returns the inner function, which is assigned to a variable called "myFunction".
When "myFunction" is called, it still has access to the "x"
variable from the outer function, even though the outer function has already
returned.
Answer : Event bubbling in JavaScript is the
behavior where events that are triggered on nested elements "bubble
up" to their parent elements, triggering any event listeners that are
attached to those elements as well.
<div
id="parent">
<div id="child">
<button id="button">Click
me!</button>
</div>
</div>
In this example, HTML code is used to define a parent
element with an id of "parent", a child element with an id of
"child", and a button element with an id of "button". If an
event listener is attached to the "parent" element and the button is
clicked, the event will bubble up to the parent element and trigger the event
listener.
Answer : Event delegation in JavaScript is the
practice of attaching a single event listener to a parent element instead of
attaching multiple event listeners to its child elements. This can improve
performance and reduce code complexity, especially for dynamic or complex web
applications.
Example code for event delegation in JavaScript:
<div id="parent">
<ul>
<li>Item
1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
In this example, HTML code is used to define a parent
element with an id of "parent" and a list of child elements. Instead
of attaching event listeners
to each list item, a single event listener can be
attached to the parent element to handle click events on any of the list items:
var
parent = document.getElementById("parent");
parent.addEventListener("click",
function(event) {
if (event.target.tagName
=== "LI") {
console.log(event.target.innerHTML);
}
});
Answer : A promise in JavaScript is an object that
represents the eventual completion (or failure) of an asynchronous operation,
and allows for more readable and maintainable asynchronous code. Promises can
be in one of three states: pending, fulfilled, or rejected.
function fetchData() {
return new
Promise(function(resolve, reject) {
fetch("https://example.com/data.json")
.then(function(response) {
if (response.ok) {
resolve(response.json());
} else {
reject(new
Error("Failed to fetch data"));
}
})
.catch(function(error) {
reject(error);
});
});
}
Answer : A callback function in JavaScript is a
function that is passed as an argument to another function and is executed at a
later time, usually after some asynchronous operation has completed.
function
fetchData(callback) {
fetch("https://example.com/data.json")
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new
Error("Failed to fetch data");
}
})
.then(function(data) {
callback(data);
})
.catch(function(error) {
console.log(error);
});
}
In this example, a function called "fetchData"
takes a callback function as an argument, and asynchronously fetches data from
a JSON file using the fetch API. If the fetch is successful, the parsed JSON
data is passed to the callback function for further processing.
Answer : In synchronous code in JavaScript, each
line of code is executed one after the other, in order, and the program blocks
(or waits) at any point where there is an expensive operation or function call.
In asynchronous code, expensive operations and function calls are executed in
the background, and the program continues to execute other code while it waits
for them to complete.
// synchronous code
var result =
fetch("https://example.com/data.json");
console.log(result);
fetch("https://example.com/data.json")
.then(function(response) {
console.log(response);
});
Example code using var in JavaScript:
function exampleFunction() {
var x = 1;
if (true) {
var x = 2;
console.log(x); // outputs
2
}
console.log(x); // outputs
2
}
Example code using let in JavaScript:
function exampleFunction() {
let x = 1;
if (true) {
let x = 2;
console.log(x); // outputs
2
}
console.log(x); // outputs
1
}
Example code using const in JavaScript:
const PI = 3.14;
PI = 3.14159; // this will
throw an error
const myObj = { name: "John" };
myObj.name =
"Jane"; // this is allowed
Answer : In JavaScript, event delegation is a
pattern where instead of attaching an event handler to each individual element
that needs to respond to a particular event, a single event handler is attached
to a parent element that contains all of the child elements. When the event is
triggered on a child element, the event bubbles up to the parent element and is
handled by the single event handler.
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
JavaScript:
document.getElementById("list").addEventListener("click",
function(event) {
if (event.target.nodeName
=== "LI") {
console.log("Clicked
item: " + event.target.innerText);
}
});
Answer : In JavaScript, the document object
represents the HTML document that is currently displayed in the browser window,
while the window object represents the browser window itself.
The document object is part of the DOM (Document Object
Model), which represents the structure and content of the HTML document as a
tree of objects. The window object is not part of the DOM.
The document object is created and loaded when the HTML document
is parsed and rendered by the browser. The window object is created when the
browser window is opened.
<html>
<head>
<title>Document and Window Objects
Example</title>
</head>
<body>
<h1>Hello, world!</h1>
<script>
// Access properties and methods of the
document object
var title = document.title;
console.log(title); // outputs
"Document and Window Objects Example"
console.log(body); //
outputs <body> element
newHeading.textContent =
"Welcome!";
document.body.appendChild(newHeading);
var width =
window.innerWidth;
console.log(width); //
outputs width of browser window in pixels
console.log(location); //
outputs URL of current page
</script>
</body>
</html>
43. What
is AJAX in JavaScript?
Answer : In JavaScript, AJAX (Asynchronous
JavaScript and XML) is a technique for making HTTP requests to a server and
receiving data in the background without needing to refresh the entire page.
This allows for dynamic and interactive web applications that can update their
content without interrupting the user's experience.
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
</head>
<body>
<div id="output"></div>
<button id="button">Get
Data</button>
<script>
var button =
document.getElementById("button");
var output =
document.getElementById("output");
var xhr = new XMLHttpRequest();
xhr.open("GET",
"data.json");
xhr.onload = function() {
if (xhr.status === 200) {
output.textContent = xhr.responseText;
}
};
xhr.send();
});
</script>
</body>
</html>
In this example, clicking the "Get Data" button
triggers an AJAX request to the server to retrieve data from a file called
data.json. When the response is received, the contents of the file are
displayed in the output div element without needing to refresh the entire page.
Answer : In JavaScript, a callback function is a
function that is passed as an argument to another function and is executed when
a certain event occurs or a certain condition is met. Callback functions are
commonly used in asynchronous programming, where the order of execution is not
predetermined and depends on external factors such as network latency or user
input.
var xhr = new
XMLHttpRequest();
xhr.open("GET",
"data.json");
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
}
};
xhr.send();
}
console.log(data);
}
fetchData(displayData);
Comments
Post a Comment