JavaScript Programs
JavaScript Programs
Number
// JavaScript Program to Find Factorial of a Number
var num = parseInt(prompt("Enter a positive integer: "));
// Checking if number is negative
if (num < 0){
console.log("Factorial of negative numbers doesn't exist.");
}
// Checking whether number equals to zero
else if (num == 0){
console.log("Factorial of 0 is: 1");
}
// Checking if number is positive
else{
let fact = 1;
for (i = 1; i <= num; ++i){
fact = fact * i;
}
console.log(`Factorial of ${num} is: ${fact}.`);
}
JavaScript Program To Find Average of 3
Numbers
//JavaScript Program To Find Average of 3 Numbers
//Take User Input
var a = parseInt(prompt("Enter First Number: "));
var b = parseInt(prompt("Enter Second Number: "));
var c = parseInt(prompt("Enter Third Number: "));
//Calculate Average
var average = (a + b + c) / 3;
//Display Output
console.log("The average of three numbers: " + average);
Output
Average of Numbers between 1 and 5 is:
Total Sum: 15
No. of elements: 5
Avera
JavaScript Program To Calculate The
Area of a Triangle
//JavaScript Program To Calculate The Area of a Triangle
var base = parseInt(prompt("Enter the base: "));
var height = parseInt(prompt("Enter the height: "));
//Calculating the area
var area = (base * height) / 2;
//Display Output
console.log("Base: " + base);
console.log("Height: " + height);
console.log("The area of the triangle is " + area);
Output
Base: 3
Height: 4
The area of the triangle is 6
Output
The Sum of 2 and 3 is: 5
Output
The sum of 5 and 7 is: 12
Example 1: Check Palindrome Using for Loop
// program to check if the string is palindrome or not
function checkPalindrome(string) {
// take input
const string = prompt('Enter a string: ');
console.log(value);
Run Code
Output
In the above program, the checkPalindrome() function takes input from the
user.
The length of the string is calculated using the length property.
The for loop is used to iterate up to the half of the string. The if condition is
used to check if the first and the corresponding last characters are the
same. This loop continues till the half of the string.
During the iteration, if any character of the string, when compared with its
corresponding last string is not equal, the string is not considered a
palindrome.
function checkPalindrome(string) {
if(string == reverseString) {
console.log('It is a palindrome');
}
else {
console.log('It is not a palindrome');
}
}
//take input
const string = prompt('Enter a string: ');
checkPalindrome(string);
Run Code
Output
The split('') method converts the string into individual array characters.
The join('') method joins all the elements of an array into a string.
Then the if...else statement is used to check if the string and the reversed
string are equal. If they are equal, the string is a palindrome.
Note: The multiple lines of code can be reduced and written in one line: