├── DAY1.js ├── DAY2.js ├── DAY3.js ├── OLD ├── Day3Challenges.js ├── Day5Challenges.js ├── Day6Challenges.js ├── FuncIntro.js ├── IntroToFunctional.js ├── PracticeProblemsDay7.js └── stopWatch.js └── README.md /DAY1.js: -------------------------------------------------------------------------------- 1 | Welcome to JS Fundamentals: Objects, Array and Functions 2 | 3 | wifi: hackreactor 4 | pw: awesomebullets 5 | 6 | Teachers: Bianca and Monthy 7 | Lead Mentors: Jeff and Spencer 8 | TAs: Xian, Aaron, Drew 9 | 10 | Bathrooms: past the kitchen on the left 11 | 12 | ================================================= 13 | 14 | Setup 15 | 16 | 1. Download Github Repo 17 | 2. Download Text Editor (sublime recommended) 18 | 3. Running a js file in your browser 19 | 4. Using the console 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | LECTURE 1 42 | 43 | //Warmup (5 mins) 44 | 45 | //create an array named recipe and add the steps, in order to make your favorite 46 | //food. Use different methods to do so. 47 | ================================================= 48 | 49 | 50 | //data structures 51 | ================================================= 52 | var simpleDataStructures = ['arrays', 'objects']; 53 | 54 | // similarities 55 | ================================================= 56 | 0. Both Arrays and Objects are Objects // interesting 57 | 1. Both are what we call in computer sciences "associative arrays" 58 | 2. Which means they are just *a bucket that hold name-value pairs* // also called key-value 59 | 3. Each name-value pair is a property (property name and property value) 60 | 61 | 62 | //what's the difference?? 63 | ================================================= 64 | 0. Arrays are enclosed in brackets, Objects use curly braces 65 | 2. Objects are unordered and have named properties 66 | 3. Arrays are ordered with numbers 67 | 4. Arrays have a length property 68 | 69 | //how to add values and indices to arrays 70 | ================================================= 71 | var addValues = ['bracket-notation', 'bracket-notation with variable']; 72 | var otherWaysToAdd =['dot-notation', 'native methods', 'lengthproperty']; 73 | 74 | //how to access values and indices in an array 75 | ================================================= 76 | var accessValues = ['bracket-notation', 'bracket-notation with variable']; 77 | var otherWaysToAccess =['dot-notation', 'native methods', 'length property']; 78 | 79 | //access the first step of your recipe using bracket notation. 80 | ================================================= 81 | 82 | //access the last step of your recipe use a variable. 83 | ================================================= 84 | 85 | //access the second to last step of your recipe. 86 | ================================================= 87 | 88 | 89 | //how to add values to objects 90 | ================================================= 91 | var addProperties = ['bracket-notation', 'dot-notation', 'bracket-notation with variable']; 92 | var otherWaysToAddProperties = []; 93 | 94 | 95 | LECTURE 2 96 | 97 | What is property assignment? 98 | 99 | //how to access values and properties to objects 100 | ================================================= 101 | var accessProperties = ['loop']; 102 | var accessValues = ['bracket-notation', 'dot-notation', 'bracket-notation with variable']; 103 | var otherWaysToAccess = []; 104 | 105 | //Failed property lookups always evaluate to the value undefined 106 | ================================================= 107 | var myObj = { one: 1, two: 2, three: 3}; 108 | myObj['two'] => ?? 109 | myObj[one] => ?? //what does no quotes mean? 110 | 111 | //You can't use dot notation with variables or special characters 112 | ================================================= 113 | var myOtherObj = { loves : 'candy', likes: 'fries' } 114 | var likes = 'loves'; 115 | 116 | myOtherObj['likes']; => ?? 117 | myOtherObj.likes => ?? 118 | 119 | What about weird symbols in property names? 120 | 121 | 122 | //create an object called myCatInfo 123 | //add some properties and values using bracket notation 124 | ================================================= 125 | 126 | //now recreate myCatInfo using dot notation (do not copy/paste!) 127 | ================================================= 128 | 129 | //some weird things 130 | ================================================= 131 | Since arrays are objects... 132 | 133 | Property + Index stringification with brackets 134 | 135 | var obj = { 136 | x: 9, 137 | 0: 'cat' 138 | }; 139 | 140 | obj[('x').toString()] = 9; 141 | obj[( 0 ).toString()] = 'cat'; 142 | log(obj[('x').toString()]);//logs 9 143 | log(obj[( 0 ).toString()]);//logs 'cat' 144 | for(var k in obj){ 145 | log(k); // logs 'x', '0' 146 | } 147 | 148 | //What is an object/array literal? 149 | ================================================= 150 | var obj1 = {}; 151 | obj['x'] = 9; 152 | obj['~/ [."4'] = 'cat'; 153 | 154 | var obj2 = { 155 | 'x' : 9, 156 | '~/ [."4' : 'cat' 157 | }; 158 | 159 | obj1 === obj2; => ?? 160 | 161 | 162 | 163 | LECTURE 3 164 | 165 | //how to loop through arrays vs objects 166 | ================================================= 167 | Arrays, use for loop with semi-colons 168 | 169 | var arr = ['a','b','c','d']; 170 | 171 | for (var i = 0; i < arr.length; i++){ 172 | console.log(arr[i]); //why don't we need quotes?? 173 | } 174 | 175 | Objects, use for in loop 176 | 177 | var obj = {hello: 'goodbye', up : 'down', blue : 'red', 'weird-symbol': 'need quotes'} 178 | 179 | for(var key in obj) { 180 | console.log(obj[key]); //why don't we need quotes?? 181 | } 182 | 183 | //Since arrays are objects... 184 | ================================================= 185 | 186 | The difference is that arrays have a few optimizations and conveniences 187 | that make them good for storing sequences of data in sequential integer keys. 188 | 189 | var arr = []; 190 | 191 | 192 | arr['x'] = 9; 193 | arr[ 0 ] = 'cat'; 194 | log(arr['x']); // logs 9 195 | log(arr[ 0 ]); // logs 'cat' 196 | for(var k in arr){ 197 | console.log(k); // logs 'x', '0' 198 | } 199 | console.log(arr.length); // logs ?? 200 | 201 | You might expect length to hold 2, since there's also a property at 202 | the key 'x'. But remember: non-integer keys do not count toward the length value. 203 | 204 | You don't see the length property when looping over the array using a for-in loop because 205 | JavaScript hides certain built-in properties away when it's clear that 206 | you won't want to visit them in for-in loops. Properties like length that have this 207 | behavior are said to be unenumerable. 208 | 209 | //Let's search arr for 'c' 210 | ================================================= 211 | 212 | //Let's search obj for the value 'red' 213 | ================================================= 214 | 215 | //Let's search obj for the property 'hello' 216 | ================================================= 217 | 218 | 219 | //"Loop through the array FAMOUS and console.log ONLY when it gets 220 | //to ashton kutcher, and mila kunis"; 221 | 222 | var famous = ['alex smith', 'amy whinehouse', 223 | 'cameron diaz', 'brad pitt', 'ashton kutcher', 'mark whalberg', 224 | 'morgan freeman', 'mila kunis']; 225 | ================================================= 226 | 227 | 228 | //"Loop through the object POLITICAL and console.log first the 229 | //VALUE then the KEY"; 230 | 231 | var political = {secretary of state: 'hillary clinton', 232 | potus: 'barack obama', flotus: 'michelle obama', vice prez: 'joe biden' 233 | governerOfCalifornia: 'jerry brown'}; 234 | ================================================= 235 | 236 | 237 | //"Loop through the political object and add the values to the famous array" 238 | ================================================= 239 | 240 | 241 | //"Take the array digits and place each value into an empty object where 242 | //The object keys the digits and the values 243 | //of the object are digit * 2" 244 | 245 | //example: 246 | 247 | var digits = [0, 1, 2, 3, 4, 5] 248 | var newDigits = {} ======> {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10}; 249 | ================================================= 250 | 251 | //'Loop through the array scramble and through each iteration take out 252 | //the FIRST and LAST value, and store it into the lovepoem array. then 253 | //turn the values in the lovepoem array into a string.' 254 | 255 | var scramble: ['roses', 'red', 'are', 'bacon', 'crispy', 'i', 'you' 256 | ,'love', 'and', 'is', 'blue', 'violets', 'are'] 257 | var lovepoem = []; 258 | ================================================= 259 | 260 | 261 | 262 | 263 | LECTURE 4 264 | 265 | //native methods + constructor methods arrays 266 | ================================================= 267 | The term "method" just means a function that interacts with an object, 268 | and is stored as a property of that object 269 | 270 | var arrayMethods = ['push', 'pop', 'shift', 'unshift', 'join', 'slice', 'splice']; 271 | var arrayConstructorMethods = ['Array.isArray()']; 272 | FURTHER READING: 273 | http://www.w3schools.com/jsref/jsref_obj_array.asp 274 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array 275 | 276 | 277 | //Now add another color that is not already in colors using a 278 | //native method (unshift/push) 279 | ================================================= 280 | 281 | 282 | //how will the below evaluate 283 | //&& means AND, more logical operators below 284 | ================================================= 285 | Array.isArray(colors) && undefined ==> ??? 286 | Array.isArray(colors) && "undefined" ==> ??? 287 | Array.isArray(colors) && colors.pop(); => ?? 288 | 289 | 290 | 291 | //"Without using a loop, take the 2nd and 3rd array values out of 292 | //FRIENDS and push it to the array ENEMIES" 293 | 294 | var friends = ['albrey', 'will', 'bianca', 'abe']; 295 | var enemies = []; 296 | ================================================= 297 | 298 | 299 | //"Join the array friends AND the array enemies into an string with 300 | //the variable name 'frenemies'" 301 | ================================================= 302 | 303 | 304 | //native methods + constructor methods objects 305 | ================================================= 306 | var objectMethods = ['hasOwnProperty']; 307 | var objectConstructorMethods = ['Object.keys()']; 308 | FURTHER READING: 309 | http://www.w3schools.com/jsref/jsref_obj_array.asp 310 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object 311 | 312 | //Why would you use an object vs an array? 313 | ================================================= 314 | 1. order 315 | 2. fast look ups 316 | 3. 'length' property 317 | 4. key value pair (named categories) 318 | 319 | 320 | ======= 321 | //Native methods (Primitive Types) 322 | 323 | //Let's build an array with the members of Destiny's Child 324 | ================================================= 325 | var destinysChild = ['Kelly Rowland', 'Michelle Williams', 'Beyonce Knowles']; 326 | 327 | //Return the last item in a multi-item array and save it in a 328 | //new variable called star 329 | ================================================= 330 | 331 | 332 | //Now add Beyonces sister Solange to star using native methods 333 | ================================================= 334 | 335 | 336 | //Now remove Beyonce using native methods so that Beyonce 337 | //is returned and Solange is the only value in star 338 | ================================================= 339 | 340 | 341 | //Let's check if star and destinysChild are arrays using 342 | //the native array method Array.isArray(obj); 343 | ================================================= 344 | 345 | 346 | 347 | 348 | //control flow 349 | ================================================= 350 | 0. The above are examples of Straight Control Flow, where code 351 | is executed predictably, from top to bottom 352 | 1. Next we wll cover conditional execution, where one of two 353 | routes are executed according to a conditional statements 354 | boolean value 355 | 356 | //Let's loop through the destinysChild array to see who's still around 357 | //Also, where's conditional statement and boolean in the function 358 | ================================================= 359 | 360 | 361 | //Cool, now what if we do the same with the following object 362 | ================================================= 363 | var singers = { 364 | female: 'Whitney Houston', 365 | male: 'Prince' 366 | }; 367 | 368 | //Remember that while arrays have a length property, 369 | //objects don't so you'll need to add a length property and 370 | //update it if you want to loop with a traditional for loop 371 | ================================================= 372 | 373 | 374 | //So that's fine but is far from ideal since we'll have to update 375 | // singers['length'] manually, let's use a for in loop instead 376 | ================================================= 377 | 378 | 379 | /*The Spy Society has decided that Austin has messed up one 380 | too many operations. They will let you join the spyRing array if 381 | and only if you can write a for loop that searches the spyRing 382 | array for Austin and puts you in his place */ 383 | =================================================== 384 | var spyRing = ['James Bond', 'Inspector Clouseau', 'Austin Powers']; 385 | 386 | 387 | 388 | //logical operators 389 | ================================================= 390 | 0. They perform boolean algebra, always evaluating to true or false 391 | 1. They always evaluate left to right 392 | 2. && most simply means 'and' 393 | 3. || is either/or 394 | 4. !() is negation 395 | 396 | //some examples 397 | ================================================= 398 | var o = {x: 1}; 399 | var p = null; 400 | 401 | //How do the following evaluate 402 | ================================================= 403 | o && o.x => ??? 404 | p && p.x => ??? 405 | o && p => ??? 406 | o || p => ??? 407 | !(o) => ??? 408 | !(p) => ??? 409 | 410 | 411 | //Search the array dogs for the name property, if it exists, 412 | //log the dogs names, if not, log that no dogs were named 413 | ================================================= 414 | var dogs = [ 415 | {name: 'Henry', 416 | age: 2, 417 | breed: 'Aussie', 418 | food: 'kibble', 419 | toy: 'tennis ball'}, 420 | {name: 'Tilly', 421 | age: 5, 422 | breed: 'Mutt', 423 | food: 'kibble', 424 | toy: 'bone'} 425 | ]; 426 | 427 | 428 | //Now let's say we want to create a function that 429 | //logs all of the values for Henry 430 | ==================================================== 431 | 432 | 433 | //That's cool and all but what good are the Values without 434 | // their keys? Write a function that will log the key/value pairs 435 | ================================================= 436 | -------------------------------------------------------------------------------- /DAY2.js: -------------------------------------------------------------------------------- 1 | Assume you receive this nested data structure from a database for 2 | your new dating site: 3 | 4 | var data = { results: [ 5 | { animal: 'fox', 6 | numberOfLegs: 4, 7 | says: '??', 8 | matches: 9 | [ 'dog', 'cat', 'pig'] 10 | }, 11 | { animal: 'frog', 12 | numberOfLegs: 4, 13 | says: 'ribbit', 14 | matches: 15 | [ 'whale', 'cat', 'pig', 'rabbit'] 16 | }, 17 | { animal: 'dog', 18 | numberOfLegs: 4, 19 | says: 'woof', 20 | matches: 21 | [ 'dog', 'fish', 'pig'] 22 | }, 23 | { animal: 'human', 24 | numberOfLegs: 2, 25 | says: 'hello', 26 | matches: 27 | [ 'frog', 'duck', 'pig'] 28 | }, 29 | { animal: 'fish', 30 | numberOfLegs: 0, 31 | says: 'blub', 32 | matches: 33 | [ 'dog', 'rabbit', 'frog', 'human'] 34 | }, 35 | { animal: 'whale', 36 | numberOfLegs: 0, 37 | says: 'aaarrrhhh', 38 | matches: 39 | [ 'duck', 'fish', 'pig'] 40 | }, 41 | { animal: 'duck', 42 | numberOfLegs: 2, 43 | says: 'quack', 44 | matches: 45 | [ 'fish', 'human', 'chicken', 'whale'] 46 | } 47 | ]}; 48 | 49 | Use the .length property to console.log the length of the results 50 | array. 51 | 52 | Imagine you want are making a search results page, 53 | (console.log) all of the animal names in order. 54 | 55 | Next, Capitalize the first letter of each name and put a label 56 | Your end result should look like this: 57 | Name: Fox 58 | Name: Dog 59 | Name: Frog 60 | Name: Human 61 | Name: Fish 62 | etc. 63 | 64 | Next, console.log the number of legs next to their name. 65 | Your end result should look like this: 66 | Name: Fox, Legs: 4 67 | Name: Dog, Legs: 4 68 | Name: Frog, Legs: 4 69 | Name: Human, Legs: 2 70 | Name: Fish, Legs: 0 71 | 72 | Now, redo the steps in the previous one and 73 | take this data and add it to an array with nested objects. 74 | Your result should look like this: 75 | var results = [ 76 | {Name: 'Fox', Legs: 4}, 77 | {Name: 'Dog', Legs: 4}, 78 | {Name: 'Frog', Legs: 4}, 79 | {Name: 'Human', Legs: 2}, 80 | {Name: 'Fish', Legs: 0} 81 | ]; 82 | 83 | For another search result, console.log the animals whose matches are 'fish' 84 | 85 | Next, add it to an array called 'FishMatches'. 86 | Make each match an object with two properties 'name' and 'index' 87 | Your end result should look like this: 88 | var fishMatches = [{name: 'dog', index: 2}, {name: 'whale', index:5}]; 89 | -------------------------------------------------------------------------------- /DAY3.js: -------------------------------------------------------------------------------- 1 | funFunctions.intro = function() { 2 | var me = { 3 | name: 'Bianca Gondolfo', 4 | follow: '@BiancaGondolfo', 5 | info: [ 6 | 'HR Cohort 4', 7 | 'Hacker in Residence Cohort 1', 8 | 'Community Evangelist', 9 | 'JS Engineer' 10 | ] 11 | } 12 | 13 | var lostandFound = email('frontdesk@hackreactor.com'), 14 | wifi = {name: 'HackReactor', PW: 'awesomebullets'}; 15 | 16 | if (YOU === NeedToPee && location === 'projector') { 17 | return 'Bathrooms are past the kitchen on the left'; 18 | } 19 | else { 20 | return 'Bathrooms are past the staircase on the right'; 21 | } 22 | 23 | }; 24 | 25 | // Takeaways 26 | 27 | funFunctions['takeaways'] = function(){ 28 | return [ 29 | 'Quick review', 30 | '' 31 | 'Scope:', 32 | 'what is function scope', 33 | 'global', 'local', 'nesting' 34 | 'what is closure scope', //TODO: tomorrow 35 | 'what is the module pattern', //TODO: tomorrow 36 | 'Higher Order Functions', 37 | 'what is a first class function', 38 | 'how to pass functions to other ‘, 39 | functions to complete basic 40 | programming problems' 41 | ]; 42 | } 43 | 44 | // Functions quick review 45 | 46 | var add = function(a, b){ 47 | return a + b; 48 | }; 49 | add(3, 4, 5); // 7 50 | 51 | // this function has 2 named parameters 52 | // it is being called with 3 arguments 53 | // The function body references 2 arguments by name 54 | // The function does work on 2 arguments 55 | 56 | 57 | // 'arguments' keyword 58 | 59 | var add = function(a, b){ 60 | console.log(arguments); //logs [3,4,5]! 61 | return a + b; 62 | }; 63 | add(3, 4, 5); // 7 64 | 65 | 66 | //Exercise: Take turns explaining to your partner the following: 67 | //parameters, 68 | //arguments, 69 | //the difference between being called with x arguments vs doing work on x arguments 70 | 71 | //Function declaration 72 | function functionName(arg0, arg1, arg2){ 73 | // function body 74 | } 75 | 76 | //funciton declarations are ready before code executes 77 | //this is OK: 78 | sayHi(); 79 | function sayHi(){ 80 | console.log("Hi"); 81 | } 82 | 83 | //Function expression 84 | 85 | var functionName = function(arg0, arg1, arg2){ 86 | // function body 87 | }; // needs ";" 88 | 89 | //not read until the execution reaches the line 90 | sayBye(); //error - function doesn't exist yet 91 | var sayBye = function() { 92 | console.log("Bye"); 93 | }; 94 | 95 | 96 | //FUNCTIONS AS OBJECTS 97 | 98 | //What does it mean a function is an object 99 | var f = function() {}; 100 | typeof f; // "function" 101 | f instanceof Function; // true 102 | f instanceof Object; // true 103 | 104 | //How does property access work on function objects? 105 | //How is it similar to or different from property access on other objects? 106 | 107 | var fun = function() {}; 108 | 109 | fun['x'] = 9; 110 | fun[0] = 'cat', fun[1] = 'dog'; 111 | 112 | console.log(fun['x']); 113 | console.log(fun[0]); 114 | 115 | for (var k in fun) { 116 | console.log(k); 117 | } 118 | 119 | // 0 120 | // 1 121 | // x 122 | 123 | fun.length; // 0 124 | 125 | for (var i = 0; i < fun.length; i++) { 126 | console.log(i); // never runs 127 | }; 128 | 129 | for (var key in fun) { 130 | console.log(i); // logs 'x', '0', '1' 131 | } 132 | 133 | //Two types of loops on functions objects 134 | //How would they behave? 135 | //Which one would you use? 136 | 137 | //FUNCTION INVOCATION 138 | 139 | //How are functions different from objects? 140 | 141 | fun(); 142 | 143 | //The only difference is that they can be invoked aka 'run.' 144 | //The parenthesis are invoking the function, like a button on a machine or the ignition key in a car. 145 | 146 | var fun = function() { console.log('2'); }; 147 | var res = fun(); // what is the value of res? 148 | 149 | var fun = function() { return 2; }; 150 | var two = fun(); 151 | 152 | 153 | 154 | function fun() { 155 | // this is the body 156 | // anything between the {} 157 | // also called *side effect* 158 | return ; // return statement 159 | }; 160 | 161 | //invoking a nameless function 162 | var two = function() { return 2; }(); //trailing invocation parens 163 | 164 | //immediate invocation is unusual because the function itself will be discarded and only the result will remain 165 | 166 | 167 | //NUANCES 168 | //aka common mistakes 169 | 170 | //****************************** 171 | // Time and audience permitting 172 | //****************************** 173 | 174 | 175 | // Function scope - Global 176 | 177 | //1. not inside a function 178 | var x = ‘global!’ 179 | 180 | //2. attached to the window object 181 | window.x = ‘also global!’ 182 | 183 | //3. defined without the word ‘var’ 184 | x = ‘global here, too!’ 185 | 186 | //Exercise 187 | 188 | //Declare a global variable attached to the global window object and assign it a value. 189 | 190 | //Declare a global variable without using var and practice feeling really fearful about this. Quickly add a var before it is too late! 191 | 192 | //Function Scope - Local 193 | 194 | var g = "global"; 195 | 196 | function go() { 197 | var l = "local"; 198 | } 199 | go(); 200 | alert(l); //out of scope! l is not defined 201 | 202 | 203 | // Function Scope - hoisting 204 | 205 | var scope = "global"; 206 | function f() { 207 | console.log(scope); // Prints "undefined", not "global" 208 | var scope = "local"; // Variable initialized here, but defined everywhere 209 | console.log(scope); // Prints "local" 210 | } 211 | 212 | function f() { 213 | var scope; // Local variable is declared at the top of the function 214 | console.log(scope); // It exists here, but still has "undefined" value 215 | scope = "local"; // Now we initialize it and give it a value 216 | console.log(scope); // And here it has the value we expect 217 | } 218 | 219 | //Function Scope - Precedence 220 | //If there are two variables of the same name within overlapping scope, the most local value overwrites any values from an outer scope. 221 | 222 | 223 | //Function Scope - exercise 2 224 | var first = function(x) { 225 | var z = “it’s lonely on top”; 226 | console.log(“in the first function y = not declared.”); 227 | var second = function() { 228 | var y = “I’m down here!!”; 229 | console.log(‘y is a local variable to this child function. it equals,’ y); 230 | console.log(“z is an inherited variable from the parent scope. The child function can access it. They value is: ‘, z); 231 | }; 232 | second(); 233 | }; 234 | 235 | //Play with this in the console and explore nested local scopes! 236 | 237 | //The first function is the parent function and cannot access y since it is inside the child function. 238 | 239 | //The second function can access the variables and values from the parent function. That is why second can refer to z in the second console.log 240 | 241 | 242 | //Function Scope - exercise 2 pt 2 243 | var first = function(x) { 244 | var z = “it’s lonely on top”; 245 | console.log(“in the first function y = not declared”); 246 | var second = function() { 247 | var y = “I’m down here!!”; 248 | var third = function() { 249 | console.log(“remember variable hoisting? y = “, y); 250 | var y = “I’m in this pretty deep..”; 251 | console.log(“What do you think y is down here? It is “, y); 252 | }; 253 | third(); 254 | }; 255 | second(); 256 | }; 257 | 258 | //Now we have added a third function the the equation. 259 | //Which functions have access to which variables? 260 | //Which functions can’t access other function’s locally scoped variables? 261 | //Why are we calling the third(); and second(); functions where we do and not somewhere else? 262 | 263 | 264 | //Function Scope vs Block Scope 265 | function test(o) { //JS has only Function Scope!! 266 | var i = 0; // i is defined throughout function 267 | if (typeof o == "object") { 268 | var j = 0; // j is defined everywhere, not just block 269 | for(var k=0; k < 10; k++) { // k is defined everywhere, not just loop 270 | console.log(k); // print numbers 0 through 9 271 | } 272 | console.log(k); // k is still defined: prints 10 273 | } 274 | console.log(j); // j is defined, but may not be initialized 275 | } 276 | 277 | //Lexical Scope 278 | var f2 = function () { 279 | return n; 280 | }; 281 | 282 | var f = function () { 283 | var n = 42; 284 | return f2; 285 | }(); 286 | 287 | var result = f(); 288 | console.log(result()) 289 | 290 | //JavaScript is not dynamically scoped. This means that the scope is defined at run-time, based on the location of the text. 291 | 292 | //Scope - chaining 293 | function A(x) { 294 | function B(y) { 295 | function C(z) { 296 | alert(x + y + z); 297 | } 298 | C(3); 299 | } 300 | B(2); 301 | } 302 | A(1); // alerts 6 (1 + 2 + 3) 303 | 304 | //Closures - definition 305 | 306 | //A closure happens when you nest a function inside another function. This creates a private function. 307 | 308 | //The inside functions can then access the arguments and variables of outside, parent functions, but the parent functions cannot touch //inside the child function. 309 | 310 | //Something really special happens when you return that function inside another function. Let’s take a look! 311 | 312 | //Closure - Recipe 313 | 1. create your parent function 314 | ex. the checkscope function 315 | 2. define some variables in the parent’s local scope (this can be accessed by the child function) 316 | ex. var scope = “local scope” 317 | 3. define a function inside the parent function. We call this a child. 318 | ex. the innerFunc function 319 | 4. return that function from inside the parent function 320 | ex. where it says ‘return innerFunc’ 321 | 322 | 323 | function checkscope() { 324 | var scope = "local scope"; 325 | function innerFunc() { 326 | return scope; 327 | }; 328 | return innerFunc; 329 | }; 330 | 331 | 332 | 333 | //Closure Scope - Execution 334 | 1. run parent function and save to a variable. This variable will hold whatever that function RETURNS 335 | 2. optional: check what that variable holds as its value. (Hint: it should be the inner function) 336 | 3. run the inner function. 337 | 4. what happens?? 338 | 339 | var scope = "global scope"; 340 | function checkscope() { 341 | var scope = "local scope"; 342 | function innerFunc() { 343 | return scope; 344 | } 345 | return innerFunc; 346 | }; 347 | var test = checkscope(); 348 | test 349 | test() 350 | 351 | 352 | //Closure Scope - more examples 353 | function outside(x) { 354 | var z = x + 1; 355 | console.log(z); 356 | function inside(y) { 357 | console.log(z + y); 358 | function moreInside(a) { console.log(‘new argument a: ’, a, ‘ previous argument y: ’, y, ‘ and the first two arguments z: ’, z, ‘ and x: ‘, x );} 359 | return moreInside(); 360 | } 361 | return inside; 362 | } 363 | 364 | fn_inside = outside(3); 365 | result = fn_inside(5); // returns 9 366 | result1 = outside(3)(5); // returns 9 367 | 368 | 369 | 370 | //Closure Scope - Module Pattern 371 | var Module = (function(){ 372 | var privateProperty = 'foo'; 373 | function privateMethod(args){ 374 | // do something 375 | } 376 | return { 377 | publicProperty: "", 378 | publicMethod: function(args){ 379 | // do something 380 | }, 381 | privilegedMethod: function(args){ privateMethod(args); } 382 | } 383 | })(); //immediate invocation 384 | 385 | 386 | 387 | //Closure Scope - more examples 388 | var makeStopwatch = function(){ 389 | console.log('initialized'); 390 | var elapsed = 0; 391 | console.log(elapsed); 392 | var stopwatch = function(){ console.log('stopwatch'); 393 | return elapsed; 394 | }; 395 | var increase = function(){ elapsed++; }; 396 | setInterval(increase, 1000); 397 | return stopwatch; 398 | }; 399 | var x = makesStopwatch(); 400 | 401 | 402 | //A Closure exercise 403 | Write a function that takes a number as it’s only argument, let’s name the parameter firstNum and includes one function inside. Have the inner function take one number as it’s argument, let’s name that one secondNum. Now in the inner function, add firstNum and secondNum. See closure recipe for step-by-step guidance! 404 | 405 | 406 | 407 | 408 | //Closure Scope - more examples 409 | function counter() { 410 | var n = 0; 411 | return { 412 | count: function() { return n++; }, 413 | reset: function() { n = 0; } 414 | }; 415 | } 416 | var c = counter(), d = counter(); c.count() 417 | d.count() 418 | c.reset() 419 | c.count() 420 | d.count() 421 | 422 | 423 | 424 | //Closure Scope - more examples 425 | //Closures have access to the outer function’s variable even after the outer function returns: 426 | function celebrityName (firstName) { 427 | var nameIntro = "This celebrity is "; 428 | function lastName (theLastName) { 429 | return nameIntro + firstName + " " + theLastName; 430 | } 431 | return lastName; 432 | } 433 | 434 | var mjName = celebrityName ("Michael"); 435 | mjName ("Jackson"); 436 | 437 | 438 | //Closure Scope - Private variables ex. 439 | //Closures store references to the outer function’s variables, NOT THE VALUE 440 | function celebrityID () { 441 | var celebrityID = 999; 442 | return { 443 | getID: function () { 444 | return celebrityID; 445 | }, 446 | setID: function (theNewID) { 447 | celebrityID = theNewID; 448 | } 449 | } 450 | } 451 | var mjID = celebrityID (); 452 | mjID.getID(); 453 | mjID.setID(567); 454 | mjID.getID(); 455 | 456 | 457 | //Closures gone wrong (extra credit) 458 | //Because closures have access to the updated values of the outer function’s variables, they can also lead to bugs when the outer function’s variable changes with a for loop. 459 | function celebrityIDCreator (theCelebrities) { 460 | var i; 461 | var uniqueID = 100; 462 | for (i = 0; i < theCelebrities.length; i++) { 463 | theCelebrities[i]["id"] = function () { 464 | return uniqueID + i; 465 | } 466 | } 467 | return theCelebrities; 468 | } 469 | var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}]; 470 | var createIdForActionCelebs = celebrityIDCreator (actionCelebs); 471 | var stalloneID = createIdForActionCelebs[0];

console.log(stalloneID.id()); //103 472 | 473 | //Fixing closures (extra credit) 474 | //To fix this side effect (bug) in closures, you can use an Immediately Invoked Function Expression (IIFE), such as the following: 475 | function celebrityIDCreator (theCelebrities) { 476 | var i; 477 | var uniqueID = 100; 478 | for (i = 0; i < theCelebrities.length; i++) { 479 | theCelebrities[i]["id"] = function (j) { 480 | return function () { 481 | return uniqueID + j; 482 | } () 483 | } (i); 484 | } 485 | return theCelebrities; 486 | } 487 | 488 | //Fixing closures (extra credit) 489 | var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}]; 490 | 491 | var createIdForActionCelebs = celebrityIDCreator (actionCelebs); 492 | 493 | var stalloneID = createIdForActionCelebs [0]; 494 | 
console.log(stalloneID.id); // 100 495 | 496 | var cruiseID = createIdForActionCelebs [1];
console.log(cruiseID.id); // 101 497 | 498 | //Higher Order Functions as First-Class Objects 499 | This means that you can pass functions as arguments to create callbacks or do other functional goodness 500 | 501 | AND return functions from functions which creates closures. 502 | 503 | Exciting right?? 504 | 505 | //Higher Order Functions - example 506 | var increment = function(n){ 507 | return n + 1; 508 | } 509 | var square = function(n){ 510 | return n*n; 511 | } 512 | var doMath = function(n, func){ 513 | return func(n); 514 | } 515 | 516 | doMath(5, square); 517 | doMath(4, increment) 518 | 519 | //window.setTimeOut() 520 | var fun = function(){ 521 | function(x){ log(x);}(‘hi’); 522 | } 523 | setTimeout(function(){ fun(‘hi’); }, 1000); 524 | 525 | //Callbacks - exercise 526 | What if we wanted to write a function that calls a function twice? 527 | 528 | It will have two named parameters, func for the function and arg for the argument that you will pass it. If you pass the alert function, and the string ‘hi’, you want the function to result in 2 alert pop ups with the word hi alert(‘hi’) 529 | 530 | //Callbacks - exercise 531 | What if we wanted to write a function that calls a function twice? 532 | 533 | It will have two named parameters, func for the function and arg for the argument that you will pass it. If you pass the alert function, and the string ‘hi’, you want the function to result in 2 alert pop ups with the word hi alert(‘hi’) 534 | 535 | //Call vs Apply 536 | 537 | //Review Exercise 1 538 | function splat(fun) { 539 | return function(array) { 540 | return fun.apply(null, array); 541 | }; 542 | } 543 | 544 | var addArrayElements = splat(function(x, y) { return x + y }); 545 | 546 | addArrayElements([1, 2]); 547 | 548 | //forEach 549 | 550 | //Write filter 551 | Looks through each value in the list, returning an array of all the values that pass a truth test (predicate). 552 | var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); 553 | => [2, 4, 6] 554 | 555 | //re-write these functions 556 | select('>2', [1,2,3,4]) 557 | returns [3,4] 558 | 559 | map(1, '+' , [2, 3]) 560 | returns [3,4]; 561 | 562 | //Further Steps 563 | Want to TA one of these classes? Please e-mail me bianca@hackreactor.com 564 | 565 | I recommend: (O’Reilly Press) Functional JavaScript 566 | Eloquent JS Ch. 6 (functional programming part) 567 | 568 | 569 | 570 | 571 | 572 | -------------------------------------------------------------------------------- /OLD/Day3Challenges.js: -------------------------------------------------------------------------------- 1 | //How will the following evaluate 2 | =============================================================== 3 | false && true || true 4 | false && (true || true) 5 | true ? console.log(3) : console.log(2); 6 | false ? console.log(3) : console.log(2); 7 | 8 | //Some examples of logical operators in action 9 | =============================================================== 10 | if (x > 5 && x < 10) 11 | { 12 | // action to be performed if x is greater than 5 13 | // and less than 10 14 | } 15 | 16 | //And you might use these while setting up a website 17 | =============================================================== 18 | function sayHi(name) 19 | { 20 | name = name || 'stranger'; 21 | alert('Hi there ' + name); 22 | } 23 | 24 | function isAdult(age) { 25 | return age && age > 17 ; 26 | } 27 | 28 | 29 | 30 | //Write a function that adds up all the numbers from 1 up to, 31 | //but not including num 32 | =============================================================== 33 | //This function will return a number 34 | //[input: 5] 35 | //[output: 10] 36 | 37 | //Write a range function that takes a start and an end value 38 | //and returns an array containing all number from start up to 39 | //and including end 40 | ============================================================== 41 | //This function will return a number 42 | //[input: 3, 8] 43 | //[output: [3,4,5,6,7,8]] 44 | 45 | //Easy stuff right? How about making a function that takes 46 | //two numbers, a base and exponent and returns the result 47 | ============================================================= 48 | //This function will return a number 49 | //[input: 2, 5] 50 | //[output: 32] 51 | 52 | //create a function named 'arrayCounter' that takes in a parameter which 53 | // is an array. The function must return the length of an array passed in 54 | // or 0 if a 'string', 'number' or 'undefined' value is passed in. 55 | ============================================================== 56 | //[hint: try using logical operators in your function] 57 | 58 | 59 | //Type conversions 60 | ============================================================== 61 | 1. Number('3'); 62 | 2. String(false); 63 | 3. Boolean([]); 64 | 4. Object(3); 65 | 66 | //change func so that it works with the for loop 67 | //with semi colons 68 | ================================================= 69 | var func = function(){}; 70 | for(var i = 0; i < func.length; i++){ 71 | console.log(func[i]); 72 | } 73 | //change obj so that it works with the for loop 74 | //with semi colons 75 | ================================================= 76 | var obj = {}; 77 | for(var i = 0; i < func.length; i++){ 78 | console.log(obj[i]); 79 | } 80 | 81 | 82 | //write a function that changes an object into an array of it's values 83 | //input => {one: 1, two: 2, three: 3, four: 4} 84 | //output => [1,2,3,4] 85 | 86 | //now write a function that takes an object and creates and array of it's 87 | //properties 88 | //input => {one: 1, two: 2, three: 3, four: 4} 89 | //output => ['one','two', 'three', 'four'] 90 | 91 | //what is the difference between a side effect of a function and 92 | //what a function returns? -------------------------------------------------------------------------------- /OLD/Day5Challenges.js: -------------------------------------------------------------------------------- 1 | //function exercises with callbacks 2 | =============================================== 3 | //Callbacks in JavaScript are functions that are passed as arguments to other functions. 4 | //There's a function called setTimeout(), it takes two arguments 5 | //the first is the function to be performed 6 | //the second is the amount of milliseconds that will elapse 7 | // before the function is called back and run 8 | setTimeout(callback, 5000); 9 | //will run the callback function after 5 seconds 10 | //You can also write setTimeout with anonymous functions 11 | setTimeout(function(){}, 5000); 12 | 13 | //lets have fun with callbacks, initialize an array 14 | //called allData 15 | ============================================== 16 | var allData = []; 17 | //Write a function called logIt accepts an argument named userData 18 | //if the input is a string, console.log the input 19 | //if the input is an object, console.log the key value pairs 20 | //like so 'key:value' 21 | 22 | //now write a function called getInput that takes two args 23 | //options and the callback 24 | //have this function push options into the allData array 25 | //and then run the callback function with options as its only 26 | //argument 27 | 28 | // When we call the getInput function, we pass logIt as a parameter. 29 | // So logStuff will be the function that will called back 30 | // (or executed) inside the getInput function 31 | 32 | // getInput ({name:"Will", speciality:"Busting a move"}, logIt); 33 | // name: Will 34 | // speciality: Busting a move 35 | 36 | // getInput('cool', logIt); 37 | // cool 38 | 39 | 40 | ============================================== 41 | //Let's do some math stuff 42 | //We've written these functions before so it 43 | //should be a piece of cake right? 44 | //write a function named range that takes two numbers 45 | //and returns an array of the numbers populated with 46 | //the range from the first to the second 47 | 48 | //now create a function called sum that takes an 49 | // array and returns the sum of that array 50 | 51 | //now chain together sum() and range() so that 52 | //you have a function that calculates the sum of all 53 | // numbers in the range 54 | 55 | 56 | //So now that we've seen we can chain methods and 57 | //put use functions as arguments, let's play with 58 | //some arguments 59 | =============================================== 60 | 61 | 62 | 63 | 64 | //function exercises with scope 65 | //What will the value of x be after running f1(); 66 | //What about f2(); 67 | ================================================ 68 | var x = 'outside'; 69 | var f1 = function() { 70 | var x = 'inside f1'; 71 | }; 72 | var f2 = function() { 73 | x = 'inside f2'; 74 | }; 75 | 76 | var name = 'Will'; 77 | 78 | 79 | write a function that takes a series 80 | of arguments and returns an arr 81 | 82 | toArray(1,2,3,4,5,6) => [1,2,3,4,5,6] 83 | ================================================= 84 | write a function that return the type of 85 | the given argument 86 | 87 | type({}) => 'object' 88 | type([]) => 'array' 89 | ================================================= 90 | ***HARD CHALLENGES BELOW*** 91 | ================================================= 92 | write a function called applied that mimics the 93 | functionality of apply (without the context part) 94 | 95 | applied(func, [arr]) => func(arr1,arr2,arr3) 96 | ================================================= 97 | write a function called partial that mimics this 98 | behavior //TODO: more details 99 | 100 | var fullName = function ( firstName, lastName ) { 101 | return firstName + ' ' + lastName; 102 | }; 103 | 104 | var billName = partial( fullName, 'Bill' ); 105 | 106 | billName( 'Smith' ); // "Bill Smith" 107 | billName( 'Clinton' ); // "Bill Clinton" 108 | 109 | ================================================= 110 | write a function that adds the properties of a second 111 | object to the first one 112 | var obj1 = {'first': 1, 'second': 2}, 113 | obj2 = {'another': 'one', 'surprise': 'combined'} 114 | extend(obj1, obj2) => {'first': 1, 'second': 2, 'another': 'one', 'surprise': 'combined'} 115 | ================================================= 116 | write a function that takes a function and only 117 | allows that function to be called once. 118 | 119 | ================================================= 120 | (EXTRA CREDIT) 121 | write a function that mimics throttle 122 | Returns a new function that can only be invoked 123 | once within milliseconds. 124 | Any calls that occur before the allotted 125 | time has passed are disregarded. 126 | The handler will be invoked at the end of the delay. 127 | 128 | ================================================= 129 | (EXTRA CREDIT) 130 | compose(fn1, fn2, ..., fnN) 131 | Compose multiple functions to create a new function. 132 | For example, wu.compose(f, g, h)(x) is equivalent 133 | to f(g(h(x))). 134 | 135 | >>> function square(x) { return x * x; } 136 | >>> function add2(x) { return x + 2; } 137 | >>> wu.compose(square, add2)(5); 138 | 49 139 | >>> wu.compose(add2, square)(5); 140 | 27 141 | 142 | -------------------------------------------------------------------------------- /OLD/Day6Challenges.js: -------------------------------------------------------------------------------- 1 | write a function that takes two parameters, one, 'arr', is an array 2 | and the second, 'x', is the number. The function returns 3 | the first 'x' indices of the array 4 | firstIndex([1,2,3,4], 3) => [1,2,3] 5 | 6 | write a function that returns the last elements of an 7 | array using the previous function (note: you cannot 8 | use slice here!) 9 | 10 | lastIndex([1,2,3,4], 3) => [4,3,2] 11 | 12 | write a function that will merge the first object into 13 | the second object. If the property already exists, on the second 14 | object, do not overwrite it. 15 | 16 | rewrite the previous function using _.each 17 | 18 | write a function that takes a nested array and returns 19 | a one dimentional array. 20 | 21 | use _.map to change the 'name' property to your name and the 22 | 'isAwesome' property to true of these objects in this array of 23 | objects - 24 | [ 25 | {loves: 'iceCream' name: 'Billy', isAwesome: false;} 26 | {loves: 'sandwiches' name: 'Albrey', isAwesome: false;} 27 | {loves: 'pizza' name: 'Spencer', isAwesome: false;} 28 | {loves: 'strawberries' name: 'Fred', isAwesome: false;} 29 | ] 30 | 31 | write a function that takes a random number(1-10) of randomly 32 | generated num inputs (1-10). With those inputs, you add 33 | them all together and return the result. 34 | 35 | randomAdder(1,4,7,2) => 14 36 | 37 | generate the random numbers by using this function: 38 | var generateNum = function(){ 39 | return Math.floor(Math.random() * 11); 40 | } 41 | 42 | step 1: create an array of catNames: 43 | 44 | var catNames = []; 45 | 46 | step 2: use _.map to loop through the catnames and apply it 47 | to the CatMaker function. This will return an array of cat objects 48 | 49 | 50 | function CatMaker(name) { 51 | var owner = "me"; 52 | return { 53 | speak: function () { 54 | console.log("Meow my name is " + name +" and my owner is" + owner); 55 | }, 56 | changeOwner: function(newOwner){ 57 | owner = newOwner; 58 | } 59 | }; 60 | } 61 | 62 | step 3: use _.each to loop through all the cat objects 63 | and call the speak method. 64 | 65 | re-write the makeStopWatch exercise from class yesterday 66 | without looking (it will be difficult but it will not help you 67 | if you do not try for at least 20min to do it on your own. 68 | Instead ask for help rather than peek.) 69 | Remember, you need to have a function called 70 | stop watch that you can access outside of the parent function so 71 | that you can check the number of seconds that have elapsed. 72 | 73 | now implement it using the module pattern (return an object with 74 | a method called stopwatch that returns the elapsed time). Now, 75 | add another priveleged method that resets the timer and 76 | another one that pauses the timer and one that restarts the 77 | timer after being paused. 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /OLD/FuncIntro.js: -------------------------------------------------------------------------------- 1 | www.github.com/bgando/JSFundamentals 2 | 3 | var results = data.results; 4 | var nameArr = []; 5 | for(var i = 0; i < results.length; i++){ 6 | var nameStr = results[i].animal; 7 | var firstLetter = nameStr[0]; 8 | var theRest = nameStr.slice(1); 9 | var name = firstLetter.toUpperCase() + theRest; 10 | console.log('Name: ' + name); 11 | nameArr.push(name); 12 | 13 | 14 | } 15 | 16 | var data = { 17 | results: [ 18 | { animal: 'fox', 19 | numberOfLegs: 4, 20 | says: '??', 21 | matches: 22 | [ 'dog', 'cat', 'pig'] 23 | }, 24 | { animal: 'frog', 25 | numberOfLegs: 4, 26 | says: 'ribbit', 27 | matches: 28 | [ 'whale', 'cat', 'pig', 'rabbit'] 29 | }, 30 | { animal: 'dog', 31 | numberOfLegs: 4, 32 | says: 'woof', 33 | matches: 34 | [ 'dog', 'fish', 'pig'] 35 | }, 36 | { animal: 'human', 37 | numberOfLegs: 2, 38 | says: 'hello', 39 | matches: 40 | [ 'frog', 'duck', 'pig'] 41 | }, 42 | { animal: 'fish', 43 | numberOfLegs: 0, 44 | says: 'blub', 45 | matches: 46 | [ 'dog', 'rabbit', 'frog', 'human'] 47 | }, 48 | { animal: 'whale', 49 | numberOfLegs: 0, 50 | says: 'aaarrrhhh', 51 | matches: 52 | [ 'duck', 'fish', 'pig'] 53 | }, 54 | { animal: 'duck', 55 | numberOfLegs: 2, 56 | says: 'quack', 57 | matches: 58 | [ 'fish', 'human', 'chicken', 'whale'] 59 | } 60 | ]}; 61 | 62 | 63 | 64 | 65 | 66 | //ternary operators 67 | ================================================= 68 | 69 | var test = true; 70 | //if test is true, log true, else log false 71 | if(test === true) { 72 | console.log(true); 73 | } else{ 74 | console.log(false) 75 | } 76 | 77 | test ? console.log(true) : console.log(false); 78 | 79 | //logic operators 80 | ================================================= 81 | && AND 82 | 83 | var x = true; 84 | var z = true; 85 | 86 | x && z 87 | 88 | || OR 89 | 90 | var potatoes = false; 91 | var tomatoes = true; 92 | 93 | potatoes || tomatoes => true 94 | 95 | ! NOT 96 | 97 | (cond1 || cond2) === !(!cond1 && !cond2) 98 | 99 | (cond1 && cond2) === !(!cond1 || !cond2) 100 | 101 | 102 | if(){ 103 | console.log('whatever') 104 | } 105 | 106 | !! 107 | 108 | //truthy + falsy 109 | ================================================= 110 | JavaScript Falsy Values: 111 | null, false, 0, undefined, NaN, and “” 112 | 113 | (this last item is an empty string). 114 | — Note that Infinity, which is a special 115 | number like NaN, is truthy; it is 116 | not falsy, while NaN is falsy. 117 | 118 | JavaScript Truthy Values: 119 | Anything other than the falsy values. 120 | 121 | // functions + logic operators 122 | ================================================= 123 | 124 | function documentTitle(theTitle) 125 | theTitle = theTitle || "Untitled Document"; 126 | return theTitle; 127 | } 128 | 129 | var data = documentTitle(); 130 | data => "Untitled Document" 131 | 132 | function isAdult(age) { 133 | if (age && age > 17) { 134 | return true; 135 | } 136 | else { 137 | return false; 138 | } 139 | } 140 | Use this: 141 | 142 | function isAdult(age) { 143 | return age && age > 17 ; 144 | } 145 | 146 | if (userName) { 147 | logIn (userName); 148 | } 149 | else { 150 | signUp (); 151 | } 152 | Use this: 153 | 154 | userName && logIn(userName) || signUp(); 155 | -------------------------------------------------------------------------------- /OLD/IntroToFunctional.js: -------------------------------------------------------------------------------- 1 | function splat(fun) { 2 | 3 | return function(array) { 4 | 5 | return fun.apply(null, array); 6 | 7 | }; 8 | 9 | } 10 | 11 | var addArrayElements = splat(function(x, y) { return x + y }); 12 | 13 | addArrayElements([1, 2]); 14 | 15 | 16 | .sort(); 17 | 18 | write a function 19 | 20 | select('>2', [1,2,3,4]) 21 | that returns [3,4] 22 | 23 | map(1, '+' , [2, 3]) 24 | 25 | 26 | 27 | var first = function(x) { 28 | var z = "it's lonely on top" 29 | console.log("in the first function y = ", y) 30 | var second = function() { 31 | var y = "I'm down here!!" 32 | var third = function() { 33 | console.log("remember variable hoisting? y = ", y); 34 | var y = "I'm in this pretty deep.." 35 | console.log("What do you think y is down here? It is ", y); 36 | } 37 | } 38 | } 39 | 40 | function test(o) { 41 | var i = 0; // i is defined throughout function 42 | if (typeof o == "object") { 43 | var j = 0; // j is defined everywhere, not just block 44 | for(var k=0; k < 10; k++) { // k is defined everywhere, not just loop 45 | console.log(k); // print numbers 0 through 9 46 | } 47 | console.log(k); // k is still defined: prints 10 48 | } 49 | console.log(j); // j is defined, but may not be initialized 50 | } 51 | -------------------------------------------------------------------------------- /OLD/PracticeProblemsDay7.js: -------------------------------------------------------------------------------- 1 | Recursion: 2 | 3 | Recursion is like a while loop for functions. 4 | 5 | - CONVERTING LOOPS INTO RECURSIVE FUNCTIONS: 6 | 7 | 8 | while (condition) 9 | { 10 | //do this 11 | } 12 | // while loop: 13 | function albrey(x) { // 1. argument 14 | 15 | while (x > 0) { // 2. base/terminating case 16 | console.log(x) // 3. action 17 | x = x - 1 // 4. incrementer 18 | } 19 | 20 | } 21 | 22 | 23 | function albrey2(x) { 24 | if (x <= 0) { // 1. terminating case 25 | return; 26 | } else { 27 | console.log(x) // 2. action 28 | return albrey2(x - 1); // 3. incrementer 29 | } 30 | } 31 | 32 | 33 | RECURSIVE FUNCTIONS NEED 3 THINGS: 34 | 35 | INPUT: input argument, where you start. 36 | 37 | TERMINATING CASE: the if statement. You need to know when to stop, and what 38 | to return when you finally do. 39 | 40 | INCREMENTER: the path between your base case and your terminating case. 41 | STEPS include your base case and an action that brings it closer 42 | to your terminating case. 43 | 44 | 1. Write a function 'addition' that takes an argument and uses 45 | a while loop to adds up all the integers between 0 and the argument. 46 | 47 | // 1. terminating case is num equals zero; 48 | // 2. action: adding each positive integer to a total 49 | // 3. incrementer is going to subtract by 1 50 | 51 | 2. Change your while loop into a recursive function. 52 | 53 | function addition(num) { 54 | var total = 0; 55 | while (num > 0) { // base case!!!!! 56 | total += num // action 57 | num--; // incrementer 58 | } 59 | 60 | return total; 61 | } 62 | 63 | function recursiveAddition(num) { 64 | if (num <= 0) { // terminating case 65 | return num; 66 | } else { 67 | return num + recursiveAddition(num - 1); //decrementer 68 | } 69 | } 70 | 71 | function recursiveAdditionStack(num) { 72 | var stack = []; 73 | function addition(num) { 74 | if (num <= 0) { 75 | return stack; 76 | } else { 77 | stack[num - 1] = num; 78 | return addition(num - 1); 79 | } 80 | } 81 | 82 | return addition(num); 83 | } 84 | 85 | 3. Write a function 'exponent' that takes two arguments 86 | base, and expo, uses a while loop to return the exponenet value 87 | of the base. 88 | 89 | 4. Write a function 'RecursiveExponent' that takes two arguments 90 | base, and expo, recursively returns exponent value 91 | of the base. 92 | 93 | Write a function 'recursiveMultiplier' that takes 94 | two arguments, 'arr and num', and multiplies 95 | each arr value into by num and returns 96 | an array of the values. 97 | 98 | /* hint use closure */ 99 | 100 | Write a function 'recursiveReverse' that takes an array 101 | and uses recursion to return its contents in reverse 102 | 103 | /* hint use closure */ 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /OLD/stopWatch.js: -------------------------------------------------------------------------------- 1 | var each = function(arr, func){ 2 | for(var i = 0; i < arr.length; i++){ 3 | func(arr[i], i, arr); 4 | } 5 | } 6 | 7 | var log = function(val, i){console.log(val, i)} 8 | 9 | each([1,2,3,4], log); 10 | 11 | 12 | var filter = function(arr, test){ 13 | results = []; 14 | _.each(arr, function(val){ 15 | if(test(val)) { 16 | results.push(val); 17 | } 18 | }) 19 | return results; 20 | } 21 | 22 | 23 | [1,0,[1,2,3,4]] 24 | [2,1,[1,2,3,4]] 25 | [3,2,[1,2,3,4]] 26 | 27 | 28 | 29 | var isEven = function(num){ 30 | if(num % 2 === 0) { 31 | return true; 32 | } else { 33 | return false; 34 | } 35 | } 36 | 37 | 38 | 39 | filter([2,3,4,5,16], isEven) 40 | 41 | 42 | 43 | 44 | 45 | var makeStopwatch = function(){ 46 | var elapsed, stopwatch, increase; 47 | 48 | console.log('initialized'); 49 | elapsed = 0; 50 | console.log(elapsed); 51 | stopwatch = function(){ 52 | console.log('stopwatch'); 53 | return elapsed; 54 | }; 55 | increase = function(){ 56 | elapsed++; 57 | }; 58 | 59 | setInterval(increase, 1000); 60 | return stopwatch; 61 | }; 62 | 63 | var x = makesStopwatch(); 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JSFundamentals Course Description 2 | 3 | Come here to solidify your understanding of Objects, Arrays and Functions in JavaScript and learn the common mistakes made by beginners. This is a highly interactive course that uses exercises and projects to drive home these JS Fundamentals. You will finish this course with expert knowledge on one of the most important aspects of the language: objects, arrays and functions. This course is the first of three in the JavaScript Fundamentals series. 4 | 5 | # Course Format 6 | 7 | The course is taught over four days with one three-hour workshop held each day. Two of these workshops consist of lectures and exercises that check the understanding of the material. The other two workshops are project-based where the fundamental concepts learned are put to use in independent projects with TAs helping each student at their level. The lectures and projects alternate. This course is the first of three in the JavaScript Fundamentals series. 8 | 9 | # Syllabus 10 | 11 | ### DAY 1 12 | 13 | Monday (6pm-9pm) Lecture + Exercise Day 14 | Topic: Everything you need to know about Objects + Arrays 15 | Source: https://github.com/bgando/JSFundamentals/blob/master/objectsAndArrays.js 16 | 17 | - basic definitions of objects and arrays 18 | - similarities between objects and arrays 19 | - differences between objects and arrays 20 | - how to add values 21 | - how to access values 22 | - failed property lookup 23 | - special value undefined 24 | - bracket notation 25 | - dot notation and limitations 26 | - special characters in property names 27 | - property/index stringification in arrays 28 | - object lieteral 29 | - looping through objects and arrays 30 | - length doesn't hold non-integer properties 31 | - definition of method 32 | - native methods and constructors of objects and arrays 33 | 34 | ### DAY 2 35 | 36 | Tuesday (6pm-9pm) Project Day 37 | Topic: Today you will work with your pair on a project that utilizes Objects + Arrays 38 | Source: https://github.com/bgando/JSFundamentals/blob/master/Day2Challenges.js 39 | 40 | - console.log 41 | - loop 42 | - push 43 | - join 44 | - pop 45 | - Array.isArray 46 | - control flow 47 | - length 48 | 49 | ### DAY 3 50 | 51 | Wednesday (6pm-9pm) Lecture + Exercise Day 52 | Topic: Today we will straighten out common confusions related to functions with exercises intertwined 53 | Source: 54 | 55 | 56 | 57 | ### DAY 4 58 | 59 | Thursday (6pm-9pm) Project Day 60 | Topic: Today you will work with your pair to tie everything together for your final project. 61 | Source: 62 | 63 | 64 | ## Goals of this course 65 | 66 | The goal of the JavaScript Fundamentals 1, 2 and 3 - collectively called Hack Reactor Junior (HRJR) classes - is to give technical foundation and support for those who have been learning JavaScript for a couple of months, so that they will have reached a level required for the Hack Reactor admission's interviews. 67 | 68 | *IMPORTANT*: completion of the HRJR courses is no guarantee of admission, nor has any influence in the admissions process. 69 | 70 | It is our goal, however, that students who successfully complete the HRJR series will have covered all JavaScript topics necessary for the interview. 71 | 72 | If Hack Reactor takes people from 60 to 120 in web development, then Hack Reactor Junior takes people from 10 to 60 ('coz we don't teach variables and the like). 73 | 74 | ## Prerequisites 75 | 76 | Students should have 1-2 months experience with JavaScript and programming, about the level of Codecademy. Students should understand and be familiar with variables, if/else statements, for loops and the most basic of JavaScript syntax. 77 | 78 | ## Textbook 79 | 80 | No textbook is required for this course. All materials are included in this github repo. 81 | 82 | ## Technical requirements 83 | 84 | Laptop, Chrome browser and a text editor. We recommend Sublime Text 3 for this course becuase its fast, light weight and you can run your JavaScript files in its console with Node. 85 | 86 | ## References 87 | 88 | http://www.w3schools.com/jsref/jsref_obj_array.asp 89 | 90 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array 91 | 92 | http://www.w3schools.com/jsref/jsref_obj_array.asp 93 | 94 | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object 95 | 96 | ## Acknowledgements 97 | 98 | This course was created by Bianca Gondolfo @bgando. Contributors include and Will Johnson @wcjohnson11, Albrey Brown @albreyb and Monthy Python @monthypython. 99 | --------------------------------------------------------------------------------