stuff Flashcards

1
Q

How would you access the first element of an array?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you declare an array?

A

(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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you declare an object?

A

(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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between == vs ===?

A

== 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What kinds of scope are available in JavaScript?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Difference between global and local scope

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Where is global scope in the browser?

A

window object
—————————————————————
Variables that are globally scoped are stored in the global object. For a browser, that’s the window object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you create an instance of an object?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is prototype property for?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you implement: module pattern?

A

(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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you implement: namespace?

A

{

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you implement: inheritance?

A

** 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you implement: closure?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you implement: private scoped variables (a kind of closure)?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Describe how exception handling works in JavaScript

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a Promise? Why are Promises used?

A

Built in JavaScript API for handling async calls, avoid callback hell, more declarative/readable than callbacks
—————————————————————
a promise represents the eventual completion or failure of an asynchronous operation and it’s resulting value. lets asynchronous methods return values like synchronous ones

17
Q

What are common standard methods you can use on a Promise?

A

.then(), .catch(), .finally(), .resolve(), .reject(), .all(), .any()
—————————————————————
all, allSettled, any, catch, finally, race, reject, resolve, then

resolve, reject, then might be the most common …

.then() - this grabs the result that might be available and allows you to specificy callbacks to use that result
.catch() - this will catch any error between the .then()’s which come before it that the promise may have, or what reject gives you
.finally() - executs the specified callback no no matter if the promise is rejected or fulfilled

.all (promise.all()) <-- takes all the val

—————————————————————

Promise. any() fulfills with the first promise to fulfill, even if a promise rejects first. This is in contrast to Promise. race() , which fulfills or rejects with the first promise to settle.

Promise.any() takes an iterable of Promise objects. It returns a single promise that fulfills as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

Promise.then() The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

The Promise.resolve() method “resolves” a given value to a Promise. If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected) (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)). This means that you have to provide an onRejected function even if you want to fall back to an undefined result value - for example obj.catch(() => {}). - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

The Promise.allSettled() method returns a promise that fulfills after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

The finally() method of a Promise schedules a function, the callback function, to be called when the promise is settled. Like then() and catch(), it immediately returns an equivalent Promise object, allowing you to chain calls to another promise method, an operation called composition. /n This lets you avoid duplicating code in both the promise’s then() and catch() handlers. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

18
Q

What is async/await? Why is it better than Promise.then()?

A

Newer way, syntactic sugar, Await expressions make promise-returning async functions behave as if they’re synchronous, suspends code execution until promise is resolved or rejected
—————————————————————
Syntactical sugar for promises that makes asynchronous code look synchronous.

Came out in ES8 (2017) https://gist.github.com/rajaramtt/7df3702a04c644b0b62c9a64f48f3dbf

not better but intends to make code easier to read

—————————————————————
https://www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13511640#overview

this explains that promises are on the job queue, which has a higher priority than the callback queue https://www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13842304#overview

—————————————————————

make it like this

16 function doit() {
15 return new Promise(resolve => {
14 setTimeout(() => {
13 resolve(“resolved”)
12 }, 2000)
11 })
10 }
9
8 async function happy() {
7 console.log(“first one”)
6
5 const sup = await doit()
4 console.log(sup)
3
2 console.log(“last one”)
1 }
17
1 happy()

19
Q

What is the Symbol type? What is it used for?

A

JavaScript primitive type, allows guaranteed unique key on an object
—————————————————————
A symbol is a unique and immutable primitive data type. It’s mostly used as a key/identifier for object properties.

Note that There are 7:

    booleans
    strings
    numbers
    symbol
    undefined
    null
   
    object - this is a non primitive type as it doesn't have the value directly like the others. arrays, and function are objects too
20
Q

How do you define a variable’s type?

A

let blah: string;, trust type inference if assigning a value immediately, built-in types can be assigned or custom types can be declared as interfaces or types, type unions, nullable with ?, etc.
—————————————————————
stick a colon right after the variable name and then the type right after the colon

21
Q

Difference between const, var, let?

A

var is older, var is hoisted, let allows reassignment like var but is block-scoped, const does not allow reassignment but has gotchas for some data types (obj, arr)
—————————————————————

const
- has to be assigned ( = “the a variable”) when its declared (const a), if you don’t assign it you’ll get a “syntax error”
- does not allow reassignment. if you try it, you’ll get a “syntax error”
- note that primatives are passed by value, and objects are passed by reference or passed by “copy of a reference” (or “sharing”) ( https://stackoverflow.com/a/38533677 ) . so if you const an array(a type of obj) you are assigning a copy of the a refernce to that object to the variable, not the actual object itself though

about those syntax errors? evaluated before the code is run, which means the un assigned const can be at the bottom of the code and all the console.logs or functions that are run before that item in the code just never happen because the syntax is evaulated first

let
- allows reassignment

var
- allows reassignment
- get hoisted
(Hoisting is the default behavior of moving all declarations to the top of the scope before code execution. Var defined variables are partially hoisted and function declarations are fully hosted to the top of their respective environments during compilation phase. )

22
Q

What is the => (lambda, arrow function) operator?

A

Binds “this” to execution context, newer way to declare functions, simpler syntax for anonymous functions, syntactic sugar
—————————————————————
Normal functions have runtime binding. They bind the “this” keyword to the object that calls the function. Arrow functions do not have their own binding and the “this” keyword retains the value from its encosing lexical environment - that is, where the function is defined, as opposed to where it’s called - instead.

23
Q

Difference between => and function()?

A

All arrow functions are anonymous, “this” keyword of execution context is bound in arrow functions (no need to explicitly .bind())

—————————————————————

arrow functions aren’t hoisted and retain the value of ‘this’ from their lexical environment or where it’s written instead of where its called

also some othe rwords on it https://www.reddit.com/r/learnjavascript/comments/w36r78/can_somebody_explain_to_me_the_point_of_arrow/

what is hoisting? it’s not where javascript moves ur code, it doesn’t do that. it’s where javascript sets up memory space for your functions and variables during the ‘creation phase’

it does this so that when the code begins to execute line by line, it can access them (those functions and variables). it gives the variables a temporary value of “undefined”, and then in the “execution phase” it gives them the value of whatever is set in our code

all variables in javascript are initially set to ‘undefined’ (not the string, the keyword)

arrow functions aren’t hoisted so you can’t call them before declaring them, unlike what you can do with function declaractions

24
Q
  • How do you define a class in TypeScript?
A

Class keyword, constructor, super, properties, methods, getters/setters, public/private scopes

class Calculator {

private a: number;

private b: number;

constructor(a: number = 0, b: number = 0) { this.a = a; this.b = b}

get a { return this.a }

set b { this.b = b }

add() { return this.a + this.b }

}
—————————————————————
using the class keyword, just like ES6. inside you have fields, aconstructor, and your mothods/functions

more information here: https://www.tutorialspoint.com/typescript/typescript_classes.htm

https://www.typescriptlang.org/docs/handbook/2/classes.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

25
Q
  • How do you implement inheritance in TypeScript?
A

Extends keyword, class syntax similar to other OOP languages

class AdvancedCalculator extends Calculator {

constructor(a, b) {

    super(a, b);

}

subtract() { return this.a – this.b }

}
—————————————————————
using the extends keyword. can also use the super keyword to access non-private members and constructors from the immediate parent class

26
Q

What are interfaces? How are interfaces used?

A

Define shape of object/data structure, duck typing, structural subtyping, enables type checking/type safety, extendable type
—————————————————————
interfaces are used to define the structure of an object. when you write it, it looks just like an object except you’re using a semicolin (instead of a comma) to separate the key: pair values and you use the word “interface Variable { “ instead of “const variable = {“

Use it like a type annotation. colon then the interface

https://youtu.be/P17bFRuefjA?t=207

27
Q

When TypeScript is compiled, what do interfaces turn into?

A

Nothing, they get compiled away
—————————————————————-
It’s gone. The typescript gets converted to javascript.

the type definition file is going to tell the typescript compiler all the different functions that are available inside the javascript library what type of arguments they take and what type of value they return

28
Q

What are the benefits of using TypeScript over JavaScript?

A

What were normally runtime errors may be caught at compile time, prevents many bugs, type safety, enables intellisense features, reduces need for explicit JSDoc/docs/code comments, speeds up development
—————————————————————

types are used by the typescript compiler to analyze our code for errors, which is good so you catch issues during development instead of after you run ur code

and ytpes allow other ppl who are looking at your code to better understand the values moving around in your codebase

29
Q
  • How do you use JavaScript code with TypeScript? or

How do you add JavaScript dependencies to a TypeScript project?

A

Declare type definitions for the JavaScript library, @types/ npm namespace

https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html

example:
npm install -S @types/lodash

https://www.techiediaries.com/use-external-javascript-libraries-typescript-projects/

example:
npm install @types/node –save

if the type doesn’t exist, create declaration file (name.d.ts)
https://medium.com/@steveruiz/using-a-javascript-library-without-type-declarations-in-a-typescript-project-3643490015f3

in it write

declare module “my-untyped-module”