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

JsAssignment 2

Uploaded by

Lakhan Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

JsAssignment 2

Uploaded by

Lakhan Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Q1.

Write a function that takes two numbers and returns their sum.

function addTwoNumbers(a, b)

return a + b;

console.log(addTwoNumbers(5, 7));

Q2.

Write a function that takes an array of numbers and returns the


largest number.

let arr = [3, 7 , 8 , 5 , 4];

let max = arr[0];

for(let i = 1; i < arr.length; i++){

if (arr[i]> max){

max = arr[i];

}
}

Q3.

Write a script that checks if a number is even or odd. function


checkEvenOrOdd(number) {

if (number % 2 === 0) {

console.log(number + ' is even.');

else

console.log(number + ' is odd.');

checkEvenOrOdd(9);

checkEvenOrOdd(8);

Q4.

Write a loop that prints numbers from 100 to 90.

for (let i = 100; i >= 90; i--) {


console.log(i);

Q5.

Create an object representing a book with properties like title,


author, year Published, and genre.

const book = {

title: "The Great Gatsby",

author: "F. Scott Fitzgerald",

yearPublished: 1925,

genre: "Novel"

};

console.log(book);

};
Q7.

Demonstrate type conversion between different data types (e.g., string


to number, number to Boolean).

const str = "257";

const num = Number(str);

console.log(num);

const num2 = 0;

const bool = Boolean(num2);

console.log(bool);

Q8.

Create a class Person with properties for name and age.

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

}
const person = new Person("Lakhan”,23);

console.log(person);

Q9.

Add a method greet that prints a greeting message.

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

greet() {

console.log(`Hello, my name is ${this.name} and I am


${this.age} years old.`);

const person = new Person("Lakhan", 23);

person.greet();
Q10.

Create a subclass Student that extends Person and adds a property


for grade. Override the greet method to include the student's grade
in the message.

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

greet() {

console.log(`Hello, my name is ${this.name} and I am


${this.age} years old.`);

class Student extends Person {

constructor(name, age, grade) {

super(name, age);
this.grade = grade;

greet() {

console.log(`Hello, my name is ${this.name}, I am $


{this.age} years old, and I am in grade $
{this.grade}.`);

const student = new Student("Lakhan", 21, "C");

student.greet();

Q11.

Write a function to handle a condition which throws an exception

function checkCondition(condition) {

if (!condition) {

throw new Error("Condition not met!");

}
console.log("Condition met.");

try {

checkCondition(false);

} catch (e) {

console.error(e.message);

Q12.

Create a function that returns a promise which resolves after 2


seconds with a success message.

function resolve () {

return new Promise((resolve) => {

setTimeout(() => {

resolve("Success!");

}, 2000);

});

}
resolve ().then(message => console.log(message));

Q13.

Chain a.then method to log the success message and a .catch


method to handle any errors.

function resolve () {

return new Promise((resolve, reject) => {

setTimeout(() => {

resolve("Success!");

// reject("Failed!");

}, 2000);

});

resolve ()

.then(message => console.log(message))

.catch(error => console.error(error));


Q14.

Rewrite the above function (point 12) using async and await.

async function resolve () {

return new Promise((resolve) => {

setTimeout(() => {

resolve("Success!");

}, 2000);

});

async function run() {

try {

const message = await resolve ();

console.log(message);

} catch (error) {

console.error(error);

run();
Q15.

Create two files, math.js and app.js.

In math.js, export functions for addition and subtraction.

In app.js, import these functions and use them to perform some


calculations

function add(a, b) {

return a + b;

function subtract(a, b) {

return a - b;

module.exports = { add, subtract };

// app.js

const { add, subtract } = require('./math');

console.log(add(2, 5));

console.log(subtract(7, 5));
Q16.

Create a form with an input field and a submit button.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width,


initial-scale=1.0">

<title>Form Example</title>

</head>

<body>

<form id="myForm">

<input type="text" id="myInput" >

<button type="submit">Submit</button>

</form>

</body>

</html>
Q17.

Write JavaScript to prevent the form from submitting if the input


field is empty and display an error message.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width,


initial-scale=1.0">

<title>Form Example</title>

</head>

<body>

<form id="myForm">

<input type="text" id="myInput">

<button type="submit">Submit</button>

<p id="errorMessage" style="color:red;"></p>

</form>

<script>
document.getElementById('myForm').addEventListener('sub
mit', function(event) {

const inputField =
document.getElementById('myInput');

const errorMessage =
document.getElementById('errorMessage');

if (inputField.value.trim() === '') {

errorMessage.textContent = 'Input field cannot be


empty!';

event.preventDefault();

} else {

errorMessage.textContent = '';

});

</script>

</body>

</html>

You might also like