Exercises: JavaScript Functions
Standard Exercises
0. What will the following code print out? After you have figured it out - try it!
function sayHello() {
console.log("Hello")
}
sayHello();1. What will the following code print out?
function sayHello(name) {
console.log("Hello " + name);
}
sayHello("John");
sayHello("Caroline");2. What will the following code print out?
function add(a, b) {
return a + b;
}
console.log( add(5,6) );
console.log( add(12, 5.5) );3. Define the function sayGoodbye() so that it prints "Goodbye" to the console and then call it 3 times.
function sayGoodbye() {
}4. 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”5. 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 256. Define the function rectangleArea(width, height) to calculate the area of a rectangle. (Hint. The area of a rectangle is the width * height).
console.log(rectangleArea(5, 10)); // Should print 50
console.log(rectangleArea(7, 3)); // Should print 217. 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.66678. 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.5Advanced Exercises
9. 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);10. A factorial is calculated by taking a number and multiplying it by (itself - 1), until you end up at 1. For instance, 6! = 6*5*4*3*2*1 = 720. This is a good case for a recursive function. Try to write a recursive function to calculate the factorial of a number;
function factorial(n) {
if ( ... ) {
return ...
}
return ...
}console.log("Hello World");