stuff Flashcards
How would you access the first element of an array?
Index 0, bracket notation, Array.at()
—————————————————————
const coolarray = [‘1’, ‘2’, ‘3’]
// bracket notation
console.log(coolarray[0])
// using the at method
// according to MDN this is experimental and may change in the future
// doesn’t work in IE
console.log(coolarray.at(1))
// using the shift method
// this mutates the array
console.log(coolarray.shift())
// destructuring
const anotherarray = [‘1’,’2’,’3’]
const [billy] = anotherarray
console.log(billy)
const sample = [[‘1’, ‘2,’, ‘3’], [‘4’, ‘5,’, ‘6’]]
let [[a], [b]] = sample;
console.log(a, b); // “1” “4”
—————————————————————
This covers destructuring array
https://www.youtube.com/watch?v=giNjEgYTd9E
How do you declare an array?
(literal) const blah = [], (constructor) new Array(), Array.from()
—————————————————————
// using the new keywrod
const array1 = new Array(“1”, “2”)
console.log(array1)
// array literal
const array2 = [true, false]
console.log(array2)
// using the from method, createds a shallow copy array
// doesn’t work in IE
const array3 = Array.from(array2)
console.log(array3)
// you can spread one array into another one
const sup = [‘1’, ‘2’]
const sup2 = […sup]
console.log(sup2)
—————————————————————
Not sure if this counts as declaring an array but … you can create an array from objects like this
// You can create an array from an objects values using Object.values
const obj1 = {
name: “brad”,
age: “12”,
}
console.log(Object.values(obj1))
» [ ‘brad’, ‘12’ ]
// Or you could do it from an object’s keys using Object.keys
console.log(Object.keys(obj1))
» [‘name’, ‘age’]
How do you declare an object?
(literal) const blah = {}, (constructor) new Object(), Object.create()
—————————————————————
Actually there’s 6 ways:
Object Literal
Object Constructor
Constructor Function
Object.create() Method
Object.assign() Method
ES6 Classes
https://attacomsian.com/blog/javascript-create-object
What is the difference between == vs ===?
== not as strict, == performs type coercion, === strictly checks type, generally prefer ===
—————————————————————
== abstract equality compares value and does type coercion
=== strict equality compares value and doesn’t do type coercion
What kinds of scope are available in JavaScript?
Global, local, function, block-level
—————————————————————
//global ->
accessible everywhere, in every function
//module ->
module pattern, es6 modules (import/export)
//function or “local scope” ->
“Everytime we create a function, we create a new execution context which has its own variable environment”
accessible within the function where it was defined
//block - let and const
if you declare a variable with one of this in the global scope, it does not become a property of the global object, but if you use var it does
note: scope is function-based and describes what’s in the variable environment while context is object-based and says what the value of this is
—————————————————————
Variables defined in global scope are available everywhere in the application.
In a module, a variable declared outside any function is hidden and not available to other modules unless it is explicitly exported.
Function scope means that parameters and variables defined in a function are visible everywhere within the function
Variables declared with let and const have block scope. var doesn’t have block scope.
—————————————————————
This covers module pattern and es6 modules pretty well https://www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13859382#overview
Difference between global and local scope
Global shared among functions, global can cause namespace collisions, local not accessible from outside, etc.
—————————————————————
Globally scoped variables are accessable everywhere, in every function, and locally scoped variables are accessable, not globally, but within the function where it was defined.
Where is global scope in the browser?
window object
—————————————————————
Variables that are globally scoped are stored in the global object. For a browser, that’s the window object.
How do you create an instance of an object?
new keyword using class constructor, Object.create()
—————————————————————
You can use the new keyword to initialize an instance of Object:
const fruits = new Object();
You can use the class keyword to define a new class in JavaScript instead of a function constructor, and then use the new keyword to create an instance of it.
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHi() { return `Hi ${this.name} 👋`; } }
const user = new User(‘Atta’, 30);
console.log(user.sayHi()); // Hi Atta 👋
console.log(user.age); // 30
–
The Object.create() method allows us to create a new object, using an existing object as the prototype of the newly created object. This method is especially useful when you want to create a new object from an already existing object.
const Vehicle = {
maker: ‘BMW’,
color: ‘Black’
};
const vehicle = Object.create(Vehicle);
console.log(vehicle.maker); // Tesla
console.log(vehicle.color); // Red
What is prototype property for?
Allows inheritance of methods & properties via prototype chain, __proto__ property gets constructed by walking up the chain, modifying prototype directly is generally bad practice
—————————————————————
Prototypes are the mechanism by which JavaScript objects inherit features from one another. The prototype property is where inhereted members/features are defined.
__proto__ is used as a property on an object that points to the prototype property (which is an object [typeof Object.prototype]) of its parent function constructor. So if I create a new object, it’s __proto__ property will point to Object.prototype.
note that only functions have the prototype property
you can do ‘typeof Object’ to see that this is a function, it’s specifically “the object constructor that creates the object wrapper”. Recall how function constructors are made with the capital letter? Yeah
How do you implement: module pattern?
(function() {})();
—————————————————————
(function() {})();
This is a pattern that was used before modules and classes became a part of the language. People would wrap all of their code in an IIFE (immediately invoked function expression). In this way, their stuff was outside of the global scope by one layer. The layers being as follows:
// global -> // module -> // function or "local scope" -> // block - let and const
There’s also something called the ‘revealing module pattern’ where you return stuff out of your IIFE for use elsewhere. For example in the code below I return an object for use:
const myName = (function() { function logFn(){ console.log("hello"); } return {logStuff: logFn} })() Now I can use stuff like myName.name in other places
How do you implement: namespace?
{
namespace1: {}, namespace2: {}
}
—————————————————————
You can do this with an object literal
lets say you have an object named animal and have properties cat and age on it. With that, both cat and age are namespaced under animal so that they’re scoped instead of being global and having the ability to conflict with other libraries
You can do it by declaring a variable that’s equal to an iffy which returns some stuff you want accessible with the name
var myApplication = (function () {
function(){
//…
},
return{
//…
}
})();
https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch13s15.html
you can use object literal notation
var myApplication = {
// As we've seen, we can easily define functionality for // this object literal.. getInfo:function(){ //... }, // but we can also populate it to support // further object namespaces containing anything // anything we wish: models : {}, views : { pages : {} }, collections : {} };
How do you implement: inheritance?
** answers vary widely, please have a dev3 chime in what they are looking for
—————————————————————
You can do this with ES6 classes, using the ‘extends’ keyword, or the pre-ES6 way with .prototypes.
With classes, you create a class, then create another one that ‘extends’ that one, then you use the new keyword on that extended class. The new item you created will have the stuff from the original class and the extended one basically.
With pre-ES6 you create a constructor function, then add new stuff to that using the ‘prototype’ word (e.g. thing.prototype.ability = function(){}) , then when you use the ‘new’ keyword your new item will have the stuff rom that original constructor function and all your prototype assignments.
–
ES6 way with classes:
class Player {
constructor(name, type) {
console.log(this, “From player”)
//console.log(name, This is the name inside the Player class
)
this.name = name;
this.type = type;
}
introduce() { console.log(`Hi my name is ${this.name}, I'm a ${this.type}`) } } class Wizard extends Player { constructor (name, type) { //console.log(name, `This is the name inside of the wizard class`) let othertype = "billy"; let othername = "mark" super(othername, othertype) console.log(this, "From Wizard") } play() { console.log(`Weeee I'm a ${this.name}, of type ${this.type}`) } } const wizard1 = new Wizard('Shelly', 'Healer') const wizard2 = new Wizard('Shawn', 'tank') wizard2.introduce() wizard2.play() wizard1.introduce() wizard1.play()
Pre-es6 way with prototypes:
var Player = function(name, type) { this.name = name; this.type = type; } Player.prototype.introduce = function() { console.log(`Hi I'm ${this.name} of type ${this.type}`) } var wizard1 = new Player("Shelly", "healer"); var wizard2 = new Player("Billy", "tank"); wizard1.play = function() { console.log(`Weeee, I'm a ${this.type}`) } wizard2.play = function() { console.log(`Woop, I'm also a ${this.type}`) } wizard1.introduce() wizard1.play()
How do you implement: closure?
function makeTimes(x) {
return function(y) {
return x * y;
};
}
var fiveTimes = makeTimes(5);
var result = fiveTimes(5); // = 25
—————————————————————
Create a function that returns another function. The outermost function goes onto the call stack, runs and gets popped off. When it runs, it’s returns the inner function, which you can also call and put on the call stack. While that inner function is on the stack, it still “remembers” all of its peers from where its defined inside of the outer function. And it has access to them.
“Functions in javascript form closures. A closure is the combination of a function and the lexical environment within which that fucntin was declared. This environment consists of any local varialbes that were in-scope at the time the closure was created.”
Functions, in javascript, form closures. A closure is the combination of the function and the references to the variables that were lexically in-scope when it was declared. The closure ensures access to the outer functions scope, even after it was removed from the call stack, from the inner function.
A closure
- A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function
- it gives you access to an outer functions scope from an inner function
- a closure is a function haveing access to the parent scop, even after the parent function has closed
- a closure is a feature in javascript where an inner function has access to the outer (enclosing0 functions variables - a scope chain)
How do you implement: private scoped variables (a kind of closure)?
function toggleClosure() {
var x = true; return function() { x = !x; return x; } ————————————————————— Create a function that has variables declared inside of it and also, in that function, return another function that, when run, can still reference the variables declared in its parent
Describe how exception handling works in JavaScript
throw, try/catch
—————————————————————
You use try, catch, throw, and finally
try - lets you test a block of code for errors catch - lets you handle the error throw - lets you create custom errors finally - lets you execute code, after try and catch, regardless of the result