Solutions to the exercises found here.
NOTE: Perfectly valid solutions can be written in a different style than the solutions below. If your code works, it works! Don't feel like your functions need to have the exact same syntax as these solutions.
-
Define a function named
calculateTip
and give it two arguments:total
andpercent
-
Inside your function, use the
return
keyword to output a tip according to thepercent
argument.
Extra Credit: Want to shave off the extra decimal places? Click here to learn about the .toFixed()
function and how to use it.
In the example below, your function should output 7.965
.
var calculateTip = function(total, percent) {
var tip = total * (percent / 100);
return tip;
}
calculateTip(44.25, 18)
-
Define a function named
removePrefix
and give it one argument:url
-
Inside your function, return the url without "www." included. Hint: Use
.slice
Hint: Don't forget to wrap quotes around your strings!
In the example below, your function should output google.com
.
var removePrefix = function(url) {
return url.slice(4);
}
removePrefix('www.google.com')
-
Define a function named
randomNumberGen
with no arguments. -
Inside your function, return a random number between 1 and 10. Hint: Use
Math.random()
andMath.floor(number)
In the example below, your function should output a whole number between 1 and 10.
var randomNumberGen = function() {
var randomNumber = Math.random() * 10 + 1;
var roundedRandomNumber = Math.floor(randomNumber);
return roundedRandomNumber;
}
randomNumberGen()
-
Define a function named
reverseSentence
with one argument:sentence
-
Inside your function, return the reversed copy of the
sentence
that is passed in as an argument. Hint: UseString.split()
Array.reverse()
andArray.join()
In the example below, your function should output "!ecnetnes emosewa na si sihT".
var reverseSentence = function(sentence) {
var sentenceArray = sentence.split('');
var reversedSentenceArray = sentenceArray.reverse();
var reversedSentenceString = reversedSentenceArray.join('');
return reversedSentenceString;
}
reverseSentence('This is an awesome sentence!')
A more concise version:
var reverseSentence = function(sentence) {
return sentence.split('').reverse().join('')
}