JavaScript Exercises
Repository of Javascript exercises that I have collected & created with the intention of adding exercises for beginners to intermediate level to help newcomers to the Javascript language.
The exercises are in no specific order and they intend to provide a variety and engaging challenges for newcomers.
Write a JavaScript program to display the current day and time in the following format:
Today is Monday, the current time is 10 PM : 30m : 38s.
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
let weekDaysArr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; // Array containing the days of the week where 0 = Sunday
let date = new Date(); // creates a new date object with current date
let weekDay = weekDaysArr[date.getDay()]; // get the current weekday from the array based on its numerical value
let hours = date.getHours(); // gets current hour from the date object
// convert the hours from 25h to 12h
switch (true) {
case hours >= 12 && hours < 24:
hours = (hours - 12) + 'pm';
break;
case hours == 0:
hours = (hours + 12) + 'am';
break;
default:
hours = hours + 'am';
}
let minutes = date.getMinutes(); // get the current minutes from the date object
let seconds = date.getSeconds(); // get the current seconds from the date object
// outputs all the values
console.log(`Today is ${weekDay}, the current time is ${hours} : ${minutes}m : ${seconds}s.`);
Write a JavaScript program to rotate the string 'jsIsAwesome', by periodically removing one letter from the end of the string and attaching it to the front. (right to left)
⤓ Show solution
<h1 id="string"></h1>
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
// The string to be rotated
let str = 'jsIsAwesome';
let container = document.getElementById('string');
setInterval(()=>{
str = (str.slice(-1) + str); // Adds the last char of the string to the front
str = str.slice(0,-1); // removes the last char of the string
container.innerHTML = str;
}, 100);
Explanation:
The key to this exercise is in the problem it self, we want to do something periodically, so we can assume we would want to run a setInterval() and the second is rearranging the characters of a string.
This can be achieved in many ways, using slice, substring and Regular Expressions.
In the example above we use slice, first to copy the last char of the string to the start of the string and a second time to remove the last char of the string, repeating this process every 100ms.
Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to guess the number picked.
If the user input matches with guess number, the program will display a message "Great, you guessed it" otherwise display a message "Better luck next time".
⤓ Show solution
<button id="play">Play</button>
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
function prontUser() {
let reply;
let rndNumber = Math.floor(Math.random() * (10 - 1) + 1);
let userNumber = prompt('Gess the number, from 1 to 10.', '0');
if ( userNumber == rndNumber ) {
reply = "Great, you guessed it";
} else {
reply = "Better luck next time, correct number was " + rndNumber;
}
if (confirm(reply)) {
prontUser();
}
}
document.getElementById('play').addEventListener("click", prontUser);
Write a JavaScript program to display the days left until next Christmas in the following format:
Santa will deliver your presents in 89 days!
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
let today = new Date();
let thisYear = today.getFullYear();
let thisChristmas = new Date(thisYear+'-12-25');
// if is still in the same year but past Christmas day calculate to christmas of next year
if ( Math.sign(thisChristmas - today) == "-1") {
thisChristmas = new Date((thisYear+1)+'-12-25');
}
let delta = Math.abs(thisChristmas - today) / 1000;
let days = Math.floor(delta / 86400);
console.log(`Santa will deliver your presents in ${days} days!`);
Write a JavaScript program to convert miles from a user input into kilometers, knowing that:
1mile = 1.60934km
⤓ Show solution
<input type="number" placeholder="1 mile" value="" id="miles"><button id="convert">Equals</button><input type="text" placeholder="1.60934km" id="kilometers" readonly>
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
function convert() {
let miles = document.getElementById('miles').value
document.getElementById('kilometers').value = (miles * 1.60934) + "km";
}
document.getElementById('convert').addEventListener("click", convert);
Write a JavaScript program to check whether a given positive number is a multiple of 2 or a multiple of 6
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
Write a JavaScript program to find out from two different given integer values which is closest to 100:
let int1 = 76;
let int2 = 123;
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
Write a JavaScript program to capitalize the first letter of each word of the string:
let str = "Learning javascript can be a lot of fun!";
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
Write a JavaScript program to extract the first half of a given string of even length.
let str = "Jon has travelled the world, but his favorite country is Japan.";
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }
Write a JavaScript program to reverse a number given number:
let int = 98341;
⤓ Show solution
body {
background: black;
color: white;
}
pre code {
font: 11pt/1.25 Monaco, monospace;
}
.debug { color: Snow; }
.info { color: LawnGreen; }
.warn { color: GoldenRod; }
.error { color: LightCoral; }