Welcome To StudyDoc Ltd.
StudyDoc

javascript Program

1
Hello World
console.log('Hello World');
2
Add Two Numbers
const num1 = 5; const num2 = 3; // add two numbers const sum = num1 + num2; // display the sum console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
3
Square Root of a Number
// take the input from the user const number = prompt('Enter the number: '); const result = Math.sqrt(number); console.log(`The square root of ${number} is ${result}`);
4
Traiangle Area When Base and Height is Known
const baseValue = prompt('Enter the base of a triangle: '); const heightValue = prompt('Enter the height of a triangle: '); // calculate the area const areaValue = (baseValue * heightValue) / 2; console.log( `The area of the triangle is ${areaValue}` );
5
swap two variables
//JavaScript program to swap two variables //take input from the users let a = prompt('Enter the first variable: '); let b = prompt('Enter the second variable: '); //create a temporary variable let temp; //swap variables temp = a; a = b; b = temp; console.log(`The value of a after swapping: ${a}`); console.log(`The value of b after swapping: ${b}`);
6
Convert Kilometers to Miles
// taking kilometers input from the user const kilometers = prompt("Enter value in kilometers: ") // conversion factor const factor = 0.621371 // calculate miles const miles = kilometers * factor console.log(`${kilometers} kilometers is equal to ${miles} miles.`);
7
convert celsius to fahrenheit
// program to convert celsius to fahrenheit // ask the celsius value to the user const celsius = prompt("Enter a celsius value: "); // calculate fahrenheit const fahrenheit = (celsius * 1.8) + 32 // display the result console.log(`${celsius} degree celsius is equal to ${fahrenheit} degree fahrenheit.`);
8
include constants
// program to include constants const a = 5; console.log(a); // constants are block-scoped { const a = 50; console.log(a); } console.log(a); const arr = ['work', 'exercise', 'eat']; console.log(arr); // add elements to arr array arr[3] = 'hello'; console.log(arr); // the following code gives error // changing the value of a throws an error // uncomment to verify // a = 8; // throws an error // const x;
9
generating a random number
// generating a random number const a = Math.random(); console.log(a);
10
positive, negative or zero
// program that checks if the number is positive, negative or zero // input from the user const number = parseInt(prompt("Enter a number: ")); // check if number is greater than 0 if (number > 0) { console.log("The number is positive"); } // check if number is 0 else if (number == 0) { console.log("The number is zero"); } // if number is less than 0 else { console.log("The number is negative"); }
11
number is even or odd
// program to check if the number is even or odd // take input from the user const number = prompt("Enter a number: "); //check if the number is even if(number % 2 == 0) { console.log("The number is even."); } // if the number is odd else { console.log("The number is odd."); }
12
largest among three numbers
// program to find the largest among three numbers // take input from the user const num1 = parseFloat(prompt("Enter first number: ")); const num2 = parseFloat(prompt("Enter second number: ")); const num3 = parseFloat(prompt("Enter third number: ")); let largest; // check the condition if(num1 >= num2 && num1 >= num3) { largest = num1; } else if (num2 >= num1 && num2 >= num3) { largest = num2; } else { largest = num3; } // display the result console.log("The largest number is " + largest);
13
prime or not
// program to check if a number is prime or not // take input from the user const number = parseInt(prompt("Enter a positive number: ")); let isPrime = true; // check if number is equal to 1 if (number === 1) { console.log("1 is neither prime nor composite number."); } // check if number is greater than 1 else if (number > 1) { // looping through 2 to number-1 for (let i = 2; i < number; i++) { if (number % i == 0) { isPrime = false; break; } } if (isPrime) { console.log(`${number} is a prime number`); } else { console.log(`${number} is a not prime number`); } } // check if number is less than 1 else { console.log("The number is not a prime number."); }
14
factorial of a number
// program to find the factorial of a number // take input from the user const number = parseInt(prompt('Enter a positive integer: ')); // checking if number is negative if (number < 0) { console.log('Error! Factorial for negative number does not exist.'); } // if number is 0 else if (number === 0) { console.log(`The factorial of ${number} is 1.`); } // if number is positive else { let fact = 1; for (i = 1; i <= number; i++) { fact *= i; } console.log(`The factorial of ${number} is ${fact}.`); }
15
multiplication table
// program to generate a multiplication table // take input from the user const number = parseInt(prompt('Enter an integer: ')); //creating a multiplication table for(let i = 1; i <= 10; i++) { // multiply i with number const result = i * number; // display the result console.log(`${number} * ${i} = ${result}`); }
16
fibonacci series up to n terms
// program to generate fibonacci series up to n terms // take input from the user const number = parseInt(prompt('Enter the number of terms: ')); let n1 = 0, n2 = 1, nextTerm; console.log('Fibonacci Series:'); for (let i = 1; i <= number; i++) { console.log(n1); nextTerm = n1 + n2; n1 = n2; n2 = nextTerm; }
17
Armstrong number
// program to check an Armstrong number of three digits let sum = 0; const number = prompt('Enter a three-digit positive integer: '); // create a temporary variable let temp = number; while (temp > 0) { // finding the one's digit let remainder = temp % 10; sum += remainder * remainder * remainder; // removing last digit from the number temp = parseInt(temp / 10); // convert float into integer } // check the condition if (sum == number) { console.log(`${number} is an Armstrong number`); } else { console.log(`${number} is not an Armstrong number.`); }
18
Armstrong number between intervals
// program to find Armstrong number between intervals // take an input const lowNumber = parseInt(prompt('Enter a positive low integer value: ')); const highNumber = parseInt(prompt('Enter a positive high integer value: ')); console.log ('Armstrong Numbers:'); // looping through lowNumber to highNumber for (let i = lowNumber; i <= highNumber; i++) { // converting number to string let numberOfDigits = i.toString().length; let sum = 0; // create a temporary variable let temp = i; /* loop through a number to find if a number is an Armstrong number */ while (temp > 0) { let remainder = temp % 10; sum += remainder ** numberOfDigits; // removing last digit from the number temp = parseInt(temp / 10); // convert float into integer } if (sum == i) { console.log(i); } }
19
simple calculator
// program for a simple calculator // take the operator input const operator = prompt('Enter operator ( either +, -, * or / ): '); // take the operand input const number1 = parseFloat(prompt('Enter first number: ')); const number2 = parseFloat(prompt('Enter second number: ')); let result; // using if...else if... else if (operator == '+') { result = number1 + number2; } else if (operator == '-') { result = number1 - number2; } else if (operator == '*') { result = number1 * number2; } else { result = number1 / number2; } // display the result console.log(`${number1} ${operator} ${number2} = ${result}`);
20
largest among
// program to find the largest among three numbers // take input from the user const num1 = parseFloat(prompt("Enter first number: ")); const num2 = parseFloat(prompt("Enter second number: ")); const num3 = parseFloat(prompt("Enter third number: ")); let largest; // check the condition if(num1 >= num2 && num1 >= num3) { largest = num1; } else if (num2 >= num1 && num2 >= num3) { largest = num2; } else { largest = num3; } // display the result console.log("The largest number is " + largest);
21
sum of natural numbers
// program to display the sum of natural numbers // take input from the user const number = parseInt(prompt('Enter a positive integer: ')); let sum = 0; // looping from i = 1 to number // in each iteration, i is increased by 1 for (let i = 1; i <= number; i++) { sum += i; } console.log('The sum of natural numbers:', sum);
22
last digit of three numbers is same
/* program to check whether the last digit of three numbers is same */ // take input const a = prompt('Enter a first integer: '); const b = prompt('Enter a second integer: '); const c = prompt('Enter a third integer: '); // find the last digit const result1 = a % 10; const result2 = b % 10; const result3 = c % 10; // compare the last digits if(result1 == result2 && result1 == result3) { console.log(`${a}, ${b} and ${c} have the same last digit.`); } else { console.log(`${a}, ${b} and ${c} have different last digit.`); }
23
HCF or GCD
// program to find the HCF or GCD of two integers let hcf; // take input const number1 = prompt('Enter a first positive integer: '); const number2 = prompt('Enter a second positive integer: '); // looping from 1 to number1 and number2 for (let i = 1; i <= number1 && i <= number2; i++) { // check if is factor of both integers if( number1 % i == 0 && number2 % i == 0) { hcf = i; } } // display the hcf console.log(`HCF of ${number1} and ${number2} is ${hcf}.`);
24
LCM
// program to find the LCM of two integers // take input const num1 = prompt('Enter a first positive integer: '); const num2 = prompt('Enter a second positive integer: '); // higher number among number1 and number2 is stored in min let min = (num1 > num2) ? num1 : num2; // while loop while (true) { if (min % num1 == 0 && min % num2 == 0) { console.log(`The LCM of ${num1} and ${num2} is ${min}`); break; } min++; }
25
factors of an integer
// program to find the factors of an integer // take input const num = prompt('Enter a positive number: '); console.log(`The factors of ${num} is:`); // looping through 1 to num for(let i = 1; i <= num; i++) { // check if number is a factor if(num % i == 0) { console.log(i); } }
26
sum of natural numbers
// program to find the sum of natural numbers using recursion function sum(num) { if(num > 0) { return num + sum(num - 1); } else { return num; } } // take input from the user const number = parseInt(prompt('Enter a positive integer: ')); const result = sum(number); // display the result console.log(`The sum is ${result}`);
27
guess a number
// program where the user has to guess a number generated by a program function guessNumber() { // generating a random integer from 1 to 10 const random = Math.floor(Math.random() * 10) + 1; // take input from the user let number = parseInt(prompt('Guess a number from 1 to 10: ')); // take the input until the guess is correct while(number !== random) { number = parseInt(prompt('Guess a number from 1 to 10: ')); } // check if the guess is correct if(number == random) { console.log('You guessed the correct number.'); } } // call the function guessNumber();
28
shuffle the deck of cards
// program to shuffle the deck of cards // declare card elements const suits = ["Spades", "Diamonds", "Club", "Heart"]; const values = [ "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", ]; // empty array to contain cards let deck = []; // create a deck of cards for (let i = 0; i < suits.length; i++) { for (let x = 0; x < values.length; x++) { let card = { Value: values[x], Suit: suits[i] }; deck.push(card); } } // shuffle the cards for (let i = deck.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * i); let temp = deck[i]; deck[i] = deck[j]; deck[j] = temp; } console.log('The first five cards are:'); // display 5 results for (let i = 0; i < 5; i++) { console.log(`${deck[i].Value} of ${deck[i].Suit}`) }
29
factorial of a number
// program to find the factorial of a number function factorial(x) { // if number is 0 if (x == 0) { return 1; } // if number is positive else { return x * factorial(x - 1); } } // take input from the user const num = prompt('Enter a positive number: '); // calling factorial() if num is positive if (num >= 0) { const result = factorial(num); console.log(`The factorial of ${num} is ${result}`); } else { console.log('Enter a positive number.'); }
30
convert decimal to binary
// program to convert decimal to binary function convertToBinary(x) { let bin = 0; let rem, i = 1, step = 1; while (x != 0) { rem = x % 2; console.log( `Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}` ); x = parseInt(x / 2); bin = bin + rem * i; i = i * 10; } console.log(`Binary: ${bin}`); } // take input let number = prompt('Enter a decimal number: '); convertToBinary(number);
31
ASCII
// program to find the ASCII value of a character // take input from the user const string = prompt('Enter a character: '); // convert into ASCII value const result = string.charCodeAt(0); console.log(`The ASCII value is: ${result}`);
32
palindrome or not
// program to check if the string is palindrome or not function checkPalindrome(string) { // find the length of a string const len = string.length; // loop through half of the string for (let i = 0; i < len / 2; i++) { // check if first and last string are same if (string[i] !== string[len - 1 - i]) { return 'It is not a palindrome'; } } return 'It is a palindrome'; } // take input const string = prompt('Enter a string: '); // call the function const value = checkPalindrome(string); console.log(value);
33
alphabetical order
// program to sort words in alphabetical order // take input const string = prompt('Enter a sentence: '); // converting to an array const words = string.split(' '); // sort the array elements words.sort(); // display the sorted words console.log('The sorted words are:'); for (const element of words) { console.log(element); }
34
replace a character
// program to replace a character of a string const string = 'Mr Red has a red house and a red car'; // replace the characters const newText = string.replace('red', 'blue'); // display the result console.log(newText);
35
reverse a string
// program to reverse a string function reverseString(str) { // empty string let newString = ""; for (let i = str.length - 1; i >= 0; i--) { newString += str[i]; } return newString; } // take input from the user const string = prompt('Enter a string: '); const result = reverseString(string); console.log(result);
36
create JavaScript object
// program to create JavaScript object using object literal const person = { name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], greet: function() { console.log('Hello everyone.'); }, score: { maths: 90, science: 80 } }; console.log(typeof person); // object // accessing the object value console.log(person.name); console.log(person.hobbies[0]); person.greet(); console.log(person.score.maths);
37
number of occurrence of a character
// program to check the number of occurrence of a character function countString(str, letter) { let count = 0; // looping through the items for (let i = 0; i < str.length; i++) { // check if the character is at that position if (str.charAt(i) == letter) { count += 1; } } return count; } // take input from the user const string = prompt('Enter a string: '); const letterToCheck = prompt('Enter a letter to check: '); //passing parameters and calling the function const result = countString(string, letterToCheck); // displaying the result console.log(result);
38
convert first letter uppercase
// program to convert first letter of a string to uppercase function capitalizeFirstLetter(str) { // converting first letter to uppercase const capitalized = str.charAt(0).toUpperCase() + str.slice(1); return capitalized; } // take input const string = prompt('Enter a string: '); const result = capitalizeFirstLetter(string); console.log(result);
39
number of vowels
// program to count the number of vowels in a string function countVowel(str) { // find the count of vowels const count = str.match(/[aeiou]/gi).length; // return number of vowels return count; } // take input const string = prompt('Enter a string: '); const result = countVowel(string); console.log(result);
40
remove a property
// program to remove a property from an object // creating an object const student = { name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], greet: function() { console.log('Hello everyone.'); }, score: { maths: 90, science: 80 } }; // deleting a property from an object delete student.greet; delete student['score']; console.log(student);
41
check if a string
// program to check if a string starts with 'S' and ends with 'G' function checkString(str) { // check if the string starts with S and ends with G if(str.startsWith('S') && str.endsWith('G')) { console.log('The string starts with S and ends with G'); } else if(str.startsWith('S')) { console.log('The string starts with S but does not end with G'); } else if(str.endsWith('G')) { console.log('The string starts does not with S but end with G'); } else { console.log('The string does not start with S and does not end with G'); } } // take input let string = prompt('Enter a string: '); checkString(string);
42
key exists
// program to check if a key exists const person = { id: 1, name: 'John', age: 23 } // check if key exists const hasKey = 'name' in person; if(hasKey) { console.log('The key exists.'); } else { console.log('The key does not exist.'); }
43
clone the object
// program to clone the object // declaring object const person = { name: 'John', age: 21, } // cloning the object const clonePerson = Object.assign({}, person); console.log(clonePerson); // changing the value of clonePerson clonePerson.name = 'Peter'; console.log(clonePerson.name); console.log(person.name);
44
loop through an object
// program to loop through an object using for...in loop const student = { name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], }; // using for...in for (let key in student) { let value; // get the value value = student[key]; console.log(key + " - " + value); }
45
merge property
// program to merge property of two objects // object 1 const person = { name: 'Jack', age:26 } // object 2 const student = { gender: 'male' } // merge two objects const newObj = Object.assign(person, student); console.log(newObj);
46
number of keys/properties in an object
// program to count the number of keys/properties in an object const student = { name: 'John', age: 20, hobbies: ['reading', 'games', 'coding'], }; let count = 0; // loop through each key/value for(let key in student) { // increase the count ++count; } console.log(count);
47
add a key/value pair
// program to add a key/value pair to an object const person = { name: 'Monica', age: 22, gender: 'female' } // add a key/value pair person.height = 5.4; console.log(person);
48
replace all occurrence
// program to replace all occurrence of a string const string = 'Mr Red has a red house and a red car'; // regex expression const regex = /red/gi; // replace the characters const newText = string.replace(regex, 'blue'); // display the result console.log(newText);
49
multiline strings
// program to create a multiline strings // using the + operator const message = 'This is a long message\n' + 'that spans across multiple lines\n' + 'in the code.' console.log(message);
50
format numbers as currency string
// program to format numbers as currency string const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); formatter.format(2500);
51
format numbers
// program to format numbers as currency string const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); formatter.format(2500);
52
generate random strings
// program to generate random strings // declare all characters const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; function generateString(length) { let result = ' '; const charactersLength = characters.length; for ( let i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } console.log(generateString(5));
53
starts with another string
// program to check if a string starts with another string const string = 'hello world'; const toCheckString = 'he'; if(string.startsWith(toCheckString)) { console.warn('The string starts with "he".'); } else { console.warn(`The string does not starts with "he".`); }
54
trim a string
// program to trim a string const string = ' Hello World '; const result = string.trim(); console.log(result);
55
string contains a substring
// program to check if a string contains a substring // take input const str = prompt('Enter a string:'); const checkString = prompt('Enter a string that you want to check:'); // check if string contains a substring if(str.includes(checkString)) { console.log(`The string contains ${checkString}`); } else { console.log(`The string does not contain ${checkString}`); }
56
perform string comparison
// js program to perform string comparison const string1 = 'JavaScript Program'; const string2 = 'javascript program'; // compare both strings const result = string1.toUpperCase() === string2.toUpperCase(); if(result) { console.log('The strings are similar.'); } else { console.log('The strings are not similar.'); }
57
encode a string to Base64
// program to encode a string to Base64 // defining the string const str = "Learning JavaScript"; // encoding the string const result = window.btoa(str); console.log(result); // decoding the string const result1 = window.atob(result); console.log(result1);
58
replace all instances
// program to replace all instances of a character in a string const string = 'Learning JavaScript Program'; const result = string.replace(/a/g, "A"); console.log(result);
59
date and time
// program to display the date and time // get date and time const date = new Date(2017, 2, 12, 9, 25, 30); // get the date as a string const n = date.toDateString(); // get the time as a string const time = date.toLocaleTimeString(); // display date console.log('Date: ' + n); // display time console.log('Time: ' + time);
60
check leap year
// program to check leap year function checkLeapYear(year) { //three conditions to find out the leap year if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) { console.log(year + ' is a leap year'); } else { console.log(year + ' is not a leap year'); } } // take input const year = prompt('Enter a year:'); checkLeapYear(year);
61
format the date
// program to format the date // get current date let currentDate = new Date(); // get the day from the date let day = currentDate.getDate(); // get the month from the date // + 1 because month starts from 0 let month = currentDate.getMonth() + 1; // get the year from the date let year = currentDate.getFullYear(); // if day is less than 10, add 0 to make consistent format if (day < 10) { day = '0' + day; } // if month is less than 10, add 0 if (month < 10) { month = '0' + month; } // display in various formats const formattedDate1 = month + '/' + day + '/' + year; console.log(formattedDate1); const formattedDate2 = month + '-' + day + '-' + year; console.log(formattedDate2); const formattedDate3 = day + '-' + month + '-' + year; console.log(formattedDate3); const formattedDate4 = day + '/' + month + '/' + year; console.log(formattedDate4);
62
display the date
// program to display the date // get local machine date time const date = new Date(); // get the date as a string const n = date.toDateString(); // get the time as a string const time = date.toLocaleTimeString(); // display date console.log('Date: ' + n); // display time console.log('Time: ' + time);
63
compare value of two dates
// program to compare value of two dates // create two dates const d1 = new Date(); const d2 = new Date(); // comparisons const compare1 = d1 < d2; console.log(compare1); const compare2 = d1 > d2; console.log(compare2); const compare3 = d1 <= d2; console.log(compare3); const compare4 = d1 >= d2; console.log(compare4); const compare5 = d1.getTime() === d2.getTime(); console.log(compare5); const compare6 = d1.getTime() !== d2.getTime(); console.log(compare6);
64
remove item from an array
// program to remove item from an array function removeItemFromArray(array, n) { const newArray = []; for ( let i = 0; i < array.length; i++) { if(array[i] !== n) { newArray.push(array[i]); } } return newArray; } const result = removeItemFromArray([1, 2, 3 , 4 , 5], 2); console.log(result);
65
insert an item into an array
// program to insert an item at a specific index into an array function insertElement() { let array = [1, 2, 3, 4, 5]; // index to add to let index = 3; // element that you want to add let element = 8; array.splice(index, 0, element); console.log(array); } insertElement();
66
check if an object is array
// program to check if an object is an array function checkObject(arr) { // check if arr is array const result = Array.isArray(arr); if(result) { console.log(`[${arr}] is an array.`); } else { console.log(`${arr} is not an array.`); } } const array = [1, 2, 3]; // call the function checkObject(array);