Page 273 - Web_Application_v2.0_C12_Fb
P. 273
4. How can you create and access an array in JavaScript? Explain with a code example.
Ans. In JavaScript, an array is a special type of object used to store multiple values in a single variable. It can hold
elements of different data types like numbers, strings, and objects.
You can create an array in JavaScript using:
Array Literal
Array Constructor
For example:
const fruits = ["Apple", "Banana", "Mango", "Orange"];
document.write(fruits);
You can also create an array using Array() constructor.
const numbers = new Array(10, 20, 30, 40);
document.write(numbers);
5. What is an object? Explain two ways of declaring an object.
Ans. Consider an object in JavaScript as a list of items, each of which is a property or method that is kept as a key-value
pair in memory.
You can define and create your own objects in any of the following ways:
Using an object literal.
The following example creates a new JavaScript object with three properties:
const student = {Name : "Rashi", age : 35, Address : "Ajmer" };
Using the keyword new.
The following example creates a new JavaScript object using new Object(), and then adds 3 properties:
const student = new Object();
student.Name = "Rashi";
student.age = 35;
student.Address = "Ajmer";
6. Explain the following with respect to Java script using suitable example.
i. Event handler ii. Objects
Ans. i. Event Handler: The "event handler" is a command that is used to specify actions in response to an event. Eg:
onLoad, onMouseover etc.
ii. Objects: JavaScript objects are simply collections of name-value pairs. The "name" part is a JavaScript string,
while the value can be any JavaScript value including more objects. Objects are a way of organizing the
variables. The different screen elements such as Web pages, forms, text boxes, images, and buttons are treated
as objects.
7. Write a JavaScript program to check if a number is even or odd.
Ans. <!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>Even or Odd Checker</TITLE>
<SCRIPT>
function checkEvenOdd() {
var num = document.getElementById("number").value;
var result = (num % 2 === 0) ? "Even" : "Odd";
document.getElementById("output").innerHTML = "The number " + num + " is " + result;
JavaScript Part 2 271

