What is the output of the program below? Why?
function halve(x){
return x / 2;
}let x = 10; console.log(halve(100)); // →
Explain this program and what is it an example of?
const hummus = function(factor) {
const ingredient = function(amount, unit, name) {
let ingredientAmount = amount * factor;
if (ingredientAmount > 1) {
unit += “s”;
}
console.log(${ingredientAmount} ${unit} ${name});
};
ingredient(1, “can”, “chickpeas”);
ingredient(0.25, “cup”, “tahini”);
ingredient(0.25, “cup”, “lemon juice”);
ingredient(1, “clove”, “garlic”);
ingredient(2, “tablespoon”, “olive oil”);
ingredient(0.5, “teaspoon”, “cumin”);
};
This program is demonstrating “lexical scoping”. This means that the variables in the inner levels of the code can access the outer levels. Notice how console.log(‘{ingredientAmount} is called outside of the scope of the function - since it is wrapped in the hummus function it is still with scope.
This program takes a factor(how much hummus to make) and based on that calculates and outputs the amount of ingredients necessary to craft.
function printFarmInventory(cows, chickens) {
let cowString = String(cows);
while (cowString.length < 3) {
cowString = "0" + cowString;
}
console.log(`${cowString} Cows`);
let chickenString = String(chickens);
while (chickenString.length < 3) {
chickenString = "0" + chickenString;
}
console.log(`${chickenString} Chickens`);
}
printFarmInventory(7, 11);// You want to start with thinking that input will be received or that you will input // data for the numbers of cows and chickens. Then you create a function for that. The while loops // are simply adding 0's if the number input is less than 3. That way it's always // 3 digits long.