Exercises: JavaScript Recap
Standard Exercises
Variables
0. Write the following code into the console and run the code.
console.log("Hello");1. What will the following print into the console? Type it in and try it out!
console.log(56*2);2. Calculate 46+92 and print the result in the console.
3. Create a variable called ‘name’ and print that variable in the console. Test with the following code;
// Create variable name
console.log(name);4. Create the variable a = 10, print it, add 5 to it and print it again.
// create a
console.log(a);
// add 5 to a
console.log(a); 5. Some variables contain properties, which give you extra information about a variable. You access properties on a variable by using a '.' dot. Strings have a 'length' property. Complete the code below to print the length of the string.
let name = "John";
console.log( ... );6. You can use “+=” and “-=” as short-hand for “a = a + 1”. Convert the following to use += and -=.
let a = 10;
a = a + 5;
console.log(a);Control Flow - if/then/else
7. Try to determine the outcome of the following statements and then enter them into the console to see the answers.
let age = 21;
if ( age > 18 ) {
console.log("You can vote!");
}let age = 15;
if ( age > 18 ) {
console.log("You can vote!");
} else {
console.log("You cannot vote!");
}8. Write an if statement that checks whether the bool likesCoffee is true and prints "Good Choice" if it is.
let likesCoffee = ...;
if ( ... ) {
console.log("Good Choice");
}9. Write an if statement that checks whether the name is Alex. If it is - print "Hello Alex" to the console. Experiment with different values for 'name' to ensure your code works.
let name = prompt("What is your name?");
console.log("Your name is: " + name);
if ( ... ) {
console.log( ... );
}Functions
10. What will the following code print out?
function sayHello(name) {
console.log("Hello " + name);
}
sayHello("John");
sayHello("Caroline");11. Define the function checkHeight(height) so that it prints “YES” if the given height is over 140cm or “NO” otherwise. Call the function with the following code and check that it prints the correct answer.
checkHeight(100); // Should print “NO”
checkHeight(200); // Should print “YES”
checkHeight(140); // Should print “NO”12. Define the function squareNumber(value) which multiplies “value” by itself and returns the answer. Check your function works with the following code.
console.log(squareNumber(7)); // Should print 49
console.log(squareNumber(-5)); // Should print 2513. Write a function “max(a,b)” that returns the maximum value of a and b.
console.log(max(10, 100)); // Should print 100
console.log(max(15.5, 4)); // Should print 15.5Arrays
14. What does the following code do? What do you expect to be printed by the end of the script?
let fruits = ["Apple", "Kiwi", "Peach"];
console.log(fruits[1]);15. Create an array called ‘vegetables’ containing the values: Broccoli, Mushroom, Carrot. After doing so, print it with the following code;
console.log(vegetables); // Should print "Broccoli,Mushroom,Carrot"16. Add the vegetable "Sweetcorn" to the array of vegetables using the ‘push’ method.
// <array>.push("New Item");
console.log(vegetables); // Should print "Broccoli,Mushroom,Carrot,Sweetcorn"17. Print out the length of the vegetables array using .length. The result should now be 4.
Loops
18. What does this for loop do? When you think you know, type it in to the console and see;
let items = ["Apple", "Kiwi", "Peach"];
for(let i = 0; i < items.length; i++) {
console.log(items[i]);
}19. Write a for loop to print out every variable in the 'names' array defined below;
let names = ["Chris", "Emily", "Tove"];
// print "Chris", "Emily, "Tove" on separate lines20. Write the function findHello(anArray); that takes an array and prints out the word "YES" if the array contains the string "Hello". Test it with the following code;
findHello( ["Good", "Bye", "Hello"] ); // Should print "YES"
findHello( [1, 2, 3, 4] ); // Should not print anythingAdvanced Exercises
Variables
21. Take a guess what value you get from these equations and then use the console to calculate it;
12 % 5
12 * 8 + 4 / 2
12 * (8 + 4) / 2
4 ** 2You can also use a++ and a-- to add/subtract one from a variable. Try out the following;
let a = 1;
console.log(a++);
console.log(a--);Wait - that's weird... It prints "1" and then "2"... What's going on (see the next question).
22. There are two ways to increment/decrement variables in JavaScript. The example shown above (a++) increments the variable and then returns the result. However, it's also possible to return the result and then increment the variable. This can lead to weird behaviour, so it's usually best to avoid it - but it can be useful in scenaroids. Try to figure out what is printed out on each line below, and then try it out!
let a = 1;
console.log(a++);
console.log(--a);
console.log(++a);
console.log(a--);
console.log(a);Strings
23. Print the string "Your height is: X" where X is the value of the variable ‘height’ below.
let height = 120;
console.log(...);24. Print characters 0, 4 and 8 from the string ‘alphabet’ below;
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";25. Extract the word 'mad' from this string using the substr(start, length) method.
let fullText = "He was a mad scientist";
let mid = fullText.substr(…);
console.log(mid); // Should print "mad"Control Flow
26. We're going to determine whether a theme park visitor is able to go on a specific ride. If the rider is 18 or over, or their height is over 140cm then they are allowed to ride.
let age = ...;
let height = ...;
...Note. Something we don't touch upon during this course is the switch statement. The switch statement allows you replace long if/then/else statements that are checking for a number of set conditions. You can read about switch statements here.
27. Use a switch statement to print out the cost of the given drink;
// coffee costs $2, tea costs $1 and juice costs $2.50
let drink = "coffee"; // covfefe?
switch( ... ) {
case ...:
...
break;
case ...:
...
break;
}Functions
28. Define the function fahrenheitToCelsius(temp); to convert the given temperature from F to C. Hint. Use the following formula to convert between the two: C = ((F-32)/9)*5;
console.log(fahrenheitToCelsius(140)); // Should print 60
console.log(fahrenheitToCelsius(80)); // Should print 26.666729. Write a function “max(a,b)” that returns the maximum value of a and b.
console.log(max(10, 100)); // Should print 100
console.log(max(15.5, 4)); // Should print 15.530. A recursive function is one that calls itself. You have to be careful with a recursive function that it doesn't call itself forever, so you need to set a parameter or condition which will stop the recursion. What will the following function do?
function hello(count) {
if ( count > 0 ) {
console.log("Hello");
hello(count - 1);
}
}
hello(5);Arrays
31. Create an array called ‘names’ containing the values: Ben, Caroline, David
32. Use the ‘unshift()’ method to add the name "Alex" to the start of the array.
console.log(names); // Should print Alex,Ben,Caroline,David33. Use ‘splice(index, 0, value)’ to insert the name "Emily" into the array after ‘Ben’.
console.log(names); // Should print "Alex,Ben,Emily,Caroline,DavidLoops
34. Write a for loop that prints the string "Goodbye" 5 times.
35. Write a for or while loop that prints out the first 20 items of the "9x" table. (i.e. 9, 18, 27, ...).
36. Write a for loop to print out every variable in the 'names' array defined below;
let names = ["Chris", "Emily", "Tove"];
// print "Chris", "Emily, "Tove" on separate lines37. Write the function removeZeros(anArray); which will remove all zeros from the given array. You will need to use anArray.splice([position], [count]) to do so.;
let anArray = [7, 9, 0, 1];
removeZeros(anArray);
console.log(anArray); // Should be "7,9,1"console.log("Hello World");