I am just beginner to javascript. I ought to replace blablabla with a code which output the following
There are 7 days in a week.
In programming, the index of Sunday tends to be 0.
Here is the code
const weekday = (function() {
const names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
**blablabla**
})();
var num = 0;
console.log("There are " + weekday.count() + " days in a week.");
console.log("In programming, the index of " + weekday.name(num) + " tends to be " + weekday.number(weekday.name(num)) + ".");
Thanks and Regards,
The key to understanding this is realising that the immediately-invoked function (IIF) needs to return an object and assign it to weekday
, and that object needs to contain functions (or references to functions) that you can call.
For example: weekday.count()
- weekday
is an object that has a function assigned as a value to its count
key. That object is what is returned from the IIF and assigned to weekday
. weekday.count()
calls that function.
So the IFF should contain the following functions:
count
- returns the length of the names
array.name
- returns the element in the names
array at the index you supply as an argument.number
- returns the index of the "weekday" string you pass in as an argument.Then add references to those functions to an object which is returned from the function and assigned to weekday
.
const weekday = (function() {
const names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
function count() {
return names.length;
}
function name(n) {
return names[n];
}
function number(str) {
return names.findIndex(el => el === str);
}
return { count, name, number };
})();
const num = 0;
console.log(`There are ${weekday.count()} days in a week.`);
console.log(`In programming the index of ${weekday.name(num)} tends to be ${weekday.number(weekday.name(num))}.`);
Additional documentation