Javascript Exercise Solutions
PLEASE NOTE Make sure you attempt the exercises before looking at this page!
Is this number bigger than 100
function isBiggerThan100( number ) {
if (number > 100) {
return true;
} else {
return false;
}
}
You can also do this with what's called a 'one-liner' inside the function – the entire express as a single line of code. That's because 'number > 100' returns a boolean, so you can just directly return that.
function isBiggerThan100( number ) {
return number > 100;
}
console.log('99 is greater than 100: ' + isBiggerThan100( 99 ) );
console.log('204 is greater than 100: ' + isBiggerThan100( 204 ) );
What number's bigger
function greaterNum(num1, num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
console.log(greaterNum(5, 10));
The World Translator
function helloWorld(lang) {
if (lang == 'fr') {
return 'Bonjour, monde';
} else if (lang == 'es') {
return 'Hola, Mundo';
} else {
return 'Hello, World';
}
}
console.log(helloWorld('en'));
console.log(helloWorld('fr'));
console.log(helloWorld('es'));
The Pluralizer
function pluralize(noun, number) {
if (number === 1){
return number + ' ' + noun;
}
if (noun === 'sheep'){
return number + ' ' + 'sheep'
}
if (noun === 'goose'){
return number + ' ' + 'geese'
}
return number + ' ' + noun + 's';
}
console.log('I have ' + pluralize('cat', 0));
console.log('I have ' + pluralize('cat', 1));
console.log('I have ' + pluralize('goose', 2));
console.log('I have ' + pluralize('dog', 2));