Skip to content

Instantly share code, notes, and snippets.

@adriandgr
Forked from JoelCodes/foreach.js
Created February 8, 2017 03:55
Show Gist options
  • Save adriandgr/c67dbcdf98e56fac3c097f5f2443ed10 to your computer and use it in GitHub Desktop.
Save adriandgr/c67dbcdf98e56fac3c097f5f2443ed10 to your computer and use it in GitHub Desktop.
Scope and Functions
function forEach(arr, fn){
for(var i = 0; i < arr.length; ++i){
var value = arr[i];
fn(value);
}
}
forEach([0, 1, 2], function(val){
console.log(`I ate ${val} hamburgers`);
})
function map(arr, transform){
var newArray = [];
for(var i = 0; i < arr.length; ++i){
var oldValue = arr[i];
var newValue = transform(oldValue);
newArray.push(newValue);
}
return newArray;
}
var newMappedArray = map([0, 1, 2], function(val){
return val * 2;
});
console.log(newMappedArray);
// Example of performing map, then forEach
function transformer(name){
return `${name} has ${name.length} letters`;
}
function thingDoer(value){
console.log('You know what?', value);
}
// forEach(map(['Sharon', 'Aecio', 'Ken'], transformer), thingDoer);
// Native version
['Sharon', 'Aecio', 'Ken']
.map(transformer)
.forEach(thingDoer);
// A bit about functions
// Functions in JavaScript are First Class Objects
// 1) Created at runtime. (see IIFE from scope.js)
// 2) Can be added to a data structure at runtime, such as a variable.
var x = 3;
console.log(x);
x = function(){
console.log('Hi Ermis!');
};
console.log(x);
x();
// 3) Can be passed as parameters to a function
function doThisThing(fn){
console.log('Do This Thing!');
fn();
}
doThisThing(x);
// 4) Can be returned from a function
function returnAFunction(){
console.log('I\'m returning a function!');
return function(){
console.log('Functions having functions!');
}
}
// Top level function runs
var returnedFunction = returnAFunction();
debugger;
// Returned function runs
returnedFunction();
// This can be simplified to returnAFunction()();
/*// The Adventures of Larryable the Variable
larryable = 'Hi, Im Larryable';
console.log(larryable);
console.log(global.larryable);
// Point out that, at the global scope, "larryable = 3" is the same as "var larryable = 3"
*/
/*function larryablesAdventure(){
var larryable = 'Hi, Im Larryable!';
console.log(larryable);
}
larryablesAdventure();
console.log(larryable);
// Now, larryable is not accessible from the outside scope.
*/
/*
// Now, let's look at nested scope, and a nested argument
function larryablesAdventure(){
var larryable = 'Hi, Im Larryable!';
function larrysBaby(){
var maryable = 'Hi, Im Maryable!';
console.log('Larryable', larryable);
console.log('Maryable', maryable);
console.trace();
}
larrysBaby();
console.log(maryable);
}
larryablesAdventure();
*/
/*
Immediately
Invoked
Function
Expression
*/
(function(){
for(var x = 0; x < 10; ++x){
console.log(x);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment