Sample Questions M2
Sample Questions M2
Sample Questions M2
=>The alert(), confirm(), and prompt() methods are functions provided by the window
object in JavaScript. They allow you to interact with users by displaying various types of
dialog boxes. Here's an explanation of each method:
1. alert(message) :
- The alert() method is used to display a simple alert dialog box with a message to the
user.
- It takes one argument, which is the message you want to display as a string.
- The dialog box typically contains an OK button for the user to dismiss the message.
- Example:
2. confirm(message):
- The confirm() method is used to display a confirmation dialog box with a message
and two buttons: OK and Cancel.
- It takes one argument, which is the message you want to display as a string.
- When the user clicks OK, the function returns true, and when the user clicks Cancel,
it returns false.
- Example:
3. prompt(message, defaultText):
- The prompt() method is used to display a dialog box that prompts the user to enter
some input.
- It takes two arguments: the first is the message to display as a string, and the
second is an optional default text that is pre-filled in the input field.
- The user can enter text and click OK or Cancel.
- If the user clicks OK, the function returns the text entered by the user as a string. If
the user clicks Cancel, it returns null.
- Example:
These dialog methods are used to enhance user interaction in web applications.
However, it's important to note that alert(), confirm(), and prompt() are considered
somewhat intrusive and may disrupt the user experience, especially when overused.
Modern web development often emphasizes more user-friendly and less disruptive
ways of interacting with users, such as using modal dialogs or custom-designed
interfaces.
Input Methods:
1. prompt(message, defaultText):
- As mentioned earlier, prompt() is used to display a dialog box that prompts the user
to enter input.
- It takes a message as its first argument (a string) and an optional default text (also a
string) that appears pre-filled in the input field.
- The user can input text and click OK or Cancel.
- If the user clicks OK, the function returns the text entered by the user as a string. If
the user clicks Cancel, it returns null.
var userInput = prompt("Please enter your name:", "John Doe");
if (userInput !== null) {
alert("Hello, " + userInput + "!");
} else {
alert("No name entered.");
}
2. confirm(message):
- confirm() displays a confirmation dialog box with a message and OK/Cancel buttons.
- It takes a message as its argument (a string) and returns true if the user clicks OK
and false if the user clicks Cancel.
3. Event Listeners:
- JavaScript can listen for user interactions (e.g., mouse clicks, keyboard input) using
event listeners.
- Developers can attach event listeners to HTML elements and respond to user
actions.
- Event listeners are used for interactive input from users.
document.getElementById("myButton").addEventListener("click", function () {
// This function is executed when the button with id "myButton" is clicked.
});
Output Methods:
1. alert(message):
- The alert() method displays an alert dialog box with the specified message.
- It takes a message as its argument (a string).
- The user can dismiss the dialog by clicking OK.
2. console.log(message):
- console.log() is used for debugging and logging information to the browser's console.
- It doesn't display messages directly to the user but is useful for developers to see
the output in the console.
4. document.write():
- This method is used to write content directly to the HTML document. However, it's
not commonly used due to its potential to overwrite existing content and affect page
layout.
These input and output methods in JavaScript enable developers to create interactive
web applications and provide feedback to users through various forms of input
gathering and output presentation. The choice of method depends on the specific use
case and user interaction requirements of the application.
3. What are functions? Explain how to create and call
functions.
=> Functions in JavaScript are reusable blocks of code that perform a specific task or
set of tasks. They allow you to organize and encapsulate your code, making it more
modular and easier to maintain. Functions can take inputs, perform operations, and
return results. Here's how to create and call functions in JavaScript:
Creating a Function:
You can create a function using the function keyword, followed by a name for the
function, a set of parentheses for parameters (if any), and a block of code enclosed in
curly braces {}. The general syntax looks like this:
function functionName(parameters) {
// Code to be executed
// ...
}
- functionName: This is the name of your function. Choose a descriptive name that
reflects what the function does.
- parameters: These are optional. You can define parameters inside the parentheses to
pass values into the function.
- {}: This is the code block where you write the instructions that the function should
execute.
function addNumbers(a, b) {
var sum = a + b;
return sum;
}
Calling a Function:
To use a function, you need to call it by its name and provide any required arguments
(values for the parameters) inside parentheses. You can assign the result of a function
to a variable or use it directly. Here's how to call the addNumbers function:
In this example:
- We call the addNumbers function with the arguments 5 and 3.
- The function adds these numbers and returns the result.
- We store the result in the result variable and then log it to the console.
Returning Values:
Functions can return values using the return statement. You can return a single value or
an expression. When a function encounters a return statement, it immediately exits, and
the specified value is returned to the caller. If a function doesn't have a return statement
or explicitly returns undefined, it still returns a value (implicitly undefined).
function multiply(a, b) {
return a b;
}
There are two common ways to create functions in JavaScript: function declarations and
function expressions.
1. Function Declaration:
function sayHello() {
console.log("Hello!");
}
2. Function Expression (using anonymous functions):
Both approaches have their use cases, but function declarations are hoisted (moved to
the top of the script during execution), allowing you to call them before their actual
definition in the code. Function expressions, on the other hand, are not hoisted.
2. String: Represents textual data. Strings are enclosed in single (') or double (") quotes.
var name = "John";
var message = 'Hello, World!';
4. Undefined: Represents a variable that has been declared but has no assigned value.
It is also the default value of function parameters that have not been provided.
var x;
var y = undefined; // You can explicitly set a variable to undefined.
1. Object: Represents a collection of key-value pairs and is the most versatile data type
in JavaScript. Objects can be created using object literals or with the new Object()
constructor.
var person = {
firstName: "John",
lastName: "Doe"
};
2. Array: Represents an ordered collection of values, typically of the same data type.
Arrays can hold primitive and reference data types.
var colors = ["red", "green", "blue"];
function greet(name) {
return "Hello, " + name + "!";
}
4. RegExp: Represents regular expressions used for pattern matching and searching
within strings.
1. var:
- var was the original way to declare variables in JavaScript, and it has been around
since the language's inception.
- Variables declared with var have function-level scope. This means they are scoped
to the nearest function block, not block-level (i.e., not limited to if statements, loops,
etc.).
- Variables declared with var are hoisted to the top of their containing function or
global scope, which can sometimes lead to unexpected behavior.
- Variables declared with var can be re-declared within the same scope.
var x = 10;
function example() {
var x = 20; // This is a separate variable, local to the function.
console.log(x); // Outputs 20
}
console.log(x); // Outputs 10
2. let:
- let was introduced in ECMAScript 6 (ES6) and offers block-level scope, making it
more predictable and flexible than var.
- Variables declared with let are scoped to the nearest enclosing block (i.e., within {}),
including loops, if statements, and function blocks.
- Variables declared with let are not hoisted to the top of the containing block.
- Variables declared with let can be reassigned, but not re-declared within the same
scope.
let y = 10;
if (true) {
let y = 20; // This is a separate variable, local to the block.
console.log(y); // Outputs 20
}
console.log(y); // Outputs 10
3. const:
- const is also introduced in ES6 and is used to declare variables whose values
should not be reassigned after initial assignment.
- Like let, variables declared with const have block-level scope and are not hoisted.
- Variables declared with const must be initialized when declared, and you cannot
reassign them later.
const z = 10;
if (true) {
const z = 20; // This is a separate constant, local to the block.
console.log(z); // Outputs 20
}
console.log(z); // Outputs 10
In modern JavaScript, it's recommended to use let for most variable declarations
because of its block-level scope and predictable behavior. Use const when you know
that a variable's value should not change after initialization. Reserve var for cases
where you specifically need function-level scope or when dealing with legacy code. The
introduction of let and const has improved the consistency and predictability of variable
scoping in JavaScript.
1. click Event:
- The click event occurs when a mouse button (typically the left button) is pressed and
then released on an HTML element, such as a button or a link.
- It is commonly used for handling user interactions like button clicks, opening links, or
triggering actions.
- Example:
2. mouseover Event:
- The mouseover event occurs when the mouse pointer enters the boundaries of an
HTML element, such as when moving the mouse over an image or a div.
- It is often used to trigger actions when a user hovers over an element, like displaying
tooltips or changing the element's appearance.
- Example:
3. mouseout Event:
- The mouseout event occurs when the mouse pointer exits the boundaries of an
HTML element, such as when moving the mouse out of an image or a div.
- It is typically used to revert changes made during the mouseover event or to perform
actions when the user stops hovering over an element.
- Example:
These are just a few examples of mouse events in JavaScript. There are many other
mouse-related events, such as mousedown, mouseup, mousemove, and contextmenu,
which you can use to create interactive and responsive web applications. Event
handlers are a fundamental part of web development and play a crucial role in
enhancing user interactivity and user experience on websites.
Mouse Events:
1. click:
- Occurs when the user clicks (presses and releases) a mouse button.
- Event Handler: onclick
2. mousedown:
- Occurs when the user presses a mouse button.
- Event Handler: onmousedown
3. mouseup:
- Occurs when the user releases a mouse button.
- Event Handler: onmouseup
4. mouseover:
- Occurs when the mouse pointer enters an element.
- Event Handler: onmouseover
5. mouseout:
- Occurs when the mouse pointer leaves an element.
- Event Handler: onmouseout
6. mousemove:
- Occurs when the mouse pointer moves within an element.
- Event Handler: onmousemove
Keyboard Events:
7. keydown:
- Occurs when a key on the keyboard is pressed down.
- Event Handler: onkeydown
8. keyup:
- Occurs when a key on the keyboard is released.
- Event Handler: onkeyup
Form Events:
9. submit:
- Occurs when a form is submitted, either by clicking a submit button or by using
JavaScript to trigger the submission.
- Event Handler: onsubmit
10. reset:
- Occurs when a form's reset button is clicked.
- Event Handler: onreset
11. change:
- Occurs when the value of an input element changes (commonly used with form
elements like text inputs, checkboxes, and radio buttons).
- Event Handler: onchange
12. load:
- Occurs when a web page or document finishes loading.
- Event Handler: onload
13. unload:
- Occurs when a web page or document is being unloaded or closed.
- Event Handler: onunload
14. resize:
- Occurs when the browser window is resized.
- Event Handler: onresize
15. scroll:
- Occurs when the user scrolls the web page.
- Event Handler: onscroll
Event Handlers:
Event handlers are functions that respond to specific events. They are used to define
what should happen when an event occurs. Event handlers can be assigned to HTML
elements using attributes (e.g., onclick, onmouseover) or attached to elements in
JavaScript code using methods like addEventListener().
button.addEventListener("click", function() {
alert("Button clicked!");
});
In this example, when the button with the id "myButton" is clicked, the click event
triggers the anonymous function that displays an alert.
These are just a few examples of the many types of events and event handlers
available in JavaScript. Events and event handling are fundamental to building
interactive and responsive web applications.
- Properties: Objects have properties, which are named values associated with the
object. Properties can store data or functions (methods).
- Methods: Functions defined within an object are called methods. They allow objects to
encapsulate behavior and functionality.
- Key-Value Pairs: Properties are defined as key-value pairs, where the key is a string
(or symbol in ES6+) that serves as the property name, and the value can be of any data
type.
There are several ways to create objects in JavaScript:
1. Object Literal:
- The most common way to create an object is using the object literal notation {}.
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
sayHello: function() {
console.log("Hello!");
}
};
2. Constructor Functions:
- You can define object templates (classes) using constructor functions and then
create multiple instances of objects from them.
3. Object.create() (ES5+):
- You can create objects based on a prototype using the Object.create() method.
var personPrototype = {
sayHello: function() {
console.log("Hello!");
}
};
4. Class (ES6+):
- ES6 introduced class syntax for creating objects and defining methods.
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
sayHello() {
console.log("Hello!");
}
}
5. Factory Functions:
- You can create objects using factory functions, which are functions that return new
objects.
Each of these methods for creating objects has its own advantages and use cases. The
choice of which method to use depends on your specific requirements and coding style.
ES6 introduced classes as a more structured way to create objects, making it easier to
define object templates and methods, but the other methods are still widely used and
valid.
1. Objects:
- Objects are fundamental in JavaScript and represent entities that have properties
and methods. Properties store data, while methods are functions associated with
objects.
2. Classes (ES6+):
- ES6 introduced class syntax, which allows developers to create object templates
with constructors and methods. Classes provide a blueprint for creating objects.
3. Inheritance:
- Inheritance in JavaScript is based on prototypes. Objects can inherit properties and
methods from their prototypes. It enables code reuse and creating hierarchies of
objects.
4. Encapsulation:
- Encapsulation involves bundling data (properties) and behavior (methods) into a
single unit (an object). JavaScript uses closures, constructor functions, and ES6 classes
for encapsulation.
5. Polymorphism:
- Polymorphism allows different objects to be treated as instances of the same type.
JavaScript supports polymorphism through its dynamic and flexible object system.
6. Abstraction:
- Abstraction involves simplifying complex systems by hiding unnecessary details and
exposing only the essential features. JavaScript objects and classes provide abstraction
by encapsulating implementation details.
These OOP concepts help organize and structure code in a more modular and reusable
way. JavaScript's unique features, such as its prototype-based inheritance and dynamic
nature, offer flexibility and power in applying OOP principles to a wide range of
programming tasks.
1. Concise Syntax:
- Arrow functions have a shorter and more concise syntax compared to traditional
function expressions, making code easier to read and write.
2. Implicit Return:
- Arrow functions with a single expression have an implicit return, eliminating the need
for the 'return' keyword for simple operations.
4. No Arguments Object:
- Arrow functions do not have their own 'arguments' object. Instead, they inherit the
'arguments' object from the enclosing function, simplifying code that relies on or avoids
naming conflicts with 'arguments'.
5. No 'new' Binding:
- Arrow functions cannot be used as constructor functions with the 'new' keyword,
preventing accidental object creation and encouraging better coding practices.
These advantages make arrow functions a useful addition to JavaScript for writing more
concise and maintainable code, particularly in scenarios where simplicity and clarity are
essential.
1. Function Declaration:
- Normal Function: A normal function is declared using the 'function' keyword, followed
by a name and a set of parentheses for parameters.
function normalFunction() {
// Function code here
}
function* generatorFunction() {
// Generator function code here
}
2. Execution Control:
- Normal Function: When you call a normal function, it runs from start to finish, and you
can't pause its execution or yield values during execution.
- Generator Function: A generator function can be paused during execution using the
'yield' keyword. This allows you to yield values one at a time and then resume execution
from where it left off.
3. Iterators:
- Generator Function: Generator functions are inherently iterable. When called, they
return a generator object that can be used to iterate over the values produced by the
'yield' statements.
- Normal Function: Each time you call a normal function, it starts with a fresh execution
context. Local variables are re-initialized, and there's no memory of the previous
execution.
- Normal Function: Normal functions run to completion and return a result. You can't
pause their execution midway or yield values during execution.
- Generator Function: Generator functions can pause their execution using 'yield',
allowing you to produce values lazily, pause, and then resume to produce more values
when needed.
6. Infinite Sequences:
- Normal Function: It's challenging to create infinite sequences using normal functions
because they run to completion.
- Generator Function: Generator functions can easily generate infinite sequences since
they can be paused and resumed as needed.
Here's an example of a generator function that generates an infinite sequence of
integers:
function* infiniteSequence() {
let i = 0;
while (true) {
yield i++;
}
}
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// ... and so on
Synchronous Programming:
3. Simple Control Flow: Synchronous code has a straightforward and predictable control
flow. It is easy to understand and reason about because tasks are executed in the order
they are written.
function syncTask1() {
// Task 1
}
function syncTask2() {
// Task 2
}
syncTask1();
syncTask2();
Asynchronous Programming:
3. Complex Control Flow: Asynchronous code can have a more complex control flow
due to callbacks, promises, or async/await syntax. This complexity arises from
managing the order of execution when tasks complete at different times.
function asyncTask2() {
// Task 2
}
asyncTask1(function() {
asyncTask2();
});
In the asynchronous example, 'asyncTask1' does not block the program; it schedules a
callback to be executed after a delay. Meanwhile, 'asyncTask2' can execute immediately
without waiting for 'asyncTask1' to finish.
Use Cases:
1. Multiline Strings: Template literals allow you to create multiline strings without the
need for escape characters or concatenation.
const multilineString = `
This is a
multiline string.`
;
3. Tagged Templates: Template literals can be "tagged" with a function, allowing you to
process the string and values in a custom way. This is commonly used for string
formatting and localization.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
sum(1, 2, 3, 4); // 10
Default Arguments:
Default function parameters allow you to specify default values for function parameters
when the caller doesn't provide a value or provides undefined. This feature is also
introduced in ES6.
Default arguments are helpful for making functions more flexible and providing sensible
defaults when certain parameters are not specified.
Iterator Generator
The scope of a
var variable is The scope of a let variable is The scope of a const
functional block scope. variable is block scope.
scope.
It can be
It can be updated but cannot
updated and It cannot be updated or
be re-declared into the
re-declared into re-declared into the scope.
scope.
the scope.
It can be
It can be declared without It cannot be declared
declared without
initialization. without initialization.
initialization.
It can be
accessed It cannot be accessed It cannot be accessed
without without initialization without initialization, as it
initialization as otherwise it will give cannot be declared without
its default value ‘referenceError’. initialization.
is “undefined”.
1. States:
- A Promise can be in one of three states:
- Pending: The initial state, representing that the operation is still ongoing.
- Fulfilled (Resolved): Indicates that the operation completed successfully, and a
result value is available.
- Rejected: Indicates that the operation encountered an error, and an error reason is
available.
2. Chaining:
- Promises allow you to chain multiple asynchronous operations together in a
sequence, making it easier to express complex asynchronous workflows.
- You can chain `.then()` and `.catch()` methods to handle fulfillment and rejection,
respectively.
3. Error Handling:
- Promises provide a clear and structured way to handle errors by using the `.catch()`
method. Errors propagate down the chain until they are caught by a `.catch()` block.
4. Creating Promises:
- You can create a new Promise using the `Promise` constructor, which takes a
function (executor) with two arguments: `resolve` and `reject`. Inside the executor, you
perform the asynchronous operation and call `resolve(value)` when it's successful or
`reject(reason)` when it fails.
5. Consuming Promises:
- To consume a Promise, you can use the `.then()` method to specify what should
happen when the Promise is fulfilled and the `.catch()` method to handle any errors.
myPromise
.then(result => {
// Handle fulfillment
})
.catch(error => {
// Handle rejection
});
6. Async/Await:
- ES2017 (ES8) introduced the `async/await` syntax, which simplifies asynchronous
code even further. It allows you to write asynchronous code in a more synchronous-like
style, making it more readable.
3. Higher-Order Functions: Callbacks are often used with higher-order functions, which
are functions that take other functions as arguments. Functions like ‘map()’, ‘filter()’, and
‘forEach()’ can accept callbacks to customize their behavior.
setTimeout(function() {
console.log("This is a callback function.");
}, 1000);
Callback functions are a crucial part of JavaScript's ability to handle asynchronous and
event-driven programming, making it possible to create responsive and interactive
applications, handle I/O operations efficiently, and design modular and reusable code.
19. Short note on Generator and Iterator.
=> Generator:
A generator in JavaScript is a special type of function that can be paused and resumed
during its execution. It allows you to generate a sequence of values lazily, which means
that you can produce values one at a time, on-demand, and potentially in an infinite
sequence. Generators are created using function declarations or expressions with an
asterisk (‘function*’).
- Syntax:
function* myGenerator() {
// Generator function code here
}
- Pausing and Resuming: Generators use the `yield` keyword to pause their execution
and yield a value. They can later be resumed from where they left off using the `next()`
method.
- Infinite Sequences: Generators are useful for creating iterators that represent
potentially infinite sequences, such as an infinite sequence of numbers.
Iterator:
An iterator is an object that provides a way to access the elements of a collection (like
an array or a custom data structure) one at a time. In JavaScript, an iterator is an object
with a `next()` method that returns an object with two properties: `value` (the current
element) and `done` (a boolean indicating whether there are more elements to iterate).
- Iterator Protocol: Iterators follow the iterator protocol, which specifies that they must
have a `next()` method. When you call `next()`, it should return an object with the
`value` and `done` properties.
- Iterables: An iterable is an object that has an associated iterator. Arrays, strings, maps,
sets, and generators are examples of iterables in JavaScript.
- For...of Loop: JavaScript provides a convenient way to iterate over iterables using the
`for...of` loop, which automatically calls the `next()` method of the iterator.
function* countToN(n) {
let count = 0;
while (count <= n) {
yield count;
count++;
}
}
In this example, ‘countToN’ is a generator that produces values from 0 to ‘n’. The
‘for...of’ loop iterates over the iterator created from the generator, printing each value.
Generators and iterators provide a powerful mechanism for working with sequences of
data in a more efficient and flexible way.
The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of a web page as a tree-like structure, where each node in the
tree corresponds to a part of the page (e.g., elements, attributes, text), and you can use
JavaScript to interact with and manipulate these nodes. The DOM provides a way for
JavaScript to dynamically access and update the content, structure, and style of a web
page.
Common Methods of the Document Object :
The Document object provides various methods and properties to interact with the web
page's structure and content. Here are some common methods of the Document object:
1. getElementById(id) :
- This method returns a reference to the first element in the document with the
specified id attribute.
- Example:
2. getElementsByClassName(className) :
- This method returns a live HTMLCollection of elements that have the specified class
name.
- Example:
3. getElementsByTagName(tagName) :
- This method returns a live HTMLCollection of elements with the specified tag name.
- Example:
4. querySelector(selector) :
- This method returns the first element that matches the specified CSS selector.
- Example:
5. querySelectorAll(selector) :
- This method returns a static NodeList of all elements that match the specified CSS
selector.
- Example:
var elements = document.querySelectorAll("p.myClass");
6. createElement(tagName) :
- This method creates a new HTML element with the specified tag name.
- Example:
7. appendChild(node) :
- This method adds a node as the last child of a parent node.
- Example:
8. removeChild(node) :
- This method removes a child node from its parent node.
- Example:
9. setAttribute(name, value) :
- This method sets or updates an attribute of an element with the specified name and
value.
- Example:
element.setAttribute("class", "newClass");
These are just some of the commonly used methods of the Document object in
JavaScript. The DOM provides a rich set of methods and properties that enable you to
create, manipulate, and interact with web page elements dynamically.
Data Validation:
Data validation is the process of checking if data or user input conforms to specified
criteria, such as format, length, or value. It is crucial for ensuring data integrity and
security in software applications.
Regular expressions are patterns used for matching and searching strings. They consist
of a combination of characters and special symbols that define a pattern to be searched
for within a text. In JavaScript, regex can be created using the `RegExp` constructor or
regex literals enclosed in forward slashes (`/`).
Regular expressions play a significant role in data validation by allowing you to:
1. Pattern Matching: Define a pattern that input data must match. For example, you can
use regex to validate email addresses, phone numbers, URLs, or dates by specifying
the expected pattern.
2. Format Validation: Check if data follows a specific format. Regex helps ensure that
data adheres to a predefined structure, such as date formats, postal codes, or credit
card numbers.
3. Length and Value Checks: Regex can be used to validate the length of a string or to
check if the data falls within a specific range of values. For instance, you can validate
passwords for complexity requirements.
4. Sanitization: Besides validation, regex can also be used for data sanitization, which
involves removing or modifying certain characters or substrings in input data to prevent
security vulnerabilities like SQL injection or cross-site scripting (XSS).
Error Handling:
When data does not pass validation, it's essential to provide meaningful error messages
or feedback to users. Error messages should clearly indicate what aspect of the input
data is invalid and how it can be corrected.
Data validation using regular expressions helps improve the reliability and security of
software applications by enforcing data integrity and preventing the processing of
potentially harmful or incorrect data.