Note: Before getting started on these exercises, please be certain that you've read through the root README.md file in this repository.
In order to complete these exercises, open repl.it, choose JavaScript, and then write your code in the left-hand panel. You can run your code using the "Run" button.
// function declaration
function square(x) {
return x * x;
}
// function expression
var square = function(x) {
return x * x;
};
Rewrite the following function declarations using a function expression:
// 1.
function cube(x) {
return x * x * x;
}
// 2.
function fullName(first, last) {
return first + " " + last;
}
// 3.
function power(base, exp) {
if (exp === 0) {
return 1;
}
return base * power(base, exp - 1);
}
// 4.
function sumCubes(numbers) {
var total = 0;
for (var i = 0; i < numbers.length; i++) {
total = total + cube(numbers[i]);
}
return total;
}
Type out your best answers to the following questions:
- Why does JavaScript output
undefined
instead of throwing an error in the following code?
console.log(message);
var message = 'Hi there!';
-
Why does JavaScript throw an error instead of logging
undefined
in the following code?console.log(message); let message = 'Hi there!';
-
Explain precisely what happens when the following code is executed.
console.log(showMessage()); var showMessage = function(){ return 'Hi there!'; };
-
Why does JavaScript not throw any errors when the following code is executed?
console.log(showMessage());
function showMessage(){
return 'Hi there!';
}
Restructure the following instances of code to work correctly:
// 1.
for(var i = 0; i < values.length; i++){
console.log(values[i]);
}
var values = [10, 20, 30];
// 2.
console.log(welcome('Charlie', 'Munger'));
function welcome(first, last) {
return `Welcome, ${first} ${last}! You last logged in on ${lastLogin}.`
};
var lastLogin = '1/1/1970';