I spent a long time trying to complete this function only to see that the syntax i was trying was not being accepted.
The countSheep function in code academy tells you to complete the function and gives you a newNumber variable that seems to not be defined in the local scope. So I tried to give it the "var" keyword. For some reason I can't understand the var keyword was not necessary and in order to complete the function and get it to pass the test I had to use the following:
as opposed to defining the variable I just used newNumber = number -1; // can also be written as newNumber -= 1; passed newNumber to the function
OR
not defined the newNumber variable and just invoke the function using n-1 as the parameter.
Here is the code that code academy gave us to solve.
function countSheep(number) {
if (number === 0) {
console.log("Zzzzzz");// Put your base case here
} else {
console.log("Another sheep jumps over the fence.");
// Define the variable newNumber as
// 1 less than the input variable number
newNumber = number - 1;
// Recursively call the function
// with newNumber as the parameter
countSheep(newNumber);
}
}
Can someone please tell me why the var keyword is not necessary inside of the function to define the newNumber variable. I appreciate it.
can also be written as newNumber -= 1- no it can'tcountSheep(number -1);and forget newNumber altogethervarit's equivalent to creating a global variable, i.e. likewindow.newNumber = number - 1vartoken is forbidden in strict-mode javascript.