Review-Of-Previous-Concepts
Review
Review of Concepts
Running JS Locally Concepts
Match the commands
ls,cd,pwdto their descriptionslslists contents of current directorycdchanges current directorycd ..takes you up one levelcdalone takes you back home
pwdreturns current directory
Given a folder structure diagram, a list of 'cd (path)' commands and target files, match the paths to the target files.
Use VSCode to create a folder. Within the folder create a .js file containing
console.log('hello new world');and save it.Use node to execute a JavaScript file in the terminal
Plain Old JS Object Lesson Concepts
Label variables as either Primitive vs. Reference
primitives: strings, booleans, numbers, null and undefined
primitives are immutable
refereces: objects (including arrays)
references are mutable
Identify when to use
.vs[]when accessing values of an objectdot syntax
object.keyeasier to read
easier to write
cannot use variables as keys
keys cannot begin with a number
bracket notation
object["key]allows variables as keys
strings that start with numbers can be use as keys
Write an object literal with a variable key using interpolation
put it in brackets to access the value of the variable, rather than just make the value that string
let a = "b"; let obj = {a: "letter_a", [a]: "letter b"}
Use the
obj[key] !== undefinedpattern to check if a given variable that contains a key exists in an objectcan also use
(key in object)syntax interchangeably (returns a boolean)
Utilize Object.keys and Object.values in a function
Object.keys(obj)returns an array of all the keys inobjObject.values(obj)returns an array of the values inobj
Iterate through an object using a
for inlooplet printValues = function(obj) { for (let key in obj) { let value = obj[key]; console.log(value); } }Define a function that utilizes
...restsyntax to accept an arbitrary number of arguments...restsyntax will store all additional arguments in an arrayarray will be empty if there are no additional arguments
let myFunction = function(str, ...strs) { console.log("The first string is " + str); console.log("The rest of the strings are:"); strs.forEach(function(str) { console.log(str); }) }
Use
...spreadsyntax for Object literals and Array literalslet arr1 = ["a","b","c"]; let longer = [...arr1, "d", "e"]; // ["a", "b", "c", "d", "e"] // without spread syntax, this would give you a nested array let withoutRest = [arr1, "d", "e"] // [["a", "b", "c"], "d", "e"]Destructure an array to reference specific elements
```javascript
let array = [35,9];
let [firstEl, secondEl] = array;
console.log(firstEl); // => 35
console.log(secondEl); // => 9
// can also destructure using ... syntax let array = [35,9,14]; let [head, ...tail] = array; console.log(head); // => 35 console.log(tail); // => [9, 14]
Write a function that accepts a array as an argument and returns an object representing the count of each character in the array
Callbacks Lesson Concepts
Given multiple plausible reasons, identify why functions are called "First Class Objects" in JavaScript.
they can be stored in variables, passed as arguments to other functions, and serve as return value for a function
supports same basic operations as other types (strings, bools, numbers)
higher-order functions take functions as arguments or return functions as values
Given a code snippet containing an anonymous callback, a named callback, and multiple
console.logs, predict what will be printedwhat is this referring to?
Write a function that takes in a value and two callbacks. The function should return the result of the callback that is greater.
// shorter version let greaterCB = function(val, callback1, callback2) { return Math.max(callback1(val), callback2(val)); } // even shorter, cause why not let greaterCB = (val, cb1, cb2) => Math.max(cb1(val), cb2(val));
Write a function, myFilter, that takes in an array and a callback as arguments. The function should mimic the behavior of
Array#filter.Write a function, myEvery, that takes in an array and a callback as arguments. The function should mimic the behavior of
Array#every.
Scope Lesson Concepts
Identify the difference between
const,let, andvardeclarationsconst- cannot reassign variable, scoped to blocklet- can reassign variable, scoped to blockvar- outdated, may or may not be reassigned, scoped to function. can be not just reassigned, but also redeclared!a variable will always evaluate to the value it contains regardless of how it was declared
Explain the difference between
const,let, andvardeclarationsvaris function scoped—so if you declare it anywhere in a function, the declaration (but not assignment) is "hoisted"so it will exist in memory as "undefined" which is bad and unpredictable
varwill also allow you to redeclare a variable, whileletorconstwill raise a syntax error. you shouldn't be able to do that!constwon't let you reassign a variable, but if it points to a mutable object, you will still be able to change the value by mutating the objectblock-scoped variables allow new variables with the same name in new scopes
block-scoped still performs hoisting of all variables within the block, but it doesn't initialize to the value of
undefinedlikevardoes, so it throws a specific reference error if you try to access the value before it has been declaredif you do not use
varorletorconstwhen initializing, it will be declared as global—THIS IS BADif you assign a value without a declaration, it exists in the global scope (so then it would be accessible by all outer scopes, so bad). however, there's no hoisting, so it doesn't exist in the scope until after the line is run
Predict the evaluation of code that utilizes function scope, block scope, lexical scope, and scope chaining
scope of a program means the set of variables that are available for use within the program
global scope is represented by the
windowobject in the browser and theglobalobject in Node.jsglobal variables are available everywhere, and so increase the risk of name collisions
local scope is the set of variables available for use within the function
when we enter a function, we enter a new scope
includes functions arguments, local variables declared inside function, and any variables that were already declared when the function is defined (hmm about that last one)
for blocks (denoted by curly braces
{}, as in conditionals orforloops), variables can be block scopedinner scope does not have access to variables in the outer scope
scope chaining—if a given variable is not found in immediate scope, javascript will search all accessible outer scopes until variable is found
so an inner scope can access outer scope variables
but an outer scope can never access inner scope variables
Define an arrow function
```javascript
let arrowFunction = (param1, param2) => {
let sum = param1 + param2;
return sum;
}
// with 1 param you can remove parens around parameters let arrowFunction = param => { param += 1; return param; }
// if your return statement is one line, you can use implied return let arrowFunction = param => param + 1;
// you don't have to assign to variable, can be anonymous // if you never need to use it again param => param + 1;
```
Given an arrow function, deduce the value of
thiswithout executing the codearrow functions are automatically bound to the context they were declared in
unlike regular function which use the context they are invoked in (unless they have been bound using
Function#bind)if you implement an arrow function as a method in an object the context it will be bound to is NOT the object itself, but the global context
so you can't use an arrow function to define a method directly
```javascript
let obj = {
name: "my object",
unboundFunc: function () {
return this.name;
// this function will be able to be called on different objects
},
boundToGlobal: () => { return this.name; // this function, no matter how you call it, will be called // on the global object, and it cannot be rebound // this is because it was defined using arrow syntax },
}
Define a method that references
thison an object literalwhen we use
thisin a method it refers to the object that the method is invoked onit will let you access other pieces of information from within that object, or even other methods
method style invocation -
object.method(args)(e.g. built in examples likeArray#push, orString#toUpperCase)
context is set every time we invoke a function
function style invocation sets the context to the global object no matter what
being inside an object does not make the context that object! you still have to use method-style invocation
Utilize the built in
Function#bindon a callback to maintain the context of thiswhen we call bind on a function, we get an exotic function back—so the context will always be the same for that new function
``
CALLING SOMETHING IN THE WRONG CONTEXT CAN MESS YOU UP!
could throw an error if it expects this to have some other method or whatever that doesn't exist
you could also overwrite values or assign values to exist in a space where they should not exist
if you call a function as a callback, it will set
thisto be the outer function itself, even if the function you were calling is a method that was called on a particular object
we can use strict mode with "use strict"; this will prevent you from accessing the global object with this in functions, so if you try to call this in the global context and change a value, you will get a type error, and the things you try to access will be undefined
let sayMeow = cat.purrMore; console.log(sayMeow()); // TypeError: this.purr is not a function
// we can use the built in Function.bind to ensure our context, our this, // is the cat object let boundCat = sayMeow.bind(cat);
boundCat(); // prints "meow"
CALLING SOMETHING IN THE WRONG CONTEXT CAN MESS YOU UP!
could throw an error if it expects this to have some other method or whatever that doesn't exist
you could also overwrite values or assign values to exist in a space where they should not exist
if you call a function as a callback, it will set
thisto be the outer function itself, even if the function you were calling is a method that was called on a particular object```javascript
let cat = {
purr: function () {
console.log("meow");
},
purrMore: function () {
this.purr();
},
};
global.setTimeout(cat.purrMore, 5000); // 5 seconds later: TypeError: this.purr is not a function
```
we can use strict mode with
"use strict";this will prevent you from accessing the global object withthisin functions, so if you try to callthisin the global context and change a value, you will get a type error, and the things you try to access will be undefined
POJOs
1. Label variables as either Primitive vs. Reference
Javascript considers most data types to be 'primitive', these data types are immutable, and are passed by value. The more complex data types: Array and Object are mutable, are considered 'reference' data types, and are passed by reference.
Boolean - Primitive
Null - Primitive
Undefined - Primitive
Number - Primitive
String - Primitive
Array - Reference
Object - Reference
Function - Reference
2. Identify when to use . vs [] when accessing values of an object
3. Write an object literal with a variable key using interpolation
4. Use the obj[key] !== undefined pattern to check if a given variable that contains a key exists in an object
5. Utilize Object.keys and Object.values in a function
6. Iterate through an object using a for in loop
7. Define a function that utilizes ...rest syntax to accept an arbitrary number of arguments
8. Use ...spread syntax for Object literals and Array literals
9. Destructure an array to reference specific elements
10. Destructure an object to reference specific values
11. Write a function that accepts a string as an argument and returns an object representing the count of each character in the array
Review of Concepts
1. Identify the difference between const, let, and var declarations
2. Explain the difference between const, let, and var declarations
varis the historical keyword used for variable declaration.vardeclares variables in function scope, or global scope if not inside a function.We consider
varto be deprecated and it is never used in this course.
letis the keyword we use most often for variable declaration.letdeclares variables in block scope.variables declared with
letare re-assignable.
constis a specialized form ofletthat can only be used to initialize a variable.Except when it is declared, you cannot assign to a
constvariable.constscopes variables the same way thatletdoes.
3. Predict the evaluation of code that utilizes function scope, block scope, lexical scope, and scope chaining
Consider this run function, inside which foo and bar have function scope. i and baz are scoped to the block expression.
Notice that referencing baz from outside it's block results in JavaScript throwing a ReferenceError.
Consider this run function, inside of which foo has function scope.
Consider this func1 function and it's nested scopes.
6. Implement a closure and explain how the closure effects scope
4. Define an arrow function
This simple construct will create a function that accepts val as a parameter, and returns val immediately. We do not need to type return val, because this is a single-line function.
Identically, we could write
5. Given an arrow function, deduce the value of this without executing the code
this without executing the codeIf we use a function declaration style function, the this variable is set to the global object (i.e. Object [global] in Node.JS and Window in your browser).
In this example, we use a fat arrow style function. Note that when we declare a funciton like this this becomes
7. Define a method that references this on an object literal
8. Utilize the built in Function#bind on a callback to maintain the context of this
this9. Given a code snippet, identify what this refers to
this refers toLast updated
Was this helpful?