Skip to content

Instantly share code, notes, and snippets.

@VPAbraham
Last active August 27, 2019 18:12
Show Gist options
  • Select an option

  • Save VPAbraham/cdffe4b9311489139d96f7218a03b783 to your computer and use it in GitHub Desktop.

Select an option

Save VPAbraham/cdffe4b9311489139d96f7218a03b783 to your computer and use it in GitHub Desktop.
Mod-2-Notes

Array Prototypes - Iteration Methods

Lesson Goals:

  • Articulate the difference between arrays and objects and when to use each
  • Define what a prototype method is and what it allows you to do
  • List several prototype methods for arrays and objects
  • Understand how to manipulate arrays and objects, and the use-cases for different prototype methods.
What do you know about arrays and objects?

Arrays:

  • list/collection of data
  • indices
  • access elems via []
  • actually objects
  • list of related values
    • same type of data

Objects:

  • group of similarly related data
  • key/value pair organization
  • complex data type

Arrays & Objects

The more complex data types available in JavaScript

Arrays

Essentially a comma separated list of related values.

['onions', 'garlic', 'peppers']

Review of for loops

for(part1; part2; part3) { part4 }

  1. initialization
  2. condition
  3. modifier
  4. statement

Prototype methods

Prototype - a model of something and how it should look or behave. Can build prototypes to create multiple copies of similar models.

Method - a function that's defined on an object

Array Iteration Methods (Prototypes)

forEach():

ES5 vs ES6

Arrow Functions

example of an arrow refactor:

let evens = [2, 4, 6, 8];

// ES5
let pairs = evens.map(function(num) {
  return {even: num, odd: num + 1}
});

// ES6
let pairs = evens.map((num) => {
  return {even: num, odd: num + 1}
});
pairs;

// num does not require parens since it is one argument, but it is good to have in case you want to add another later on

Spread operator:

The spread operator took the individual values from the array and added them into the new array.

var arr = [4, 5, 6];

// es5
var completeArr = [1, 2, 3].concat(arr); // [1, 2, 3, 4, 5, 6]

// es6
var completeArr = [1, 2, 3, ...arr]; // [1, 2, 3, 4, 5, 6]

Complex data types are defined by reference, not by value.

.sort(); will mutate the original array even if it is assigned to another var name.

let numbers = [5, 7, 2, 6, 1];
let sortedNumbers = numbers;
sortedNumbers.sort();

numbers;
//both now return [ 1, 2, 5, 6, 7 ]

Instead of assigning numbers to sortedNumbers:

let sortedNumbers = [...numbers];
//now numbers; returns [5, 7, 2, 6, 1]

Destructuring:

Allows us to create variables based on values nested deep within an object

let dog = {
  name: 'Spot',
  breed: 'pug',
  tricksLearned: {
    sit: true,
    stay: true,
    rollOver: false,
    beg: true,
    speak: false
  }
}

let { name, breed } = dog;

console.log(breed);
console.log(name);

another example: https://repl.it/@vpforvp/WorldlyOtherAlgorithm

Intro to NPM

(Node Package Manager)

Vocab:

  • Package Manager - a registry where developers can publish small, reusable pieces of code that they’ve written and would like others to be able to incorporate into their projects
  • Package - small, independent piece of reusable code that often solves a commonplace problem
  • Dependency - a package that your project relies on in order to function properly. (packages can BE dependencies as well as HAVE dependiencies)
  • Configuration File - a file that allows you to define how a particular tool you’re using should interact with your codebase

Tools for developing:

  • Text editor
  • Browser
  • Dev tools
  • Git/GH
  • NPM
  • mocha & chai
  • extensions
  • linters

In Your Notebook Take a look at the files and directory structure of this repo What are some things that seem new to you? What’s familiar? Why are so many files prefixed with a dot? The folder structure is more complex than what I am used to and there seems to be a lot more files of varying file extensions that i haven't used like python and .toml.

I believe the dot may mean that they are modules that can be run on other files but I am not sure.

Configuration Files:

  • eslintrc - defines out rules for stylistic conventions we want our code to follow
  • .gitignore - tells git not to push certain files to our remote repo
  • README.md = allows us to describe our application and provide any instructions to people trying to use or contribute to it
  • package-lock.json - builds a dependency tree of any third-party code we are relying on and what versions of those packages our apps are using
  • package.json - describes our application to NPM and what dependencies we need in order to use and develop the app

With the exception of README.md, each of these is some sort of config file. A configuration file is a file that allows you to define how a particular tool you're using should interact with your codebase.

NPM

The NPM files: package.json and package-lock.json

NPM = Node Package Manager Package manager - a registry where devs can publish small, reusable pieces of code that they've written (a package), and allow other devs to download it directly into their projects as dependencies.

  • a package is a small, independent piece of reusable code
  • a dependency is a package that your project relies on in order to work

As an example, pretend that the .filter() method did not exist in JavaScript for filtering arrays. Developers would constantly have to write some sort of function that would allow them to easily filter any array they might need to work with. This means developers all over the world would be spending time writing some kind of code that looked like the following:

Array.prototype.filter = function(callback) {
  var filteredData = [];

  this.forEach(function(i) {
    if (callback(i)) {
      filteredData.push(i)
    }
  })
  return filteredData;
}

package.json - config file; describes the app to NPM

package-lock.json = build dependency tree of the files/packages our app uses

/node_module - directory holds dependencies

Semantic Versioning

You’ll notice that the dependencies we install each have a value associated with them like ‘1.4.6’ – these values are the version numbers of our dependencies.

As developers update their packages, they must increase the version number of their package to allow any projects relying on it some lee-way before they update.

Think back to the filter example code from earlier. Imagine the developer who created that package decided to change the name of the method from filter to sift. If this change took effect immediately, as soon as the developer pushed it to GitHub, now anybody using the filter method would have a broken application. Version numbers allow us to rely on a particular representation of a package (e.g. filter at version 1.2.3), then update manually to a newer version (e.g. sift at version 2.0.0) when we have the time and knowledge to refactor our applications to work with the new changes.

#iron-fe

.find:

stops after finding the first element that meets the criteria

eastereggs.find(egg => egg.color === 'orange').color
//then append this to the DOM

.map:

returns an array of the same length always

eastereggs.map(egg => {
  return egg.candy
});

.filter:

returns a new array of only the criteria given

.sort:

sort mutates the original array.

eastereggs.sort((eggA, eggB) => 
  return eggB.candyCount - eggA.candyCount);
  //4-1.  look up on MDN

.reduce:

eastereggs.reduce(totalMoney, egg) => {
  totalMoney += egg.money;
  return totalMoneyo
}

jQuery Intro - DOM Traversal, Manipulation, and Events

Learning Goals

  • What is jQuery?
  • How to use jQuery to interact with the DOM

jQuery is a library that uses CSS style selectors to find elements on the DOM and interact w/ them. Used in about 71% of top webpages.

Vocab

  1. jQuery - a library built tot get around the pain points of early JS
  2. CDN - content delivery network
  3. Minified - A file that can still interpret correctly, but has none of the bits helpful to humans. Used to reduce the size of a file.
  4. CSS Selector - a description of how to find an element on the page
  5. Library - provides an abstraction over common developer code to make it easier to read or write.
  6. Framework - enforces some sort of code organization that you must adhere to.

Loading the jQuery library

To use the jQuery library, you'll need to include the following in HTML

<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="path/to/your/jquery.min.js"><\/script>')</script>

Links to the Google hosted CDN for $

  • Note: If you look at the file extension you’ll see the file says jquery.min.js - that min extensions indicates that its a minified version of the jQuery library.
  • jQuery is a large library, and in order to maximize performance (especially on larger code bases), reducing how much space your code takes up is incredibly important.
  • A minified file indicates that it has been abbreviated using one of many different encryption techniques.

First Lines of jQuery

To manipulate HTML code like this:

<h1 class="important-header">Dinosaurs are awesome.</h1>
document.querySelector('h1').innerText = 'I AM A DINOSAUR.'

//translates to

$('h1').text('I AM A DINOSAUR.');

3 things you can do with jQuery:

  1. Selecting elements from the DOM and manipulating them.
  2. Responding to user interaction.
  3. Grab values and user inputs.

jQuery Jigsaw

Getting and Setting Content Values Using jQuery methods:

  • How do you get the text from an element (say a paragraph element)?
$('.elem').text();
  • How do you set the text from an element (say a paragraph element)?
$('.elem').text('Your text here')
  • How do you get the text from an input element?
$('elem').val();
  • How do you set the text from an input element?
$('elem').val(value);
  • How do you add, remove, or toggle classes of HTML elements?
$('elem').addClass('yourClass');

$('elem').removeClass('yourClass');

$('elem').toggleClass('yourClass');
  • How can you tell if an HTML element contains a certain CSS class?
$('elem').hasClass('className');
  • What happens when you select and element using vanilla JavaScript (document.querySelector()) and then try to use a jQuery method for getting the text of that element? Provide examples of this and what errors you see.

It does not correctly select the element. Seems that jQuery methods will only work on jQuery objects.

  • If you have a jQuery selector that returns multiple elements, say $('.link-img'), then do you need to use a for loop to change the elements? Why or why not? What is returned by the selector?

No, all elements falling under these classes will have the same methods run on them simultaneously.

  • Create a demo (in CodePen) getting the text and setting the text of different elements.

    Codepen Demo

  • Where do you go to find the official jQuery docs? On this doc page, there are two parts of the page, each with a black header: one text() and the other text( text ). jQuery API Documentation

  • What is the purpose of these two different sections? I can't find this particular site.

  • Can you find other examples where a page is written/organized in this way?

Notes for Mod 2 Assesments:

  • Might ask clarifying questions, or re-iterate some of the prompt to ensure they’re reading and understanding the question accurately

  • Will articulate their thought process and/or might write some pseudocode before coding a solution

  • Will speak confidently about their approach (even if it might not be the best route!), rather than phrasing every step they want to take as a question (e.g. you don’t want to be saying things like ’So next I’m going to create a for loop…right? 👀 looks at interviewer for confirmation)

  • Can be flexible in their approach and thought process — when the interviewer prompts them to take a different direction, they can switch gears and refactor to follow the new lead

  • Can recover from syntax errors or small typos they may have made - they can be confronted with an error message and identify where they went wrong

Scope

Goals:

  • Describe the differences between var, let, and const
  • Predicyt how varaibles will behave when multiple scopes are involved
  • Understand how the scope chain is initialized and utilized to resolve variables

Vocab:

Scope - the level in which a variable can be accessed.

  • where & when variables are usable/accessible

const

  • can't be reassigned

let

  • can be reassigned

var

  • function scoped

Review from last week:

Interpreter:

Reads and executes code in two phases

  • Creation phase
    • Hoisting of global variables and function declarations
  • Execution phase
    • code does the thing Scopes:
  • Global
    • Basically, recognized everywhere in the file
    • Default scope
    • Functions and vars in the global scope are 'vulnerable' because they can be accessed by everything and potentially mutated (changed)
    • var, let, and const can be globally scoped
var one = "one";
let two = "two";
const three = "three";

showNumbers();

function showNumbers () {
  console.log("In function: ", one, two, three);
  if (one && two && three) {
    console.log("In if block: ", one, two, three);
  }
}
// The three global variables are accessible everywhere
  • Function
    • Vars declared in the function (using var, let, or const) can only be accessed by the other code inside the function
    • You control what's in the function scope, can't be meddled with by anyone or anything else
    • The global scope cannot access this funtion
function readWords() {
  var greeting = "Hello, friend, ";
  let question = "how are you? ";
  const response = "I am fine."

  if (true) {
    console.log('Sentence in the if block: ', greeting, question, response);
  }

  console.log(greeting + question + response);
}

readWords();

console.log(greeting + question + response);
  • Block
    • Scope is relegated to a code block, such as an if statement
    • Vars declared in the block statement (if blocks, for loops, etc) using let or const can only be accessed by other code inside the block
    • Vars declared in the block statements using var will not be scoped within the block (as this is a special feature of let and const). Vars will be declared with var will 'leak out'.
function readWords() {
  var greeting = "Hello, friend, ";
  let question = "how are you? ";
  const response = "I am fine."

  if (true) {
     var greeting = "Sup dawg, ";
     let question = "what's good?";
     const response = "Nm."
     console.log('Sentence in if block: ', greeting, question, response);
  }

  console.log(greeting + question + response);
}

readWords();

Complete the following prompts in your journal:

Describe “scope” in your own words. What are the similarities and differences between var, let, and const?

Scope is the level at which variables are recognized. All are variables, const cannot be changed but let and var can. Var will leak out in a block scope.

Scope Chain

Whenever a variable is used, the JavaScript interpreter traverses the scope chain until it finds an entry for that variable.

Remember that the scope chain is initialized during the “creation phase” of the interpreter running through the code. This is important to note, as the scope chain (e.g. “What is the parent scope for this variable? The grandparent scope?”) is determined by where functions are defined in the code base…. not where functions are invoked.

Every time a variable is initialized, the interpreter will first look in its own scope to see if the label can be found. If it is not found, it will look “up” the scope chain to the parent scope to try to resolve the variable in the parent context.

1  let number = 10;
2
3  function foo () {
4    number = 20;
5    console.log('A', number);  // prints 'A', 20
6  }
7
8  console.log('B', number);  // prints 'B', 10
9  
10  foo();
11
12  console.log('C', number);    // prints 'C', 20

Scope 3

Goals:

  • Describe and speak to lexical scoping in JavaScript
  • Understand and implement closures

CLOSURES ARE A QUESTION THAT OFTEN COMES UP IN INTERVIEWS! KNOW WHAT IT IS!!!

Vocab:

  • lexical scope also known as static scope
  • closure a function that has a reference to its outer lexical environment

Lexical Scope

JavaScript is lexically or statically scoped.

Our conversations around scope and scope chain are directly related to what we call lexical scoping

Code Example: Repl.it - Scope 3 example

  1. 'What does our jQuery function return?' a jQuery object
  2. 'What jQuery methods do we have access to?' addClass(), removeClass(), hasClass(), toggleClass()

Closures

What is a closure? Code Example Repl.it - Closure Example

  • A closure is formed when a function is defined inside of another function.
  • When an inner function has access to its outer function's variables.
  • When an inner function has access to its outer function's variables and can remember their values no matter when or how it's invoked.
  • The outer functions are protected by the closure and can only be manipulated by code defined within that function.

What is it used for?

  • To protect variables from any sort of otuside manipulation.
  • To hide information that isn't necessary and only exposing what is absolutely necessary.

// Before anything can happen, we need a describe block to group related tests together // In this case, the tests within our describe block are all related to the 'Unicorn' class describe('Unicorn', function() {

// Next, an 'it block' contains the context of each specific test it('should add 100 calories after eating', function() {

// 1. "Setup"
// Instantiate an instance of our unicorn
var unicorn = new Unicorn('Susan');

// 2. "Execution"
// Run appropriate functions that execute the behavior indicated by our test title
unicorn.eat();
unicorn.eat();
unicorn.eat();

// 3. "Assertion"
// Make an assertion to verify that after executing certain functions, we end up with what we expect
expect(unicorn.calories).to.equal(300);

}); });

Understanding the keyword this

Learning Goals

  • Understand and scribe what this is in JavaScript
  • Determine what this is referencing in a codebase

Vocab

  • Invoke / Execute -- To run a function. e.g., “I’ve invoked the function here”
  • Declare -- To write a function definition. Usually distinct from function execution
  • Constructor Function -- The function called to create a new instance of an object. Usually contains the code to set up the object

this:

  • refers to the current context (or owner of the code being executed)
    • context is most often determined based on how a function is invoked
  • refers to the object on which the current function is called.
let dog = {
  name: 'Spot',
  doTrick(trickName) {
    return `${this.name} is going to ${trickName}!`;
  }
}
dog.doTrick('speak')

// => 'Spot is going to speak!'

Rules of this:

  • When invoking a fn as a method on an object,this refers to that object
  • When invoking a fn as a method on an instance of a class, this refers to that instance.
  • By default (if either of the first two rules apply), this refers to your global object.
  • Arrow functions fuck this up
    • ES5 function declarations: this is determined upon invocation
    • ES6 arrow functions: this is determined upon declaration/creation(meaning wherever it is written)

WAI ARIA (the Accessible Rich Internet Applications suite of web standards)

Vocab

  • Accessibility Broadly, creating an experience that is available to anyone and everyone
  • ARIA Accessible Rich Internet Applications
  • Role The function an element serves on the page
  • State The state of an element on a page (e.g., expanded, disabled)
  • Property Additional information about an element or other elements its related to

Learning Goals

By the end of this lesson, you will know/be able to:

  • Speak to why website accessibility is important
  • Implement Semantic HTML to make websites more accessible
  • Implement ARIA to make websites more accessible
  • Learn basic VoiceOver screen reader commands to test accessibility

Accessibility

Accessibility in Web development means enabling as many people as possible to use Web sites, even when those people’s abilities are limited in some way.

Most production websites are not very accessible. This is a great way to set yourself apart from other candidates in the job hunt and add value to teams early.

While you watch, think about these questions:

  1. What has changed about web accessibility in recent years? The screen readers have improved and semantic information has made it so that readers are guided to the necessary pieces of information.

  2. What is the accessibility tree?

This is basically what the browser actually presents to the screen reader. The browser takes the DOM tree and modifies it into a form that is useful to assistive technology. We refer to this modified tree as the Accessibility Tree.

  1. How can developers make webpages more accessible?

Week 2 Review:

Review questions for tomorrow:

What is a prototype and what does it contain? Why might someone say everything is an object in JavaScript? Why is a prototype useful? defines a place to store any shared methods for our objects Talk about prototype chain?

Data Types:

Primitives:

immutable, not objects, no methods
  • boolean
  • undefined
  • numbers
  • null
  • string
  • objects
  • array
  • functions

Complex:

mutable, objects, have methods

  • objects
  • arrays
  • functions

plain english version : a prototype is a framework for creating copies of a thing. It will have some parts built out to set a standard but have room for portions of the prototype to be changed.


prototype - a property on a function that points to an object. Contains any shared methods for how that object should behave.

let quack = new Function('console.log("quack")');

quack;
ƒ anonymous(
) {

console.log("quack")
}
quack();
quack

prototype chain -

prototype inheritance - any object can inherit methods from the prototype of another object

The same object methods apply to all these primitive data types because under the hood, the array or string prototype contructors are calling an object prototype constructor.

Array -> prototype (array methods) -> prototype (object methods)

let letters = ['a', 'b', 'c'];
let str = 'Hello'
letters.push('d');

let animals = { 
  duck: 'quack',
  cow: 'moo',
  sheep: 'baa'
};

Object.keys(animals);
Object.values(animals);
Object.keys(letters);
Object.values(letters);
Object.values(str);
Object.keys(str);

let letters = ['a', 'b', 'c'];
console.log('First Proto: ', letters.__proto__)
console.log('Second Proto: ', letters.__proto__.__proto__)
console.log('Third Proto: ', letters.__proto__.__proto__.__proto__
//prototypes only go two layers deep in this case

// First Proto:  []
// Second Proto:  {}
// Third Proto:  null

Whiteboarding & Psuedocoding

Goals:

  • Understand the realtionshipbetween problem-solving & programming, how we will utilize these skills in our careers

Problem Solving Strategies

UPS process for Problem Solving:

  1. UNDERSTAND - read the problem and verify your understanding of what's being asked/what needs to be solved
  2. PLAN - pick a purposeful problem-solving strategy
  3. SOLVE - implement your plan to deliver a solution

Whiteboarding

Why Whiteboard?

  1. Helps you approach solving a problem
  2. Demonstrates you rability to think about and discuss a problem at a high level
class Elevator {
  constructor() {
    this.currentFloor = 0;
  }
  requestFloor(pickUp, dropOff){
    move(pickUp)
  //move the elevator to that particular dropoff floor
  while (pickUp < currentFloor) 
  
  }
}

Psueudocoding

An intermediary language between English and JS that allows you to write step-by-step directions for creating a piece of functionality Benefits:

  1. PROVIDES A SAFETY NET - Something to look back on and refer to if you lose your train of thought
  2. ALLOWS OTHERS TO INTERVENE - others can identify and correct any misunderstandings earlier
  3. DEMONSTRATES YOUR LOGIC - this might be enough for someone to trust in your skills
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment