Published
Edited
Jan 19, 2020
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
scopesExample = {
// if we ignore the globalScopeExample = { } above...
var imGlobal = "global variable"
function localScope() {
var imLocal = "local variable"
imGlobal // global can be accessed in here.
}
localScope()
// global variable can be accessed over here but not local variable
return [ imGlobal, imLocal ]
}
Insert cell
Insert cell
locallyScopedFunctions = {
function globalFunction() {
function localFunction() {
return "Hai from local function"
}
return "Hai from global function"
}
globalFunction()
localFunction()
}
Insert cell
Insert cell
iifeExample = {
var ret;
(function () {
var mySecret = "dont let the global scope know about this"
ret = "return " + "\"" + mySecret + "\"";
})()
return ret
}
Insert cell
Insert cell
function Poodle(name, owner) {
var breed = "poodle"
var sound = "Woof"
function introduce() {
return "I'm a " + breed + " named " + name +
". My owner is " + owner + "."
}
function setSound(s) {
sound = s
}

return {
talk: function() {
return sound + "! " + introduce()
},
setSound: setSound
}
}
Insert cell
{
var marvin = Poodle("Marvin", "Mike")
// so we have access to the setSound method
marvin.setSound( "wrrooof" )
// NONE OF THESE WORK
// marvin.owner = "Bob"
// marvin.name = "Spock"
// marvin.breed = "Bulldog"
// marvin.sound = "WRAAA"
// marvin.introduce = undefined
///////////////////////////
// Marvin still says the same thing
return marvin.talk();
}
Insert cell
Insert cell
{
var alfred = Poodle("Alfred", "George")
var sput = Poodle("Sput", "Jack")
var lola = Poodle("Lola", "Matt")
return alfred.talk() + "\n" +
sput.talk() + "\n" +
lola.talk() + "\n"
}
Insert cell
Insert cell
tipCalculator = (function() {
// anything we need to do to set up the calculator goes here
function roundToHundreths(num) {
return Math.round(100*num) / 100
}

function findPercentage(percent, amount) {
return roundToHundreths(amount * percent);
}

return {
// the calculator functions we choose to "expose" to the user
fifteen: function(amount) {
return "$" + findPercentage(0.15, amount)
},
twenty: function(amount) {
return "$" + findPercentage(0.2, amount)
},
twentyFive: function(amount) {
return "$" + findPercentage(0.25, amount)
},
thirty: function(amount) {
return "$" + findPercentage(0.3, amount)
}
}
})()
Insert cell
tipCalculator.fifteen(12.57)
Insert cell
tipCalculator.twenty(57.09)
Insert cell
Insert cell
Insert cell
CatFactory = function() {
// your code here
}
Insert cell
Insert cell
Insert cell
numberModule = undefined // replace with your code here
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more