0% found this document useful (0 votes)
2 views

IP -- M2

JSON (JavaScript Object Notation) is a lightweight, human-readable data format used for data interchange, particularly in web applications, while XML (Extensible Markup Language) is a more verbose markup language. JSON is preferred over XML due to its simplicity, smaller data size, faster parsing, and better integration with JavaScript. Additionally, JSON supports complex data structures more intuitively and has widespread adoption in modern APIs.

Uploaded by

Khan Fardeen
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)
2 views

IP -- M2

JSON (JavaScript Object Notation) is a lightweight, human-readable data format used for data interchange, particularly in web applications, while XML (Extensible Markup Language) is a more verbose markup language. JSON is preferred over XML due to its simplicity, smaller data size, faster parsing, and better integration with JavaScript. Additionally, JSON supports complex data structures more intuitively and has widespread adoption in modern APIs.

Uploaded by

Khan Fardeen
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
You are on page 1/ 14

Q) What is JSON & what are benefits of using JSON over XML.

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for
humans to read and write and easy for machines to parse and generate. It is widely used for
data exchange between a server and a client, especially in web applications.

Key Features of JSON:


1. Syntax: Based on key-value pairs, JSON syntax is similar to JavaScript objects.
2. Lightweight: It’s minimal, making it efficient for data transmission.
3. Readable: Human-readable text format.
4. Language-Independent: Though derived from JavaScript, JSON is supported in
most programming languages.

JSON Syntax:
1. Data is represented as:
Objects: Encapsulated in curly braces {} with key-value pairs.
Arrays: Ordered list of values enclosed in square brackets [].

2. Key-value pairs:
Key: Must be a string and is enclosed in double quotes.
Value: Can be a string, number, boolean, null, array, or another JSON object.

Example JSON Structure:


{
“name”: “John Doe”,
“age”: 30,
“isStudent”: false,
“skills”: [“JavaScript”, “Python”, “SQL”],
“address”: {
“city”: “New York”,
“zip”: “10001”
}
}

Uses of JSON:
APIs: To send and receive data.
Configuration files: In software and tools (e.g., package.json in Node.js).
Database storage: Some databases like MongoDB use JSON-like documents.

JSON (JavaScript Object Notation) and XML (Extensible Markup Language) are both
used for data representation and transfer, but JSON is often preferred in modern
applications due to several advantages:

1. Simplicity and Readability


JSON: Uses a lightweight, human-readable format that is easy to write and understand
(keyvalue pairs, arrays, etc.).
XML: Is verbose, requiring opening and closing tags for every element, which can make it
harder to read.

Example:

JSON: {“name”: “John”, “age”: 30}

XML: <person><name>John</name><age>30</age></person>

2. Smaller Data Size


JSON: Has less overhead because it does not require tags or attributes, leading to smaller
file sizes.

XML: Includes more metadata in the form of tags, making it bulkier.

3. Faster Parsing
JSON: Can be natively parsed by most modern programming languages (especially
JavaScript) with built-in functions, leading to faster processing.

XML: Requires additional libraries or parsers, which can slow down processing.

4. Easier Integration with JavaScript


JSON: Is designed to work seamlessly with JavaScript, making it ideal for web
development.

XML: Needs extra steps to convert data into a format that JavaScript can easily work with.

5. Support for Complex Data Structures


JSON: Natively supports arrays and nested objects, making it more suitable for representing
complex, hierarchical data.

XML: Represents data as a tree of elements, which can make it less intuitive for some use
cases.

6. Widespread Adoption in APIs


Most modern APIs (e.g., RESTful APIs) prefer JSON because it is easier to work with,
particularly in web and mobile development.

7. Better Performance
JSON’s compact format and simpler structure typically result in better performance during
transmission and parsing, especially for applications that deal with a large volume of data.

8. Less Complexity in Schemas

JSON: Validation schemas (e.g., JSON Schema) are simpler and easier to use.
XML: Uses complex schemas like DTD or XSD, which can be challenging to implement
and maintain.

Q) Explain Document Object Model in detail

The Document Object Model (DOM) is a programming interface that allows developers to
interact with and manipulate the structure, content, and style of a web page. It represents an
HTML or XML document as a tree-like structure of objects.

Key Features:
1. Tree Structure:

The document is organized as a tree with nodes representing elements, attributes, or text.

Example:

<html>

<body>

<h1>Hello</h1>

</body>

</html>

DOM Tree:

- html

- body

- h1

- Text: “Hello”

2. Node Types:

Element Nodes: Represent HTML elements (e.g., <div>, <p>).

Text Nodes: Represent text content inside elements.

Attribute Nodes: Represent attributes (e.g., id, class).

3. DOM Manipulation:

You can add, modify, or delete elements dynamically.

Example:

<div id=”myDiv”></div>

<script>

Const div = document.getElementById(“myDiv”);

div.innerHTML = “Hello, DOM!”;

</script>
4. Methods:

getElementById(id): Select an element by ID.

querySelector(selector): Select the first matching element using CSS

selectors. createElement(tag): Create a new element. appendChild(node):

Add a new node.

5. Event Handling:

The DOM allows you to handle user interactions like clicks or input using:

Element.addEventListener(“click”, function() {

Alert(“Clicked!”);

});

Example of DOM in Action:

<button onclick=”changeText()”>Click Me</button>

<p id=”text”>Hello</p>

<script>

Function changeText() {

Document.getElementById(“text”).innerHTML = “Text Changed!”;

</script>

When the button is clicked, the paragraph text updates dynamically.


Q) Explain Built – in object in javascript

In JavaScript, built-in objects are predefined objects provided by the language to perform
various tasks, like handling data, performing mathematical calculations, working with
strings, and interacting with the browser. These objects simplify programming by offering
readymade methods and properties to manipulate data and perform operations.

Categories of Built-in Objects:

1. Global Objects:
These are fundamental objects available in every JavaScript environment without the need
to import or define them. They provide basic functionalities:
Object: The base for all JavaScript objects, allowing you to create and manipulate custom
objects.

Function: Represents JavaScript functions.

Array: Used to store ordered collections of items (numbers, strings, or other objects).

String: Allows manipulation of text data.

Number: Represents numerical values and provides methods for number-related tasks.

Boolean: Represents true/false values.

Symbol: Represents unique and immutable values, often used as object property keys.

BigInt: Used for handling integers larger than the Number type can safely represent.

2. Error Objects:

Used for handling exceptions and debugging code:

Error: Represents a general error.

TypeError: Indicates an operation was performed on an incompatible data type.

RangeError: Occurs when a value is not within the allowable range.

SyntaxError: Thrown when there’s a syntax mistake in code.

ReferenceError: Indicates the use of an undefined variable.


3. Math and Date:
These objects provide functionality for mathematical operations and working with dates and
times:
Math: Contains methods for mathematical constants and functions like Math.PI,
Math.sqrt(), and Math.random().

Date: Allows the creation and manipulation of date and time values.

4. Utility Objects:

Objects designed to facilitate specific operations:

JSON: Provides methods to parse and stringify JSON data.


RegExp: Allows creation and manipulation of regular expressions for pattern matching in
strings.

5. Browser-Specific Objects:
Available in environments like web browsers, these objects help interact with the web page
and perform browser-related tasks:

Window: Represents the browser window, allowing control over the viewport.

Document: Represents the DOM of the web page.

Console: Provides methods like console.log() for debugging and outputting information.

Example Usage:

1. Using the Math Object:

Console.log(Math.PI); // 3.141592653589793

Console.log(Math.sqrt(16)); // 4

Console.log(Math.random()); // Random number between 0 and 1

2. Manipulating Strings:

Const text = “Hello, World!”;

Console.log(text.toUpperCase()); // “HELLO, WORLD!”


Console.log(text.includes(“World”)); // true

3. Working with Dates:

Const now = new Date();

Console.log(now.toISOString()); // Current date and time in ISO format

4. Using JSON:

Const obj = { name: “Alice”, age: 25 };

Const jsonString = JSON.stringify(obj); // Convert to JSON string

Console.log(jsonString); // ‘{“name”:”Alice”,”age”:25}’

Const parsedObj = JSON.parse(jsonString); // Convert back to object

Console.log(parsedObj.name); // “Alice”

Q) Explain how JavaScript can hide HTML Elements with suitable example.

In JavaScript, you can hide HTML elements by modifying their CSS properties. The most
common way to hide an element is by setting its style.display or style.visibility property.

Ways to Hide HTML Elements

1. Using style.display:
Setting display to “none” completely removes the element from the layout (it doesn’t
occupy any space).

Example:

Document.getElementById(“myElement”).style.display = “none”;

2. Using style.visibility:
Setting visibility to “hidden” hides the element but still reserves its space in the layout.

Example:

Document.getElementById(“myElement”).style.visibility = “hidden”;

3. Using classList:

Add or remove a CSS class to control visibility using CSS rules.

Example:

Document.getElementById(“myElement”).classList.add(“hidden”);

Explanation of the Example

1. Hiding with style.display:


Clicking the first button (Hide with display) sets the heading’s display property to none.
The element disappears, and the layout is adjusted as if it doesn’t exist.

2. Hiding with style.visibility:


Clicking the second button (Hide with visibility) hides the paragraph, but its space is still
reserved in the layout.

3. Hiding with classList:


Clicking the third button (Hide with class) adds the CSS class .hidden to the heading, which
sets its display to none.

Q) Explain Exception handling in Javascript with suitable example.

Exception handling in JavaScript is a mechanism to handle runtime errors gracefully,


preventing the program from crashing and allowing developers to handle errors in a
controlled way.

JavaScript provides the try-catch-finally block for handling exceptions:

1. Try block: Contains the code that may throw an error.


2. Catch block: Executes if an error is thrown in the try block. It provides an error
object for debugging.
3. Finally block (optional): Executes after try and catch, regardless of whether an error
was thrown or not. It is often used for cleanup tasks.
4. Throw statement: Used to manually throw an error.

Syntax

Try {

// Code that may throw an error

} catch (error) {

// Code to handle the error

} finally {

// Cleanup code (optional)

Example 1: Handling a Syntax Error

Try {

// Intentional error: undefined variable

Console.log(undeclaredVariable);

} catch (error) {

Console.log(“An error occurred:”, error.message);

} finally {

Console.log(“Execution complete.”);

Output:

An error occurred: undeclaredVariable is not defined

Execution complete.
Example 2: Throwing a Custom Error

Function checkAge(age) {

If (age < 18) {

Throw new Error(“Age must be 18 or above.”);

} else {

Console.log(“Access granted.”);

} Try { checkAge(16); // This will throw

an error

} catch (error) {

Console.log(“Caught an error:”, error.message);

} finally {

Console.log(“Age check complete.”);

Output:

Caught an error: Age must be 18 or above.

Age check complete.

Key Points
The catch block receives an Error object that includes details like name (type of error) and
message.

The finally block runs regardless of whether an error occurs.

You can use the throw statement to generate custom errors.

Q) Explain Event Handling in JavaScript with example.

Event handling in JavaScript is the process of detecting and responding to user actions or
browser events, such as clicks, keystrokes, mouse movements, form submissions, etc. It
allows developers to add interactivity to their web applications.
Key Concepts in Event Handling

1. Event: An action or occurrence that happens in the browser (e.g., a button click,
mouse hover, or keypress).
2. Event Listener: A function that “listens” for a specific event on an HTML element
and executes a callback when the event occurs.
3. Event Object: Provides information about the event, such as the type of event, the
target element, and additional data like mouse position or key code.

Ways to Handle Events

1. Inline Event Handlers


Add event handling directly in the HTML element using attributes like onclick,
onmouseover, etc.

<button onclick=”alert(‘Button clicked!’)”>Click Me</button>

2. Using DOM Properties

Assign a function to an event property of an HTML element.

Const button = document.getElementById(“myButton”);

Button.onclick = function() {

Alert(“Button clicked!”);

};

3. Using addEventListener()
The preferred modern way to attach event listeners. It allows multiple listeners for the same
event and better control.

Const button = document.getElementById(“myButton”);

Button.addEventListener(“click”, () => {

Alert(“Button clicked!”);

});
Example: Button Click Event

<!DOCTYPE html>

<html lang=”en”>

<head>

<title>Event Handling Example</title>

</head>

<body>

<button id=”myButton”>Click Me</button>

<p id=”message”></p>

<script>

// Select the button and message elements

Const button = document.getElementById(“myButton”);

Const message = document.getElementById(“message”);

// Add a click event listener

Button.addEventListener(“click”, () => {

Message.textContent = “Button was clicked!”;

});

</script>

</body>

</html>

Benefits of Event Handling

1. Improved Interactivity: Responds to user actions, making web pages dynamic and
engaging.
2. Separation of Concerns: Using addEventListener() keeps JavaScript separate from
HTML, improving maintainability.
3. Efficient Control: Event delegation allows handling events efficiently, especially in
dynamic content.

Q) Difference between JSON & XML

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy