- Write a JavaScript program to find the maximum number in an array.
- Write a JavaScript function to check if a given string is a palindrome (reads the same forwards and backwards).
- Write a JavaScript program to reverse a given string.
Q) Write a JavaScript program to find the maximum number in an array.
Ans:
function findMax(arr) {
if (arr.length === 0) {
return "Array is empty";
}
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Example usage:
const numbers = [10, 5, 20, 8, 15];
const maxNumber = findMax(numbers);
console.log("The maximum number in the array is:", maxNumber);
Q) Write a JavaScript function to check if a given string is a palindrome (reads the same forwards and backwards).
Ans:
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Compare the original string with its reverse
return cleanStr === cleanStr.split('').reverse().join('');
}
// Example usage:
const string1 = "radar";
const string2 = "hello";
console.log(`"${string1}" is a palindrome:`, isPalindrome(string1)); // true
console.log(`"${string2}" is a palindrome:`, isPalindrome(string2)); // false
Q) Write a JavaScript program to reverse a given string.
Ans:
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
// Example usage:
const originalString = "hello";
const reversedString = reverseString(originalString);
console.log("Original string:", originalString);
console.log("Reversed string:", reversedString);