Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

1. Write a JavaScript program to display the current day and time in the following format.

 
Sample Output : Today is : Tuesday.
Current time is : 10 PM : 30 : 38
Click me to see the solution

2. Write a JavaScript program to print the current window contents.  


Click me to see the solution

3. Write a JavaScript program to get the current date.  


Expected Output :
mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy
Click me to see the solution

4. Write a JavaScript program to find the area of a triangle where three sides are 5, 6, 7.  
Click me to see the solution

5. Write a JavaScript program to rotate the string 'w3resource' in the right direction. This is done
by periodically removing one letter from the string end and attaching it to the front.  
Click me to see the solution

6. Write a JavaScript program to determine whether a given year is a leap year in the Gregorian
calendar.  
Click me to see the solution

7. Write a JavaScript program to find out if 1st January will be a Sunday between 2014 and
2050.  
Click me to see the solution

8. Write a JavaScript program where the program takes a random integer between 1 and 10, and
the user is then prompted to input a guess number. The program displays a message "Good
Work" if the input matches the guess number otherwise "Not matched".  
Click me to see the solution

9. Write a JavaScript program to calculate the days left before Christmas.  


Click me to see the solution

10. Write a JavaScript program to calculate multiplication and division of two numbers (input
from the user).  
Sample form :
Click me to see the solution

11. Write a JavaScript program to convert temperatures to and from Celsius, Fahrenheit.  
[ Formula : c/5 = (f-32)/9 [ where c = temperature in Celsius and f = temperature in Fahrenheit ]
Expected Output :
60°C is 140 °F
45°F is 7.222222222222222°C
Click me to see the solution

12. Write a JavaScript program to get the website URL (loading page).  
Click me to see the solution

13. Write a JavaScript exercise to create a variable using a user-defined name.  


Click me to see the solution

14. Write a JavaScript exercise to get the filename extension.  


Click me to see the solution

15. Write a JavaScript program to get the difference between a given number and 13, if the
number is broader than 13 return double the absolute difference.  
Click me to see the solution

16. Write a JavaScript program to compute the sum of the two given integers. If the two values
are the same, then return triple their sum.  
Click me to see the solution

17. Write a JavaScript program to compute the absolute difference between a specified number
and 19. Returns triple the absolute difference if the specified number is greater than 19.  
Click me to see the solution

18. Write a JavaScript program to check a pair of numbers and return true if one of the numbers
is 50 or if their sum is 50.  
Click me to see the solution

19. Write a JavaScript program to check whether a given integer is within 20 of 100 or 400.  
Click me to see the solution
20. Write a JavaScript program to check two given integers whether one is positive and another
one is negative.  
Click me to see the solution

21. Write a JavaScript program to create another string by adding "Py" in front of a given string.
If the given string begins with "Py" return the original string.  
Click me to see the solution

22. Write a JavaScript program to remove a character at the specified position in a given string
and return the modified string.  
Click me to see the solution

23. Write a JavaScript program to create a new string from a given string by changing the
position of the first and last characters. The string length must be broader than or equal to 1.  
Click me to see the solution

24. Write a JavaScript program to create another string from a given string with the first
character of the given string added to the front and back.  
Click me to see the solution

25. Write a JavaScript program to check whether a given positive number is a multiple of 3 or 7.

Click me to see the solution

26. Write a JavaScript program to create a string from a given string. This is done by taking the
last 3 characters and adding them at both the front and back. The string length must be 3 or more.

Click me to see the solution

27. Write a JavaScript program to check whether a string starts with 'Java' if it does not
otherwise.  
Click me to see the solution

28. Write a JavaScript program to check whether two given integer values are in the range 50..99
(inclusive). Return true if either of them falls within the range.  
Click me to see the solution

29. Write a JavaScript program to check whether three given integer values are in the range
50..99 (inclusive). Return true if one or more of them are in the specified range.  
Click me to see the solution

30. Write a JavaScript program to check whether a string "Script" appears at the 5th (index 4)
position in a given string. If "Script" appears in the string, return the string without "Script"
otherwise return the original one.  
Click me to see the solution
31. Write a JavaScript program to find the largest of three given integers.  
Click me to see the solution

32. Write a JavaScript program to find the closest value to 100 from two numerical values.  
Click me to see the solution

33. Write a JavaScript program to check whether two numbers are in the range 40..60 or 70..100
inclusive.  
Click me to see the solution

34. Write a JavaScript program to find the largest number from the two given positive integers.
The two numbers are in the range 40..60 inclusive.  
Click me to see the solution

35. Write a program to check whether a specified character exists between the 2nd and 4th
positions in a given string.  
Click me to see the solution

36. Write a JavaScript program that checks whether the last digit of three positive integers is the
same.  
Click me to see the solution

37. Write a JavaScript program to produce a new string that has the first 3 characters in lower
case from a given string. If the string length is less than 3 convert all the characters to upper case.

Click me to see the solution

38. Write a JavaScript program to check a student's total marks in various examinations. The
student will get A+ grade if the total marks are in the range 89..100 inclusive, if the examination
is "Final-exam" the student will receive A+ grade and total marks must be greater than or equal
to 90. If the student gets an A+ grade, return true, otherwise return false.  
Click me to see the solution

39. Write a JavaScript program to compute the sum of the two given integers. If the sum is in the
range 50..80 return 65 otherwise return 80.  
Click me to see the solution

40. Write a JavaScript program to check from two given integers whether one of them is 8 or
their sum or difference is 8.  
Click me to see the solution

41. Write a JavaScript program to check a set of three numbers; if the three numbers are the
same return 30; otherwise return 20; and if two numbers are the same return 40.  
Click me to see the solution
42. Write a JavaScript program to check whether three given numbers are increasing in strict or
in soft mode.  
Note: Strict mode -> 10, 15, 31 : Soft mode -> 24, 22, 31 or 22, 22, 31
Click me to see the solution

43. Write a JavaScript program to check from three given numbers (non negative integers) that
two or all of them have the same rightmost digit.  
Click me to see the solution

44. Write a JavaScript program to check from three given integers whether a number is greater
than or equal to 20. It is less than the others.  
Click me to see the solution

45. Write a JavaScript program that checks two integer values and returns true if either one is 15
or if their sum or difference is 15.  
Click me to see the solution

46. Write a JavaScript program to check two given non-negative integers if one (not both) is a
multiple of 7 or 11.  
Click me to see the solution

47. Write a JavaScript program to check whether a given number exists in the range 40..10000.  
For example 40 presents in 40 and 4000
Click me to see the solution

48. Write a JavaScript program to reverse a given string.  


Click me to see the solution

49. Write a JavaScript program to replace every character in a given string with the character
following it in the alphabet.  
Click me to see the solution

50. Write a JavaScript program to capitalize the first letter of each word in a given string.  
Click me to see the solution

51. Write a JavaScript program to convert a given number into hours and minutes.  
Click me to see the solution

52. Write a JavaScript program to convert letters of a given string alphabetically.  


Click me to see the solution

53. Write a JavaScript program to check whether the characters a and b are separated by exactly
3 places anywhere (at least once) in a given string.  
Click me to see the solution
54. Write a JavaScript program to count the number of vowels in a given string.  
Click me to see the solution

55. Write a JavaScript program to check whether a given string contains an equal number of p's
and t's.  
Click me to see the solution

56. Write a JavaScript program to divide two positive numbers and return the result as string
with properly formatted commas.  
Click me to see the solution

57. Write a JavaScript program to create one string of specified copies (positive numbers) of a
given string.  
Click me to see the solution

58. Write a JavaScript program to create an updated string of 4 copies of the last 3 characters of a
given original string. The string length must be 3 and above.  
Click me to see the solution

59. Write a JavaScript program to extract the first half of a even string.  
Click me to see the solution

60. Write a JavaScript program to create a new string without the first and last characters of a
given string.  
Click me to see the solution

61. Write a JavaScript program to concatenate two strings except for their first character.  
Click me to see the solution

62. Write a JavaScript program to move the last three characters to the start of a given string. The
string length must be greater than or equal to three.  
Click me to see the solution

63. Write a JavaScript program to create a string using the middle three characters of a given
string of odd length. The string length must be greater than or equal to three.  
Click me to see the solution

64. Write a JavaScript program to concatenate two strings and return the result. If the length of
the strings does not match, then remove the characters from the longer string.  
Click me to see the solution

65. Write a JavaScript program to test whether a string ends with "Script". The string length must
be greater than or equal to 6.  
Click me to see the solution
66. Write a JavaScript program to display the city name if the string begins with "Los" or "New"
otherwise return blank.  
Click me to see the solution

67. Write a JavaScript program to create a new string from a given string. This program removes
the first and last characters of the string if the first or last character is 'P'. Return the original
string if the condition is not satisfied.  
Click me to see the solution

68. Write a JavaScript program to create a new string using the first and last n characters from a
given string. The string length must be larger than or equal to n.  
Click me to see the solution

69. Write a JavaScript program to compute the sum of three elements of a given array of integers
of length 3.  
Click me to see the solution

70. Write a JavaScript program to rotate the elements left in a given array of integers of length 3.

Click me to see the solution

71. Write a JavaScript program to check whether 1 appears in the first or last position of a given
array of integers. The array length must be larger than or equal to 1.  
Click me to see the solution

72. Write a JavaScript program to check whether the first and last elements are the same in a
given array of integers of length 3.  
Click me to see the solution

73. Write a JavaScript program to reverse the elements of a given array of integers of length 3.  
Click me to see the solution

74. Write a JavaScript program to find the largest value between the first and last elements and
set all the other elements to that value. Display the updated array.  
Click me to see the solution

75. Write a JavaScript program to create an array taking the middle elements of the two arrays of
integer and each length 3.  
Click me to see the solution

76. Write a JavaScript program to create an array by taking the first and last elements from a
given array of integers. The length must be larger than or equal to 1.  
Click me to see the solution

77. Write a JavaScript program to test whether an array of integers of length 2 contains 1 or 3.  
Click me to see the solution
78. Write a JavaScript program to test whether an array of integers of length 2 does not contain 1
or 3.  
Click me to see the solution

79. Write a JavaScript program to test whether a given array of integers contains 30 and 40
twice. The array length should be 0, 1, or 2.  
Click me to see the solution

80. Write a JavaScript program to swap the first and last elements of a given array of integers.
The array length should be at least 1.  
Click me to see the solution

81. Write a JavaScript program to add two digits to a given positive integer of length two.  
Click me to see the solution

82. Write a JavaScript program to add two positive integers without carrying.  
Click me to see the solution

83. Write a JavaScript program to find the longest string from a given array of strings.  
Click me to see the solution

84. Write a JavaScript program to replace each character in a given string with the next in the
English alphabet.  
Note: 'a' will be replace by 'b' or 'z' would be replaced by 'a'.
Click me to see the solution

85. Write a JavaScript program to divide a given array of positive integers into two parts. First
element belongs to the first part, second element belongs to the second part, and third element
belongs to the first part and so on. Now compute the sum of two parts and store it in an array of
size two.  
Click me to see the solution

86. Write a JavaScript program to find the types of a given angle.  

Types of angles:

 Acute angle: An angle between 0 and 90 degrees.


 Right angle: An 90 degree angle.
 Obtuse angle: An angle between 90 and 180 degrees.
 Straight angle: A 180 degree angle.

Click me to see the solution

87. Write a JavaScript program to determine if two arrays of integers of the same length are
similar. The arrays will be similar if one array can be obtained from another array by swapping at
most one pair of elements.  
Click me to see the solution

88. Write a JavaScript program that takes two integers and a divisor. If the given divisor divides
both integers and does not divide either, two specified integers are similar. Check whether two
integers are similar or not.  
Click me to see the solution

89. Write a JavaScript program to check whether it is possible to replace $ in a given expression
x $ y = z with one of the four signs +, -, * or / to obtain a correct expression.  
For example x = 10, y = 30 and z = 300, we can replace $ with a multiple operator (*) to obtain x
*y=z
Click me to see the solution

90. Write a JavaScript program to find the kth greatest element in a given array of integers.  
Click me to see the solution

91. Write a JavaScript program to find the maximum possible sum of some of its k consecutive
numbers (numbers that follow each other in order) in a given array of positive integers. 
Click me to see the solution

92. Write a JavaScript program to find the maximum difference between any two adjacent
elements of a given array of integers. 
Click me to see the solution

93. Write a JavaScript program to find the maximum difference among all possible pairs of a
given array of integers. 
Click me to see the solution

94. Write a JavaScript program to find the number appearing most frequently in a given array of
integers. 
Click me to see the solution

95. Write a JavaScript program to replace all numbers with a specified number in an array of
integers. 
Click me to see the solution

96. Write a JavaScript program to compute the sum of the absolute differences of consecutive
numbers in a given array of integers. 
Click me to see the solution

97. Write a JavaScript program to find the shortest possible string. This can be converted into a
string and converted into a palindrome by adding characters to the end of it. 
Click me to see the solution
98. Write a JavaScript program to change the case of the minimum number of letters to make a
given string written in upper case or lower case. 
Fox example "Write" will be write and "PHp" will be "PHP"
Click me to see the solution

99. Write a JavaScript program to check whether it is possible to rearrange the characters of a
given string. This is in such a way that it will become equal to another given string. 
Click me to see the solution

100. Write a JavaScript program to check if there is at least one element in two given sorted
arrays of integers. 
Click me to see the solution

101. Write a JavaScript program to check whether a given string contains only Latin letters and
no two uppercase and no two lowercase letters are in adjacent positions. 
Click me to see the solution

102. Write a JavaScript program to find the number of inversions of a given array of integers. 
Note: Two elements of the array a stored at positions i and j form an inversion if a[i] > a[j] and i
< j.
Click me to see the solution

103. Write a JavaScript program to find the maximum number of a given positive integer by
deleting exactly one digit of the given number.  
Click me to see the solution

104. Write a JavaScript program to find two elements of an array such that their absolute
difference is not larger than a given integer. However, it is as close as possible to the integer. 
Click me to see the solution

105. Write a JavaScript program to find the number of times to replace a given number with the
sum of its digits. This is until it converts to a single-digit number. 
Click me to see the solution

106. Write a JavaScript program to divide an integer by another integer as long as the result is an
integer and return the result. 
Click me to see the solution

107. Write a JavaScript program to find the number of sorted pairs formed by arrays of integers.
This is such that one element in the pair is divisible by the other one. 
For example - The output of [1, 3, 2] ->2 - (1,3), (1,2).
The output of [2, 4, 6] -> 2 - (2,4), (2,6)
The output of [2, 4, 16] -> 3 - (2,4), (2,16), (4,16)
Click me to see the solution
108. Write a JavaScript program to create the dot products of two given 3D vectors. 
Note: The dot product is the sum of the products of the corresponding entries of the two
sequences of numbers.
Click me to see the solution

109. Write a JavaScript program to sort an array of all prime numbers between 1 and a given
integer. 
Click me to see the solution

110. Write a JavaScript program to find the number of even values in sequence before the first
occurrence of a given number. 
Click me to see the solution

111. Write a JavaScript program to check a number from three given numbers where two
numbers are equal. Find the third one. 
Click me to see the solution

112. Write a JavaScript program to find the number of trailing zeros in the decimal
representation of the factorial of a given number. 
Click me to see the solution

113. Write a JavaScript program to calculate the sum of n + n/2 + n/4 + n/8 + .... where n is a
positive integer and all divisions are integers. 
Click me to see the solution

114. Write a JavaScript program to check whether a given string represents a correct sentence or
not. A string is considered a correct sentence if it starts with a capital letter and ends with a full
stop (.) 
Click me to see the solution

115. Write a JavaScript program to check whether a matrix is a diagonal matrix or not. In linear
algebra, a diagonal matrix is a matrix in which the entries outside the main diagonal are all zero
(the diagonal from the upper left to the lower right). 
Example:
[1, 0, 0], [0, 2, 0], [0, 0, 3] ]) = true
[1, 0, 0], [0, 2, 3], [0, 0, 3] ]) = false
Click me to see the solution

116. Write a JavaScript program to find all the possible options to replace the hash in a string
(Consists of digits and one hash (#)) with a digit to produce an integer divisible by 3. 
For a string "2*0", the output should be : ["210", "240", "270"]
Click me to see the solution

117. Write a JavaScript program to check whether a given matrix is an identity matrix. 
Note: In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of
size n is the n ? n square matrix with ones on the main diagonal and zeros elsewhere.
[[1, 0, 0], [0, 1, 0], [0, 0, 1]] -> true
[[1, 0, 0], [0, 1, 0], [1, 0, 1]] -> false
Click me to see the solution

118. Write a JavaScript program to check whether a given number is in a given range. 
Click me to see the solution

119. Write a JavaScript program to check if a given integer has an increasing digit sequence. 
Click me to see the solution

120. Write a JavaScript program to check if a point lies strictly inside the circle. 
Input:
Center of the circle (x, y)
Radius of circle: r
Point inside a circle (a, b)
Click me to see the solution

121. Write a JavaScript program to check whether a given matrix is lower triangular or not. 
Note: A square matrix is called lower triangular if all the entries above the main diagonal are
zero.
Click me to see the solution

122. Write a JavaScript program to check whether a given array of integers represents a strictly
increasing or decreasing sequence. 
Click me to see the solution

123. Write a JavaScript program to find out if the members of a given array of integers are a
permutation of numbers from 1 to a given integer. 
Click me to see the solution

124. Write a JavaScript program to create the NOR value of two given booleans. 
Note: In boolean logic, logical nor or joint denial is a truth-functional operator which produces a
result that is the negation of logical or. That is, a sentence of the form (p NOR q) is true precisely
when neither p nor q is true - i.e. when both of p and q are false
Sample Example:
For x = true and y = false, the output should be logical_Nor(x, y) = false; For x = false and y =
false, the output should be logical_Nor(x, y) = true.

Click me to see the solution

125. Write a JavaScript program to find the longest string in a given array. 
Click me to see the solution

126. Write a JavaScript program to get the largest even number from an array of integers. 
Click me to see the solution
127. Write a JavaScript program to reverse the order of bits in a integer. 
14 -> 00001110 -> 01110000 -> 112
56 -> 00111000 -> 00011100 -> 28
234 -> 11101010 -> 01010111 -> 87
Click me to see the solution

128. Write a JavaScript program to find the smallest round number not less than a given value. 
Note: A round number is informally considered to be an integer that ends with one or more
zeros.[3] So, 590 is rounder than 592, but 590 is less round than 600.
Click me to see the solution

129. Write a JavaScript program to find the smallest prime number strictly greater than a given
number. 
Click me to see the solution

130. Write a JavaScript program to find the number of even digits in a given integer. 
Click me to see the solution

131. Write a JavaScript program to create an array of prefix sums of the given array. 
In computer science, the prefix sum, cumulative sum, inclusive scan, or simply scan of a
sequence of numbers x0, x1, x2, ... is a second sequence of numbers y0, y1, y2, ..., the sums of
prefixes of the input sequence:
y0 = x0
y1 = x0 + x1
y2 = x0 + x1+ x2
...
Click me to see the solution

132. Write a JavaScript program to find all distinct prime factors of a given integer. 
Click me to see the solution

133. Write a JavaScript program to check whether a given fraction is proper or not. 
Note: There are two types of common fractions, proper or improper. When the numerator and the
denominator are both positive, the fraction is called proper if the numerator is less than the
denominator, and improper otherwise.
Click me to see the solution

134. Write a JavaScript program to change the characters (lower case) in a string where a turns
into z, b turns into y, c turns into x, ..., n turns into m, m turns into n, ..., z turns into a. 
Click me to see the solution

135. Write a JavaScript program to remove all characters from a given string that appear more
than once. 
Click me to see the solution
136. Write a JavaScript program to replace the first digit in a string (should have at least one
digit) with the $ character. 
Click me to see the solution

137. Write a JavaScript program to test whether a given integer is greater than 15 and return the
given number, otherwise return 15. 
Click me to see the solution

138. Write a JavaScript program to reverse the bits of a given 16-bit unsigned short integer. 
Click me to see the solution

139. Write a JavaScript program to find the position of the rightmost round number in an array of
integers. If there are no round numbers, the function returns 0.  
Note: A round number is informally considered to be an integer that ends with one or more
zeros.
Click me to see the solution

140. Write a JavaScript program to check whether all the digits in a given number are the same
or not.  
Click me to see the solution

141. Write a JavaScript program to find the number of elements in both arrays.  
Click me to see the solution

142. Write a JavaScript program to simplify a given absolute path for a file in Unix-style.  
Click me to see the solution

143. Write a JavaScript program to sort the strings of a given array of strings in order of
increasing length.  
Note: Do not change the order if the lengths of two string are same.
Click me to see the solution

144. Write a JavaScript program to break an URL address and put its parts into an array.  
Note: url structure : ://.org[/] and there may be no part in the address.
Click me to see the solution

145. Write a JavaScript program to find the maximum integer n such that 1 + 2 + ... + n <= a
given integer.  
Click me to see the solution

146. Write a JavaScript program to compute the sum of cubes of all integers from 1 to a given
integer.  
Click me to see the solution
147. Write a JavaScript program to compute the sum of all the digits that occur in a given string.

Click me to see the solution

148. Write a JavaScript program to swap two halves of a given array of integers of even length.  
Click me to see the solution

149. Write a JavaScript program to change the capitalization of all letters in a given string.  
Click me to see the solution

150. Write a JavaScript program to swap pairs of adjacent digits of a given integer of even
length.  
Click me to see the solution

1. Write a JavaScript function to print the “Hello World” message

Function `displayMessage()` prints “Hello World” string using console.log() function.

function displayMessage() {
console.log("Hello World");
}

displayMessage(); //"Hello World"


24 JavaScript Projects For Beginner...
Remaining Time -0:40
24 JavaScript Projects For Beginners In 2023 (With Source Code)

2. Write a function that returns the square of a number

Function `findSquare()` returns the square of the input number which is passed as an argument in
the function call.

function findSquare(num) {
return num*num;
}

console.log(findSquare(2)) //4
console.log(findSquare(9)) //81
console.log(findSquare(15)) //225

3. Write a function to convert Celsius to Fahrenheit

Function `calFahrenheit()` returns the converted Celsius value to Fahrenheit value based on the
formula `(Celsius × 9/5) + 32 = Fahrenheit`

function calFahrenheit(cel) {
return (cel*9/5)+32; //Conversion formula
}

console.log(calFahrenheit(0)) //32
console.log(calFahrenheit(20)) //68
console.log(calFahrenheit(40)) //104

4. Write a function to find the area of a given Rectangle

Function `rectangleArea()` returns the rectangle area provided the width and height as the
argument.

function rectangleArea(a,b) {
return `The area of rectangle is ${a*b}`;
}

console.log(rectangleArea(10,20)) //The area of rectangle is 200


console.log(rectangleArea(30,30)) //The area of rectangle is 900

5. Write a function to find the area and perimeter of a Circle

Function `circleValues()` returns the perimeter and area of the circle provided the radius as an
argument for the function call.

function circleValues(rad) {
return `Perimeter: ${2*Math.PI*rad}, Area: ${Math.PI*rad*rad}`;
}

console.log(circleValues(10)) //"Perimeter: 62.83, Area: 314.15"


console.log(circleValues(15)) //"Perimeter: 94.24, Area: 706.85"
console.log(circleValues(25)) //"Perimeter: 157.07, Area: 1963.49"

6. Write a function to reverse a number

Function `reverseNum()` returns the reversed number for the given argument number value. 

function reverseNum(num) {
var reverse = 0;
while(num != 0)
{
reverse = reverse * 10;
reverse = reverse + num%10;
num = Math.trunc(num/10); // Remove decimal places
}
return reverse;
}

console.log(reverseNum(123)) //321
console.log(reverseNum(5872)) //2785

7. Count number of Vowels in String


Function `countVowel()` returns the number of vowels in input string. Learn more about
JavaScript String methods from javatpoint.com/javascript-string.

function countVowel(str) {
var count = 0;
str=str.toLowerCase();
for(var i=0;i<str.length;i++){
if(str.charAt(i)=="a"||str.charAt(i)=="e"||str.charAt(i)=="i"||
str.charAt(i)=="o"||str.charAt(i)=="u"){
count++; //Increment vowel count
}
}
return count;
}

console.log(countVowel("Hello")) //2
console.log(countVowel("Umbrella")) //3

8. Flatten array of arrays using JavaScript reduce

Function `flattenArr()` flattens a 2D array by combining each sub array into 1D array by using
JavaScript reduce.

function flattenArr(arr) {
return arr.reduce((result, array) => result.concat(array));
}

console.log(flattenArr([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))


// [1, 2, 3, 4, 5, 6, 7, 8, 9]

9. Write a function to check if an input string is a palindrome

Function `checkPalindrome()` return a boolean value based on whether the input string is
palindrome or not.

function checkPalindrome(str) {
for(var i=0;i<str.length;i++){
if(str.charAt(i)!=str.charAt(str.length-i-1)){ // Comparison fail
return false;
}
}
return true;
}

console.log(findPalindrome("bannana")) //false
console.log(findPalindrome("racecar")) //true
console.log(findPalindrome("madam")) //true

10. Write a function to calculate simple interest based on the principle amount

Function `simpleInt()` returns a final amount based on the simple interest formula provided
principal amount, rate of interest per year, and time on a yearly basis.
function simpleInt(principle, rate, time) {
var finalAmt=principle + principle*time*rate;
return finalAmt;
}

console.log(simpleInt(20000,5,2)) //220000
console.log(simpleInt(150000,25,1)) //3900000

11. Write a function to calculate compound interest based on the principle


amount

Function `compoundInt()` returns a final amount based on the compound interest formula
provided principal amount, rate of interest per year, time on a yearly basis, and n as the number
of times that interest is compounded per unit time.

function compoundInt(principle, rate, time, n) {


var interest = principle * (Math.pow((1 + (rate / n)), (n * time)));
return principle + interest;
}

console.log(compoundInt(20000,5,2,2)) //3021250
console.log(compoundInt(150000,25,1,2)) //27487500

12. Write a function to generate a random number

Function `genRandom()` return a generated random integer number between the provided start
and end range.

function genRandom(start, end) {


return Math.floor(Math.random() * end) + start
}

console.log(genRandom(1,10)) // random int between 1 to 10


console.log(genRandom(80,90)) // random int between 80 to 90

13. Write a function to find Factorial of a number

Function `getFactorial()` return the factorial of a number using the formula `n*(n-1)*(n-2)*…` .

function getFactorial(num) {
if(num==1){
return 1; // Termination condition
}
if(num==0 || num<0){
return 0; // Termination condition
}
return num*getFactorial(num-1);
}

console.log(getFactorial(5)) // 120
console.log(getFactorial(12)) // 479001600
14. Write a function to add unlimited numbers

Function `addNumber()` return the sum of all the number passed as arguments of the function.

function addNumber(...args) {
return args.reduce((total,num) => total+num); //Add numbers
}

console.log(addNumber(2,4,5)) // 11
console.log(addNumber(10,45,34,130)) // 219

15. Write a function to combine unlimited arrays

Function `addArrays()` return the concatenated array by combining all the arrays passed as an
argument of the function.

function addArrays(...args) {
return args.reduce((total,arr)=>total.concat(arr));
}

console.log(addArrays([2,3,4],[6,4,9],[34,6,4]))
// [2, 3, 4, 6, 4, 9, 34, 6, 4]

16. Write a function to find the count of a letter in a string

Function `letterCount()` return the count of letter in a given string.

function letterCount(str, c) {
var count=0;
str=str.toLowerCase(); //Case insensitive
for(var i=0;i<str.length;i++){
if(str.charAt(i)==c){
count++; //Increment count
}
}
return count;
}

console.log(letterCount("Connect",'c')) // 2
console.log(letterCount("first person",'s')) // 2

17. Write a function to check if a number is Prime

Function `checkPrime()` return Boolean value based on whether the number is Prime or not.

function checkPrime(num, div=2) {


// Base case
if (num <= 2){
return (num == 2) ? true : false;
}
// No Divisor case
if (div * div > num){
return true;
}

// Number is not prime if divisible


if (num % div == 0){
return false;
}
// Recursive call with next divisor
return checkPrime(num, div+1);
}

console.log(checkPrime(27)) // false
console.log(checkPrime(19)) // true

1. Write a JS code to print numbers from 1 to 10

Function `printNumbers()` prints numbers from 1 to 10 using for loop.

function printNumbers() {
for(var i=1;i<=10;i++){
console.log(i);
}
}

printNumbers() //1 2 3 4 5 6 7 8 9 10
Javascript For Loops Explained in O...
Remaining Time -6:24
Javascript For Loops Explained in One Video | ES6 | ES7 Loops

2. Write a JS code to print a 2D array

Function `printArray()` prints all the elements of a 2D array using nested for loops.

function printArray(arr) {
for (var i=0;i<arr.length;i++){
for(var j=0;j<arr[0].length;j++){
console.log(arr[i][j]);
}
}
}
var arr = [[1, 2],
[3, 4],
[5, 6]];

printArray(arr) //1 2 3 4 5 6

3. Write a JS code to print Even numbers in given array

Function `printEven()` prints all the even numbers of a 2D array using for loops and ‘%’
operator.
function printEven(arr) {
for (var i=0;i<arr.length;i++){
if(arr[i]%2==0){
console.log(arr[i]); //print even number
}
}
}
var arr = [13,23,12,45,22,48,66,100]

printEven(arr) //12 22 48 66 100

4. Write a JS code to delete all occurrence of element in given array

Function `deleteElement()` deletes all the occurrence of element from the given array.

function deleteElement(arr, ele) {


for (var i=0;i<arr.length;i++){
if(arr[i]==ele){
arr.splice(i,1); //Delete element from array
}
}
return arr;
}
var arr = [23,56,4,78,5,63,45,210,56];
arr = deleteElement(arr, 56)

console.log(arr); //[23, 4, 78, 5, 63, 45, 210]

5. Write a JS code to demonstrate Async loop

For loop consisting of setTimeout() function to print loop variable 5 times in asynchronous way.

for(var i=0;i<5;i++){
setTimeout(()=>console.log(i), 5000);// 5 5 5 5 5
}

6. Write a JS code to find the power of a number using for loop

Function numPower() to returns power of number for provided exponential value using for loop.

function numPower(num,pow) {
var res=1; //return 1 for pow=0
for(var i=0;i<pow;i++){
res=res*num;
}
return res;
}
console.log(numPower(4,3)); //64
console.log(numPower(16,2)); //256

7. Write a JS code to print a pattern using for loop


Function printPattern() is used to print a pattern for a given range using nested for loop.

function printPattern(range) {
for(var i=1;i<=range;i++){
var str="";
for(var j=1;j<=i;j++){
str += j+" ";
}
console.log(str);
}
}
printPatter(8);

/* 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 */

8. Write a JS code to find the no of digits in a number

Function digitCount() to returns the number of digits in a given number using while loop.

function digitCount(num) {
var count=0; //return 1 for pow=0
while(num!=0){
num=Math.floor(num/10);
count++;
}
return count;
}
console.log(digitCount(8367)); //4
console.log(digitCount(563349)); //6

9. Write a JS code to calculate the sum of digits in a number

Function digitSum() to returns sum of all digits in a given number using while loop. Learn more
about JavaScript built-in Math methods from developer.mozilla.org/Global_Objects/Math

function digitSum(num) {
var sum=0;
while(num!=0){
sum += num % 10;
num = Math.floor(num/10);
}
return sum;
}
console.log(digitSum(4367)); //20
console.log(digitSum(56349)); //27
10. Write a JS code to find the largest number in an array

Program to find the largest number in the given 1D array. 

var arr = [2, 45, 3, 67, 34, 567, 34, 345, 123];
var largest = arr[0];
for(var i=0;i<arr.length;i++){
largest = arr[i]>largest ? arr[i]:largest; //Check largest number
}
console.log(largest) //567

11. Write a JS code to find the number of zeros in 2D Matrix

Program to find count number for zeros in 2d matrix using nested for loops and increment
operation.

var arr = [[0,1,1],[0,1,0],[1,0,0]];


var zeroCount = 0;
for(var i=0;i<arr.length;i++){
for(var j=0;j<arr[0].length;j++){
zeroCount = arr[i][j]==0 ? zeroCount+1 : zeroCount;
}
}

console.log(zeroCount) //5

12. Write a JS code to find product of two arrays

Function findProd() to generate a new array which is the product of two arrays of the same size
using for loop.

function findProd(arr1, arr2) {


var arrProd = arr1.length>arr2.length ? arr1 : arr2;
for(var i=0; i < Math.min(arr1.length, arr2.length); i++){
arrProd[i] = arr1[i] * arr2[i]; //Product of 2 array elements
}
return arrProd;
}
var arr1 = [3,45,23,78,34];
var arr2 = [4,2,34,4,12,1];

console.log(findProd(arr1,arr2)); //[12, 90, 782, 312, 408, 1]

13. Write a JS code to print the Fibonacci series for a given value of N

The function fibonacci() prints the Fibonacci series for the given range N using While loop.

function fibonacci(n) {
var n1=0;
var n2=1;
var count=2;
var n3;
console.log(n1,n2);
while(count<n){
n3=n1+n2;
console.log(n3); //print current element
n1=n2;
n2=n3;
count++;
}
}

fibonacci(8) //0 1 1 2 3 5 8 13

14. Write a JS code to find N value in the Fibonacci series for a given number

The function Findfibonacci() prints the index of number in the Fibonacci series if present or
“element not present” if the number is not part of the Fibonacci series.

function findFibonacci(num) {
var n1=0;
var n2=1;
var count=2;
var n3;
while(true){
n3=n1+n2;
if(n3==num){
console.log(`Element ${num} is present in index ${count}`)
break;
}
else if(n3>num){
console.log("Element not present");
break;
}
n1=n2;
n2=n3;
count++;
}
}

findFibonacci(13) //"Element 13 is present in index 7"


findFibonacci(144) //"Element 144 is present in index 12"

15. Write a JS code to count all letters in a word

Program to find the count of all letters in a word using double for loops.

var str="Suggesting";
var count=new Array(26);
str=str.toLowerCase();
for(var i=0; i<str.length; i++){
if(count[str.charCodeAt(i)-97]){
count[str.charCodeAt(i)-97]++; // Increment count
}
else{
count[str.charCodeAt(i)-97]=1; // Add entry
}
}
for(var i=0;i<26;i++){
if(count[i]){
console.log(`Character ${i+'a'} has occured ${count[i]} number of times`);
}
}

16. Write a JS code to find duplicate values in a given array

Function findDup() to returns all the elements that are repeated more than once in a given array.

function findDup(arr) {
var arrDup=[]
for(var i=0; i<arr.length; i++){
if(arr.indexOf(arr[i])!=i&&arrDup.indexOf(arr[i])==-1){
arrDup.push(arr[i]);
}
}
return arrDup;
}
var arr = [4,2,34,4,1,12,1,4];

console.log(findDup(arr)); //[4, 1]

17. Write a JS code for binary search algorithm

Program to find the index of a search element in an array using the binary search algorithm.

var arr = [13,45,34,2,56,3,57,34,88,55];


var key=57;
var low=0;
var high=arr.length-1;
var mid=0;
var flag=0;
arr.sort()

console.log("The sorted array is: "+arr); //13,2,3,34,34,45,55,56,57,88

while(low<=high)
{
mid=Math.floor((low+high)/2);
if(key < arr[mid])
{
high=mid-1;
}
else if(key > arr[mid])
{
low=mid+1;
}
else if(key == arr[mid])
{
flag++;
console.log("found at index:"+mid); //print the position
break;
}
}

if(flag==0)
{
console.log("Not found"); // Element not present in array
}

JavaScript Loop tutorials

1. JavaScript Program To Print Hello World


2. JavaScript Program to Add Two Numbers
3. JavaScript Program to Find the Square Root
4. JavaScript Program to Calculate the Area of a Triangle
5. JavaScript Program to Swap Two Variables
6. Javascript Program to Solve Quadratic Equation
7. JavaScript Program to Convert Kilometers to Miles
8. Javascript Program to Convert Celsius to Fahrenheit
9. Javascript Program to Generate a Random Number
10. Javascript Program to Check if a number is Positive, Negative, or Zero
11. Javascript Program to Check if a Number is Odd or Even
12. JavaScript Program to Find the Largest Among Three Numbers
13. JavaScript Program to Check Prime Number
14. JavaScript Program to Print All Prime Numbers in an Interval
15. JavaScript Program to Find the Factorial of a Number
16. JavaScript Program to Display the Multiplication Table
17. JavaScript Program to Print the Fibonacci Sequence
18. JavaScript Program to Check Armstrong Number
19. JavaScript Program to Find Armstrong Number in an Interval
20. JavaScript Program to Make a Simple Calculator
21. JavaScript Program to Find the Sum of Natural Numbers
22. JavaScript Program to Check if the Numbers Have Same Last Digit
23. JavaScript Program to Find HCF or GCD
24. JavaScript Program to Find LCM
25. JavaScript Program to Find the Factors of a Number
26. JavaScript Program to Find Sum of Natural Numbers Using Recursion
27. JavaScript Program to Guess a Random Number
28. JavaScript Program to Shuffle Deck of Cards
29. JavaScript Program to Display Fibonacci Sequence Using Recursion
30. JavaScript Program to Find Factorial of Number Using Recursion
31. JavaScript Program to Convert Decimal to Binary
32. JavaScript Program to Find ASCII Value of Character
33. JavaScript Program to Check Whether a String is Palindrome or Not
34. JavaScript Program to Sort Words in Alphabetical Order
35. JavaScript Program to Replace Characters of a String
36. JavaScript Program to Reverse a String
37. JavaScript Program to Create Objects in Different Ways
38. JavaScript Program to Check the Number of Occurrences of a Character in the String
39. JavaScript Program to Convert the First Letter of a String into UpperCase
40. JavaScript Program to Count the Number of Vowels in a String
41. JavaScript Program to Remove a Property from an Object
42. JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
43. JavaScript Program to Check if a Key Exists in an Object
44. JavaScript Program to Clone a JS Object
45. JavaScript Program to Loop Through an Object
46. JavaScript Program to Merge Property of Two Objects
47. JavaScript Program to Count the Number of Keys/Properties in an Object
48. JavaScript Program to Add Key/Value Pair to an Object
49. JavaScript Program to Replace All Occurrences of a String
50. JavaScript Program to Create Multiline Strings
51. JavaScript Program to Format Numbers as Currency Strings
52. JavaScript Program to Generate Random String
53. JavaScript Program to Check if a String Starts With Another String
54. JavaScript Program to Trim a String
55. JavaScript Program to Convert Objects to Strings
56. JavaScript Program to Check Whether a String Contains a Substring
57. JavaScript Program to Compare Two Strings
58. JavaScript Program to Encode a String to Base64
59. JavaScript Program to Replace all Instances of a Character in a String
60. JavaScript Program to Replace All Line Breaks with

61. JavaScript Program to Display Date and Time


62. JavaScript Program to Check Leap Year
63. JavaScript Program to Format the Date
64. Javascript Program to Display Current Date
65. JavaScript Program to Compare The Value of Two Dates
66. JavaScript Program to Create Countdown Timer
67. JavaScript Program to Remove Specific Item From an Array
68. JavaScript Program to Check if An Array Contains a Specified Value
69. JavaScript Program to Insert Item in an Array
70. JavaScript Program to Append an Object to An Array
71. JavaScript Program to Check if An Object is An Array
72. JavaScript Program to Empty an Array
73. JavaScript Program to Add Element to Start of an Array
74. JavaScript Program to Remove Duplicates From Array
75. JavaScript Program to Merge Two Arrays and Remove Duplicate Items
76. JavaScript Program to Sort Array of Objects by Property Values
77. JavaScript Program to Create Two Dimensional Array
78. JavaScript Program to Extract Given Property Values from Objects as Array
79. JavaScript Program to Compare Elements of Two Arrays
80. JavaScript Program to Get Random Item From an Array
81. JavaScript Program To Perform Intersection Between Two Arrays
82. JavaScript Program to Split Array into Smaller Chunks
83. JavaScript Program to Include a JS file in Another JS file
84. JavaScript Program to Get File Extension
85. JavaScript Program To Check If A Variable Is undefined or null
86. JavaScript Program to Set a Default Parameter Value For a Function
87. JavaScript Program to Illustrate Different Set Operations
88. Javascript Program to Generate a Random Number Between Two Numbers
89. JavaScript Program To Get The Current URL
90. JavaScript Program to Validate An Email Address
91. JavaScript Program to Check If a Variable is of Function Type
92. JavaScript Program To Work With Constants
93. JavaScript Program to Pass Parameter to a setTimeout() Function
94. JavaScript Program to Generate a Range of Numbers and Characters
95. JavaScript Program to Perform Function Overloading
96. JavaScript Program to Implement a Stack
97. JavaScript Program to Implement a Queue
98. JavaScript Program to Check if a Number is Float or Integer
99. JavaScript Program to Pass a Function as Parameter
100. JavaScript Program to Get the Dimensions of an Image
101. JavaScript Program to Remove All Whitespaces From a Text
102. JavaScript Program to Write to Console
103. JavaScript Program to Convert Date to Number

You might also like