How do you declare variables and initialize them in javascript? Give examples for each data type.
// 1️⃣ String (Text)
let name = "John Doe"; // Double quotes
let message = 'Hello, World!'; // Single quotes
let greeting = `Welcome, ${name}`; // Template literal
console.log(name, message, greeting);
// 2️⃣ Number (Integer & Float)
let age = 25; // Integer
let price = 99.99; // Floating-point
console.log(age, price);
// 3️⃣ Boolean (True/False)
let isLoggedIn = true;
let hasPermission = false;
console.log(isLoggedIn, hasPermission);
// 4️⃣ Undefined (No value assigned)
let user;
console.log(user); // Output: undefined
// 5️⃣ Null (Explicitly no value)
let emptyValue = null;
console.log(emptyValue); // Output: null
// 6️⃣ Object (Key-Value Pairs)
let person = {
name: "Alice",
age: 30,
isStudent: false
};
console.log(person);
// 7️⃣ Array (List of Values)
let colors = ["Red", "Green", "Blue"];
let numbers = [10, 20, 30, 40];
console.log(colors, numbers);
// 8️⃣ Symbol (Unique Identifier)
let id = Symbol("userID");
console.log(id);
// 9️⃣ BigInt (For large numbers beyond Number.MAX_SAFE_INTEGER)
let bigNumber = 123456789012345678901234567890n;
console.log(bigNumber);
// 🔹 var, let, and const Usage
var x = 10; // Function-scoped, can be redeclared
let y = 20; // Block-scoped, cannot be redeclared
const z = 30; // Constant, cannot be reassigned
console.log(x, y, z);
Give examples of the following in JS
Instructions
console.log("Hello, World!"); // Instruction to print a message
let sum = 5 + 3; // Instruction to add numbers and store the result
Comment
// This is a single-line comment
let x = 10; // This variable stores the number 10
/*
This is a multi-line comment.
It can span multiple lines.
*/
let y = 20;
Statements
let a = 10; // Variable declaration statement
a = a + 5; // Assignment statement
console.log(a); // Function call statement
if (a > 10) { console.log("A is greater than 10"); } // Conditional statement
Variable declaration
var oldVar = "I am declared using var"; // Function-scoped (not recommended)
let age = 25; // Block-scoped (preferred for variables that change)
const PI = 3.1416; // Constant value (cannot be reassigned)
What do you mean by dynamically typed and interpreted languages?
Write a recursive function in js to find the factorial of a number and display the result on the console.
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
const num = 5; // Change this to any number you want to test
console.log(`Factorial of ${num} is: ${factorial(num)}`);
Write a js script to display the numbers 0 to 9 except a number entered via prompt. Preferably use a do while loop.
const skipNumber = parseInt(prompt("Enter a number to skip
(0-9):"), 10);
let i = 0;
do {
if (i !== skipNumber) {
console.log(i);
}
i++;
} while (i < 10);
a) Write a JavaScript program that displays the largest integer among two integers
b) Write a JavaScript conditional statement to find the sign of the product of three numbers. Display an alert box with the specified sign
Input: 3,-9 , 6 Output: -ve sign
const num1 = parseInt(prompt("Enter the first integer:"), 10);
const num2 = parseInt(prompt("Enter the second integer:"), 10);
if (num1 > num2) {
console.log(`The larger number is: ${num1}`);
} else if (num2 > num1) {
console.log(`The larger number is: ${num2}`);
} else {
console.log("Both numbers are equal.");
}
Prgm2:
const num1 = parseFloat(prompt("Enter the first number:"));
const num2 = parseFloat(prompt("Enter the second number:"));
const num3 = parseFloat(prompt("Enter the third number:"));
const product = num1 * num2 * num3;
if (product > 0) {
alert("The sign of the product is: +ve");
} else if (product < 0) {
alert("The sign of the product is: -ve");
} else {
alert("The product is zero (0).");
}
a) Write a JavaScript conditional statement to find the largest of five numbers. Display an alert box to show the results.
b) Write a JavaScript for loop that iterates from 0 to 15. For each iteration, it checks if the current number is odd or even, and displays a message on the screen.
Sample Output :"0 is even" "1 is odd" "2 is even"
const num1 = parseFloat(prompt("Enter the first number:"));
const num2 = parseFloat(prompt("Enter the second number:"));
const num3 = parseFloat(prompt("Enter the third number:"));
const num4 = parseFloat(prompt("Enter the fourth number:"));
const num5 = parseFloat(prompt("Enter the fifth number:"));
const largest = Math.max(num1, num2, num3, num4, num5);
alert(`The largest number is: ${largest}`);
for (let i = 0; i <= 15; i++) {
if (i % 2 === 0) {
console.log(`${i} is even`);
} else {
console.log(`${i} is odd`);
}
}
Write a JavaScript program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
let pattern = "";
for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= i; j++) {
pattern += "* ";
}
pattern += "\n";
}
console.log(pattern);
Write a JavaScript program to compute the greatest common divisor (GCD) of two positive integers.
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
const num1 = parseInt(prompt("Enter the first positive integer:"), 10);
const num2 = parseInt(prompt("Enter the second positive integer:"), 10);
if (num1 > 0 && num2 > 0) {
alert(`The GCD of ${num1} and ${num2} is: ${gcd(num1, num2)}`);
} else {
alert("Please enter valid positive integers.");
}
Write a JavaScript program to sum 3 and 5 multiples under 1000.
let sum = 0;
for (let i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
}
console.log(`The sum of all multiples of 3 and 5 below 1000 is: ${sum}`);
Reversing a Number with JavaScript While Loop.
function reverseNumber(num) {
let reversed = 0;
while (num !== 0) {
let digit = num % 10; // Get the last digit
reversed = reversed * 10 + digit; // Append digit to reversed number
num = Math.floor(num / 10); // Remove the last digit
}
return reversed;
}
const num = parseInt(prompt("Enter a number to reverse:"), 10);
alert(`The reversed number is: ${reverseNumber(num)}`);
Finding the Largest Digit in a Number Using a While Loop.
function largestDigit(num) {
num = Math.abs(num); // Ensure the number is positive
let maxDigit = 0;
while (num !== 0) {
let digit = num % 10; // Extract the last digit
if (digit > maxDigit) {
maxDigit = digit; // Update maxDigit if current digit is larger
}
num = Math.floor(num / 10); // Remove the last digit
}
return maxDigit;
}
const num = parseInt(prompt("Enter a number:"), 10);
alert(`The largest digit in ${num} is: ${largestDigit(num)}`);
Checking Prime Numbers Using While Loop in JavaScript.
function isPrime(num) {
if (num < 2) return false; // 0 and 1 are not prime numbers
let i = 2;
while (i <= Math.sqrt(num)) {
if (num % i === 0) {
return false; // If divisible, not a prime number
}
i++;
}
return true;
}
const num = parseInt(prompt("Enter a number:"), 10);
if (isPrime(num)) {
alert(`${num} is a prime number.`);
} else {
alert(`${num} is not a prime number.`);
}
Write a JavaScript program to list the properties of a JavaScript object.
Sample object:
var student = {name : "Ram Rahim", sclass : "VI", rollno : 12 };
Sample Output: name, sclass, rollno
var student = { name: "Ram Rahim", sclass: "VI", rollno: 12 };
console.log(Object.keys(student).join(", "));
Write a JavaScript program to delete the roll-no property from the following object. Also print the object before or after deleting the property.
Sample object:
var student = { name : "ram rahim", sclass : "VI", rollno : 12 };
var student = { name: "Ram Rahim", sclass: "VI", rollno: 12 };
console.log("Before deletion:", student);
delete student.rollno;
console.log("After deletion:", student);
Write a JavaScript program to get the volume of a cylindrical with four decimal places using object classes.
Volume of a cylinder : V = πr2h
where r is the radius and h is the height of the cylinder.
class Cylinder {
constructor(radius, height) {
this.radius = radius;
this.height = height;
}
getVolume() {
let volume = Math.PI * Math.pow(this.radius, 2) * this.height;
return volume.toFixed(4); // Round to 4 decimal places
}
}
const radius = parseFloat(prompt("Enter the radius of the cylinder:"));
const height = parseFloat(prompt("Enter the height of the cylinder:"));
const cylinder = new Cylinder(radius, height);
alert(`The volume of the cylinder is: ${cylinder.getVolume()}`);
Write a JavaScript program to calculate circle area and perimeter.
Note : Create two methods to calculate the area and perimeter. The radius of the circle will be supplied by the user.
class Circle {
constructor(radius) {
this.radius = radius;
}
// Method to calculate the area
getArea() {
return (Math.PI * Math.pow(this.radius, 2)).toFixed(2);
}
// Method to calculate the perimeter (circumference)
getPerimeter() {
return (2 * Math.PI * this.radius).toFixed(2);
}
}
// Get user input for radius
const radius = parseFloat(prompt("Enter the radius of the circle:"));
if (!isNaN(radius) && radius > 0) {
const circle = new Circle(radius);
alert(`Circle Area: ${circle.getArea()} \nCircle Perimeter: ${circle.getPerimeter()}`);
} else {
alert("Please enter a valid positive number for the radius.");
}
For the following script what problem might be encountered in the addHx function?
<script>
function createElementAsChild(parent, tag){
let tagInstance = document.createElement(tag)
parent.appendChild(tagInstance)
return tagInstance
}
function addHx(parent, tag, content){
tagInstance = createElementAsChild(parent, tag)
tagInstance.textContent = content
return tagInstance
}
let body = document.body
let h3Tag = addHx(body, "h3")
</script>
How does javascript handle errors?
FInal fixed code:
function createElementAsChild(parent, tag) {
let tagInstance = document.createElement(tag);
parent.appendChild(tagInstance);
return tagInstance;
}
function addHx(parent, tag, content = "") { // Default value prevents "undefined"
let tagInstance = createElementAsChild(parent, tag);
tagInstance.textContent = content;
return tagInstance;
}
let body = document.body;
let h3Tag = addHx(body, "h3", "Hello, this is H3!"); // Proper function call
Write a js script to add the following in the body of an html document using dom manipulation by invoking functions document.createElement() and parent.appendChild().
<body>
<h1> Hello World</h1>
<h2>I am SuperMan</h2>
<h3>I am SpiderNam</h3>
</body>
// Function to create and append elements
function addHeading(tag, text) {
let heading = document.createElement(tag); // Create the element (h1, h2, h3)
heading.textContent = text; // Set text content
document.body.appendChild(heading); // Append to body
}
// Adding the elements dynamically
addHeading("h1", "Hello World");
addHeading("h2", "I am SuperMan");
addHeading("h3", "I am SpiderMan");
What does the following code do?
<div>
<span title="Window Title123" id="hi">Hello</span>
<span id="bye">Bye</span>
</div>
<script>
let div = document.querySelector("div")
let hiSpan = document.querySelector("#hi")
let byeSpan = document.querySelector("#bye")
console.log(hiSpan.getAttribute("title"))
</script>
Add a new attribute and remove an existing attribute for the hiSpan.
let div = document.querySelector("div");
let hiSpan = document.querySelector("#hi");
let byeSpan = document.querySelector("#bye");
console.log(hiSpan.getAttribute("title")); // Logs: "Window Title123"
// Add a new attribute
hiSpan.setAttribute("data-info", "newData");
// Remove the existing "title" attribute
hiSpan.removeAttribute("title");
// Check the changes
console.log(hiSpan.getAttribute("data-info")); // Logs: "newData"
console.log(hiSpan.getAttribute("title")); // Logs: null (because it's removed)
Explain the following methods of selecting elements:
document.getElementById()
document.getElementsByName()
document.getElementsByTagName()
document.getElementsByClassName()
document.querySelector()
document.querySelectorAll()
by giving a single html page and querying its elements by these methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Selection Example</title>
</head>
<body>
<h1 id="main-title">Welcome to JavaScript DOM</h1>
<p class="description">This is a paragraph inside the body.</p>
<p class="description">Another paragraph with the same class.</p>
<input type="text" name="username" value="John Doe">
<input type="text" name="email" value="john@example.com">
<div>
<span class="info">Span inside div</span>
</div>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
// 1️⃣ document.getElementById("id")
let title = document.getElementById("main-title");
console.log("getElementById:", title.textContent);
// 2️⃣ document.getElementsByName("name")
let inputs = document.getElementsByName("username");
console.log("getElementsByName:", inputs[0].value);
// 3️⃣ document.getElementsByTagName("tagname")
let paragraphs = document.getElementsByTagName("p");
console.log("getElementsByTagName:", paragraphs[0].textContent);
// 4️⃣ document.getElementsByClassName("classname")
let descriptions = document.getElementsByClassName("description");
console.log("getElementsByClassName:", descriptions[1].textContent);
// 5️⃣ document.querySelector("selector")
let firstListItem = document.querySelector("ul li");
console.log("querySelector:", firstListItem.textContent);
// 6️⃣ document.querySelectorAll("selector")
let allListItems = document.querySelectorAll("ul li");
allListItems.forEach(item => console.log("querySelectorAll:", item.textContent));
</script>
</body>
</html>
No comments:
Post a Comment