1. What is the use of a constructor function in JavaScript?
Explain with suitable example
In JavaScript, a constructor function is a special type of function used to create and initialize
objects.
It acts like a blueprint for objects and is invoked with the `new` keyword.
Example:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
};
}
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
person1.greet(); // Hello, my name is Alice and I am 25 years old.
2. List and explain different types of Arrays in JavaScript with example.
Types of Arrays in JavaScript:
1. Single-Dimensional Array: Simple list of values.
Example: let fruits = ["Apple", "Banana", "Mango"];
2. Multi-Dimensional Array: Array inside another array (like a matrix).
Example: let matrix = [[1,2,3],[4,5,6],[7,8,9]];
3. Jagged Array: Multi-dimensional array with different lengths.
Example: let jagged = [[1,2],[3,4,5],[6]];
4. Array of Objects: Each element is an object.
Example: let students = [{name:"Alice", age:21}, {name:"Bob", age:22}];
5. Sparse Array: Contains empty slots.
Example: let sparse = []; sparse[5] = "Hello";
6. Typed Arrays: Special arrays for binary data.
Example: let arr = new Int16Array([10,20,30]);
3. What is Document Object Model? Discuss different ways of DOM to access HTML element
value.
The Document Object Model (DOM) is a programming interface that represents an HTML or XML
document as a tree structure.
Each element becomes a node and JavaScript can interact with them dynamically.
Ways to access HTML elements:
1. getElementById(id) – Returns element with given id.
2. getElementsByClassName(class) – Returns collection of elements with class.
3. getElementsByTagName(tag) – Returns collection of elements with tag.
4. querySelector(selector) – Returns first matching element.
5. querySelectorAll(selector) – Returns all matching elements as NodeList.
6. Accessing input value: document.getElementById("id").value
4. Explain JSON with example. Show the use of regular expression in JavaScript to validate
the email address with example.
JSON (JavaScript Object Notation) is a lightweight data-interchange format used for storing and
exchanging data.
It uses key-value pairs and is language independent.
Example JSON:
{
"name": "Alice",
"age": 25,
"skills": ["JavaScript", "Python"]
}
JavaScript usage:
let person = {name:"Alice", age:25};
let jsonString = JSON.stringify(person);
let obj = JSON.parse(jsonString);
Regular Expression for Email Validation:
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/;
if(regex.test("
[email protected]")){
console.log("Valid Email");
} else {
console.log("Invalid Email");
}