Questions Function, Closure, Callback
Questions Function, Closure, Callback
2. Write a JavaScript function getFirstElement that takes an array as an argument and returns the
first element of the array. Provide an example with an array of your choice.
function getFirstElement(array) {
if (array.length === 0) {
return undefined;
}
return array[0];
}
const exampleArray = [10, 20, 30, 40, 50];
const firstElement = getFirstElement(exampleArray);
console.log(`The first element is ${firstElement}.`);
3. Define a JavaScript object person with properties name, age, and city. Write a function
getPersonInfo that takes this object and returns a string with the person's details in the format
"Name: [name], Age: [age], City: [city]".
const person = {
name: 'Ram Thapa',
age: 30,
city: 'New Baneshword'
};
function getPersonInfo(person) {
return `Name: ${person.name}, Age: ${person.age}, City: $
{person.city}`;
}
const personInfo = getPersonInfo(person);
console.log(personInfo);
4. Write a JavaScript function toUpperCase that takes a string as an argument and returns the
string in all uppercase letters. Provide an example with a sample string.
function toUpperCase(str) {
return str.toUpperCase();
}
const sampleString = 'hello world';
const upperCaseString = toUpperCase(sampleString);
console.log(upperCaseString);
5. Write a JavaScript function multiply that takes two numbers as arguments and returns their
product. Provide an example of calling this function with two numbers.
function multiply(a, b) {
return a * b;
}
const num1 = 6;
const num2 = 7;
const product = multiply(num1, num2);
console.log(`The product of ${num1} and ${num2} is ${product}.`);
6. Write a JavaScript function getLastElement that takes an array as an argument and returns the
last element of the array. Provide an example with an array of your choice.
function getLastElement(array) {
if (array.length === 0) {
return undefined;
}
return array[array.length - 1];
}
const exampleArray = [10, 20, 30, 40, 50];
const lastElement = getLastElement(exampleArray);
console.log(`The last element is ${lastElement}.`);
7. Define a JavaScript object book with properties title, author, and year. Write a function
getBookTitle that takes this object and returns the title of the book.
const book = {
title: 'Science',
author: 'Sanjeev',
year: 1960
};
function getBookTitle(book) {
return book.title;
}
const bookTitle = getBookTitle(book);
console.log(`The title of the book is "${bookTitle}".`);
8. Write a JavaScript function reverseString that takes a string as an argument and returns the
string reversed. Provide an example with a sample string.
function reverseString(str) {
return str.split('').reverse().join('');
}
const sampleString = 'hello world';
const reversedString = reverseString(sampleString);
console.log(`The reversed string is "${reversedString}".`);
9. Write a JavaScript function isEven that takes a number as an argument and returns true if the
number is even and false if it is odd. Provide an example with a sample number.
function isEven(number) {
return number % 2 === 0;
}
const sampleNumber = 42;
const isSampleNumberEven = isEven(sampleNumber);
console.log(`Is the number ${sampleNumber} even? $
{isSampleNumberEven}.`);
10. Write a JavaScript function sumArray that takes an array of numbers as an argument and
returns the sum of all the numbers in the array. Provide an example with an array of numbers.
function sumArray(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
const numbersArray = [1, 2, 3, 4, 5];
const totalSum = sumArray(numbersArray);
console.log(`The sum of the array is ${totalSum}.`);
11. Define a JavaScript object car with properties make, model, and year. Write a function
getCarModel that takes this object and returns the model of the car.
const car = {
make: 'Toyota',
model: 'Corolla',
year: 2020
};
function getCarModel(car) {
return car.model;
}
const carModel = getCarModel(car);
console.log(`The model of the car is ${carModel}.`);
12. Write a JavaScript function concatenateStrings that takes two strings as arguments and returns a
new string that is the concatenation of the two input strings. Provide an example with two
sample strings.
function concatenateStrings(str1, str2) {
return str1 + str2;
}
const string1 = 'Hello, ';
const string2 = 'world!';
const concatenatedString = concatenateStrings(string1, string2);
console.log(`The concatenated string is "${concatenatedString}".`);
13. Write a JavaScript function square that takes a number as an argument and returns its square.
Provide an example of calling this function with a sample number.
function square(number) {
return number * number;
}
const sampleNumber = 4;
const squaredNumber = square(sampleNumber);
console.log(`The square of ${sampleNumber} is ${squaredNumber}.`);
14. Write a JavaScript function findMax that takes an array of numbers as an argument and returns
the largest number in the array. Provide an example with an array of numbers.
function findMax(numbers) {
if (numbers.length === 0) {
return undefined;
}
let max = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
const numbersArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const maxNumber = findMax(numbersArray);
console.log(`The largest number in the array is ${maxNumber}.`);
15. Define a JavaScript object student with properties firstName, lastName, and grade. Write a
function getFullName that takes this object and returns the full name of the student in the
format "firstName lastName".
const student = {
firstName: 'Sanjeev',
lastName: 'Shrestha',
grade: 'A'
};
function getFullName(student) {
return `${student.firstName} ${student.lastName}`;
}
const fullName = getFullName(student);
console.log(`The full name of the student is "${fullName}".`);
16. Write a JavaScript function greet that takes a name as an argument and returns a greeting string
in the format "Hello, [name]!". Provide an example of calling this function with a sample name.
function greet(name) {
return `Hello, ${name}!`;
}
const sampleName = 'Sandesh';
const greeting = greet(sampleName);
console.log(greeting);
17. Write a JavaScript function doubleArray that takes an array of numbers as an argument and
returns a new array with each number doubled. Provide an example with an array of numbers.
function doubleArray(numbers) {
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(numbers[i] * 2);
}
return doubledNumbers;
}
const numbersArray = [1, 2, 3, 4, 5];
const doubledArray = doubleArray(numbersArray);
console.log(`The doubled array is ${doubledArray}.`);
18. Define a JavaScript object movie with properties title, director, and releaseYear. Write a
function getMovieTitle that takes this object and returns the title of the movie.
const movie = {
title: 'Inception',
director: 'Christopher Nolan',
releaseYear: 2010
};
function getMovieTitle(movie) {
return movie.title;
}
const movieTitle = getMovieTitle(movie);
console.log(`The title of the movie is "${movieTitle}".`);
19. Write a JavaScript function getLength that takes a string as an argument and returns the length
of the string. Provide an example with a sample string.
function getLength(str) {
return str.length;
}
const sampleString = 'hello world';
const stringLength = getLength(sampleString);
console.log(`The length of the string is ${stringLength}.`);
20. Write a JavaScript function subtract that takes two numbers as arguments and returns their
difference. Provide an example of calling this function with two numbers.
function subtract(a, b) {
return a - b;
}
const num1 = 10;
const num2 = 3;
const difference = subtract(num1, num2);
console.log(`The difference between ${num1} and ${num2} is $
{difference}.`);
21. Write a JavaScript function mergeArrays that takes two arrays as arguments and returns a new
array containing all elements from both arrays. Provide an example with two arrays.
function mergeArrays(array1, array2) {
return array1.concat(array2);
}
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = mergeArrays(array1, array2);
console.log(`The merged array is ${mergedArray}.`);
22. Define a JavaScript object recipe with properties name, ingredients (an array), and servings.
Write a function getIngredientList that takes this object and returns the ingredients array.
const recipe = {
name: 'Pancakes',
ingredients: ['flour', 'milk', 'eggs', 'sugar', 'baking powder'],
servings: 4
};
function getIngredientList(recipe) {
return recipe.ingredients;
}
const ingredientList = getIngredientList(recipe);
console.log(`The ingredients are ${ingredientList}.`);
23. Write a JavaScript function endsWith that takes a string and a character as arguments and
returns true if the string ends with the given character, otherwise false. Provide an example with
a sample string and character.
function endsWith(str, char) {
return str.charAt(str.length - 1) === char;
}
const sampleString = 'hello';
const sampleChar = 'o';
const result = endsWith(sampleString, sampleChar);
console.log(`Does the string "${sampleString}" end with "${sampleChar}"?
${result}`);
24. Write a JavaScript function divide that takes two numbers as arguments and returns their
quotient. Provide an example of calling this function with two numbers.
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed.');
}
return a / b;
}
const num1 = 10;
const num2 = 2;
const quotient = divide(num1, num2);
console.log(`The quotient of ${num1} divided by ${num2} is $
{quotient}.`);
25. Write a JavaScript function removeFirstElement that takes an array as an argument and returns
a new array with the first element removed. Provide an example with an array.
function removeFirstElement(array) {
return array.slice(1);
}
const array = [10, 20, 30, 40, 50];
const newArray = removeFirstElement(array);
console.log(`The new array with the first element removed is $
{newArray}.`);
26. Define a JavaScript object album with properties title, artist, and tracks (an array of track
names). Write a function getTrackCount that takes this object and returns the number of tracks.
const album = {
title: 'Aacharya',
artist: 'Bhakta Raj Acharya',
tracks: ['Jaha Chan Buddhaka Aankha', 'Hajar Aankha']
};
function getTrackCount(album) {
return album.tracks.length;
}
const trackCount = getTrackCount(album);
console.log(`The album "${album.title}" has ${trackCount} tracks.`);
27. Write a JavaScript function startsWith that takes a string and a character as arguments and
returns true if the string starts with the given character, otherwise false. Provide an example
with a sample string and character.
function startsWith(str, char) {
return str.charAt(0) === char;
}
const sampleString = 'hello';
const sampleChar = 'h';
const result = startsWith(sampleString, sampleChar);
console.log(`Does the string "${sampleString}" start with "$
{sampleChar}"? ${result}`);
28. Write a JavaScript function isPositive that takes a number as an argument and returns true if the
number is positive and false if it is negative or zero. Provide an example with a sample number.
function isPositive(number) {
return number > 0;
}
const sampleNumber = 5;
const isSampleNumberPositive = isPositive(sampleNumber);
console.log(`Is the number ${sampleNumber} positive? $
{isSampleNumberPositive}`);
29. Write a JavaScript function countElements that takes an array as an argument and returns the
number of elements in the array. Provide an example with an array.
function countElements(array) {
return array.length;
}
const exampleArray = [1, 2, 3, 4, 5];
const elementCount = countElements(exampleArray);
console.log(`The array has ${elementCount} elements.`);
30. Define a JavaScript object game with properties name, genre, and platforms (an array of
strings). Write a function getPlatformList that takes this object and returns the platforms array.
const game = {
name: 'The Legend of Zelda: Breath of the Wild',
genre: 'Action-adventure',
platforms: ['Nintendo Switch', 'Wii U']
};
function getPlatformList(game) {
return game.platforms;
}
const platformList = getPlatformList(game);
console.log(`The game "${game.name}" is available on the following
platforms: ${platformList.join(', ')}.`);