Types of Objects in Javascript
Types of Objects in Javascript
1. Explain the different types of objects in JavaScript and how objects are
created.
In JavaScript, objects are used to store collections of data and functions. They consist
of properties (key-value pairs) and methods (functions inside objects).
A. User-Defined Objects
These are objects created by the programmer to store and manipulate data.
name: "John",
age: 21,
course: "JavaScript",
displayInfo: function() {
};
➡️ Key Features:
● Created using {} (curly braces).
● Properties and methods are defined inside.
● The this keyword refers to the current object.
These are predefined objects provided by JavaScript. Some common built-in objects
include:
console.log(str.length); // 18
console.log(fruits[1]); // Banana
console.log(Math.sqrt(16)); // 4
4. RegExp Object – Used for pattern matching and text searching.
let regex = /hello/i; // 'i' makes it case-insensitive
🔹 Example:
let person = {
name: "Alice",
age: 25,
};
console.log(person.name); // Alice
➡️ Best For:
● Small-scale applications.
● When an object does not need a blueprint/template.
🔹 Example:
let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.year = 2022;
console.log(car.brand); // Toyota
➡️ Best For:
● When objects need to be created dynamically at runtime.
● When working with key-value pairs in a structured manner.
🔹 Example:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
console.log(p1.name); // Bob
➡️ Best For:
● When multiple objects of the same type need to be created.
● When objects share similar properties and behaviors.
🔹 Example:
let animal = {
type: "Mammal",
makeSound: function() {
};
let dog = Object.create(animal);
dog.breed = "Labrador";
console.log(dog.type); // Mammal
➡️ Best For:
● When an object needs to inherit properties from another object.
● When using prototype-based inheritance.
A. Definition
canEat: true
};
console.log("Woof!");
};
dog.bark(); // Woof!
➡️ How It Works?
1. dog does not have the property canEat.
2. JavaScript searches in dog’s prototype (animal) and finds canEat.
🔹 Example:
let vehicle = {
hasWheels: true,
move: function() {
console.log("Moving...");
};
car.type = "Sedan";
car.move(); // Moving...
console.log(car.type); // Sedan
➡️ Best For:
● Creating new objects with an existing object as a prototype.
● Simple one-level inheritance.
🔹 Example:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
};
➡️ How It Works?
1. The greet() method is not inside p1 or p2.
2. JavaScript looks up the prototype chain and finds greet() inside
Person.prototype.
➡️ Best For:
● When creating multiple objects with shared methods.
● Helps in memory optimization (methods are stored once in the prototype
instead of being duplicated in each object).
● ES6 introduced the class syntax, which internally works using prototypes.
🔹 Example:
class Animal {
constructor(name) {
this.name = name;
speak() {
bark() {
➡️ How It Works?
1. Dog extends Animal, meaning Dog.prototype is linked to
Animal.prototype.
2. When calling dog1.speak(), JavaScript looks up the prototype chain and finds
speak() inside Animal.
➡️ Best For:
● Structuring object-oriented JavaScript programs.
● When working with complex object hierarchies.
🔹 Example:
let parent = { greet: function() { console.log("Hello!"); }
};
Object.setPrototypeOf(child, parent);
child.greet(); // Hello!
➡️ Best For:
● When dynamically linking objects at runtime.
● Not recommended for performance-sensitive applications.
Example:
car → vehicle → transport → Object.prototype → null
A. Definition
➡️ Difference:
● The literal notation (/pattern/) is simpler and preferred for fixed patterns.
● The constructor (new RegExp("pattern")) is useful when the pattern is
dynamic.
2. Usage of Regular Expressions
Regular expressions are used with string methods like:
console.log(pattern.test("Hello!")); // false
console.log(text.search(/JavaScript/)); // 7
🔹 Example:
let pattern = /\d{2,4}/;
console.log(pattern.test("123")); // true
console.log(pattern.test("1")); // false
5. Modifiers (Flags)
Modifiers change how a regular expression behaves.
🔹 Example:
let pattern = /hello/i;
A. Grouping with ()
console.log(result[1]); // "123"
B. Character Sets [ ]
🔹 Example:
let pattern = /[aeiou]/;
C. Negation [^ ]
🔹 Example:
let pattern = /[^aeiou]/;
return pattern.test(email);
console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("wrong-email")); // false
🔹 Example:
console.log("5" + 2); // "52"
🔹 Example:
console.log(5 + true); // 6 (true → 1)
🔹 Example:
console.log("10" * 2); // 20
console.log("5" - 1); // 4
console.log("100" / 10); // 10
🔹 Example:
console.log(null + 5); // 5 (null → 0)
🔹 Example:
let num = 123;
console.log(String(num)); // "123"
console.log(num.toString()); // "123"
🔹 Example:
console.log(Number("123")); // 123
console.log(parseInt("123.45")); // 123
console.log(parseFloat("123.45")); // 123.45
console.log(Number("Hello")); // NaN
🔹 Example:
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true
console.log(Boolean("")); // false
console.log(Boolean("Hello")); // true
➡️ Falsy values (0, "", null, undefined, NaN) return false, everything else is
true.
🔹 Example:
console.log(1 + "2"); // "12"
➡️ Numbers are added first, but if a string appears, all values convert to strings.
🔹 Example:
console.log(5 == "5"); // true (Type conversion happens)
1. What are JavaScript events? Explain event flow, including event bubbling and
event capturing.
Event Description
alert("Button Clicked!");
});
🔹 Example:
Consider the following HTML structure:
<div id="parent">
</div>
document.getElementById("child").addEventListener("click",
function() {
console.log("Child clicked");
}, true);
➡️ The event first reaches the parent, then the child (Top to Bottom).
B. Event Bubbling
📌 Definition:
● In bubbling, the event starts from the target element and moves upward in the
DOM hierarchy.
● Bubbling is the default behavior in JavaScript.
document.getElementById("child").addEventListener("click",
function() {
console.log("Child clicked");
}, false);
➡️ The event starts at the child and bubbles up to the parent (Bottom to Top).
🔹 Example:
document.getElementById("child").addEventListener("click",
function(event) {
console.log("Child clicked");
});
document.getElementById("parent").addEventListener("click",
function() {
console.log("Parent clicked");
});
● This method stops the event from calling any other listeners attached to the
same element.
🔹 Example:
document.getElementById("child").addEventListener("click",
function(event) {
});
document.getElementById("child").addEventListener("click",
function() {
});
4. Event Delegation
📌 Definition:
● Instead of adding event listeners to multiple child elements, we can add a single
event listener to a parent element and handle events using delegation.
● This is useful for dynamic elements (e.g., buttons created at runtime).
});
Parameter Description
alert("Button Clicked!");
});
};
alert("Button Clicked!");
};
console.log("Hello!");
}
// Adding event listener
document.getElementById("btn").addEventListener("click",
sayHello);
document.getElementById("btn").removeEventListener("click",
sayHello);
console.log("First Function");
};
document.getElementById("btn").onclick = function() {
console.log("Second Function");
};
📌 Output (Click on btn):
Second Function
});
document.getElementById("btn").addEventListener("click",
function() {
});
<html>
<head>
<title>DOM Example</title>
</head>
<body>
</body>
</html>
✔️ The DOM represents this structure as a tree, where <html> is the root node, and
all other elements are children of it.
2. Types of DOM
JavaScript interacts with different types of DOM structures:
A. Core DOM
<books>
<book>
<title>JavaScript Guide</title>
<author>John Doe</author>
</book>
</books>
✔️ XML DOM allows JavaScript to search for <title> inside <book> just like HTML
DOM.
A. Selecting Elements
B. Modifying Elements
✔️ Changing Attributes
document.getElementById("title").setAttribute("class",
"new-class");
document.getElementById("title").style.fontSize = "24px";
D. Removing Elements
parent.removeChild(child);
4. How can images, tables, and node lists be handled using JavaScript and the
DOM? Provide relevant examples.
<script>
function changeImage() {
document.getElementById("myImage").src = "image2.jpg";
</script>
img.src = "newImage.jpg";
img.width = 400;
img.height = 250;
document.getElementById("imageContainer").appendChild(img);
</script>
<script>
function removeImage() {
document.getElementById("myImg").remove();
}
</script>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
<script>
function addRow() {
cell2.innerHTML = "25";
</script>
✔️ Clicking the button adds a new row with data "John Doe" and "25".
✔️ Use deleteRow(index).
🔹 Example: Deleting the Last Row from a Table
<button onclick="deleteRow()">Delete Last Row</button>
<script>
function deleteRow() {
table.deleteRow(rowCount - 1);
</script>
✔️ Unlike arrays, node lists do not have array methods like map() or filter().
✔️ Can be looped using forEach() or a for loop.
<script>
p.style.color = "blue";
});
</script>
✔️ Loops through all <p> elements and changes their color to blue.
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
<script>
</script>
<script>
function removeAllParagraphs() {
document.querySelectorAll(".text").forEach(p =>
p.remove());
</script>
✔️ Clicking the button removes all paragraphs with the class "text".