Javascript Flashcards

1
Q

What is Node.js

A

Server-side JavaScript framework allowing programmers to run JavaScript from their terminals

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

What is ECMAScript

A

Standardized specification for JavaScript, currently on ES6 (ES2015)

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

Explain the difference between an expression and statement

A

Expressions return a value and need a semicolon. Statements are any line of code and generally don’t require semicolons

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

Two looping keywords

A

continue - skips the current iteration

break - exits the loop

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

What’s the difference between for loops and forEach

A

You can’t exit early from a forEach loop. for loops are less descriptive but have different forms

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

Explain a for..in loop

A

for (key in object) - iterates through enumerable properties of an object (key and values for example). When used with an array/string, the keys are numerical indexes.

Note: not recommended when sequence matters as iteration is in arbitrary order

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

Explain a for..of loop

A

Utilizes Symbol.iterator.next() from ES6 with a nice wrapper for (variable of iterable) - works for iterable things like Array/Strings but will not work on Objects.

Of note, we can use it with NodeLists (which normally don’t have access to Array iteration methods like foreach)

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

How do switch statements differ in JS

A

Same setup as Ruby but we need to include a ‘break’ otherwise it’ll keep passing through cases

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

Explain what a callback function is

A

A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed

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

How does prototype inheritance work in Javascript?

A

Each object has an internal property called prototype, which links to another object. The prototype object has a prototype object of its own, and so on - this is referred to as the prototype chain.

If you follow an object’s prototype chain, you will eventually reach the core Object prototype whose prototype is null, signalling the end of the chain. When you request a property which the object does not contain, JavaScript will look down the prototype chain until it either finds the requested property, or until it reaches the end of the chain.

This behaviour is what allows us to create “classes”, and implement inheritance.

An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object.

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

Explain what Arrays are in JavaScript

A

An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions

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

What is THIS keyword in JavaScript

A

In JavaScript this always refers to the ‘owner’ of the function we’re executing, or rather, to the object that a function is a method of

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

What is closure in Javascript

A

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. In JavaScript, closures are created every time a function is created, at function creation time.

When the outer function exits, a reference to the inner function is returned so the inner function can be called

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

The closure has access to variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in global namespace

Use cases:

  • DATA PRIVACY: data in parent function only available in parent function unless we define “privileged methods” to allow access (this would be the child function returned from the parent function, which has access to that data)
  • STATEFUL FUNCTIONS: return values can be influenced by the internal state (recall those functions from Foundations that only run sometimes)
  • PARTIAL APPLICATION/CURRYING
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is transpiling

A

A process of transforming and compiling to convert newer code into older code equivalents

Typically you insert the transpiler into your build process, similar to your code linter or your minifier. There are quite a few great transpilers for you to choose from:

Babel: Transpiles ES6+ into ES5
Traceur: Transpiles ES6, ES7, and beyond into ES5

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

Differences between ES5 and ES6

A
  • arrow functions and string interpolation
  • the const keyword (can mutate, but cannot reassign)
  • block-scoped variables: the new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does.
  • the new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does.
  • class definition and inheritance: The new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does.
  • for-of operator:The for…of statement creates a loop iterating over iterable objects.
  • spread operator: for objects merging
  • promises: promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.
  • modules “importing” and “exporting”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Equality in JS (== vs ===)

A
  • Strict comparison (e.g., ===) checks for value equality without allowing coercion
  • Abstract comparison (e.g., ==) checks for value equality with coercion allowed (implicit type conversion)
  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===
  • If either value in a comparison could be of these specific values (0, “”, or [] – empty array), avoid == and use ===.
17
Q

What kind of scope do variables have?

A

Scope of variables depends on where they sit in nested functions. Each function creates a new scope that can only be seen by functions nested further within.

18
Q

What is hoisting?

A

Variable assignments are not hoisted to the top of the current scope ` let text = 1’

Variable declarations however are hoisted let text

Variable declarations in a function hoisted to the top of the function.

Prevented by creating a local variable set equal to a named function
const baz = function foo(){return x = 1}
19
Q

Function to raise a num to power (of 3 for example)

A

Math.pow(num, 3);

20
Q

What is the difference between .unshift() and .shift()

A

.unshift() adds a value to be beginning of an array and returns new length

.shift() removes the first element and returns it

21
Q

How would you check if a number is an integer

A

See if there is a remainder when dividing by 1

function isInt(num) {
  return num % 1 === 0;
}

console. log(isInt(4)); // true
console. log(isInt(12.2)); // false
console. log(isInt(0.3)); // false

22
Q

What will the following code output?

(function() {
  var a = b = 5;
})();

console.log(b);

A
  1. Even thought it was declared within a function, var a = b and b = 5 but b wasn’t declared anywhere in the function so it’s set equal to 5 in the global scope.
23
Q

Use a closure to create a function for multiply(5)(6);

A
function multiply(a) {
  return function(b) {
    return a * b;
  }
}
24
Q

What does “use strict” do?

A

At the top of a JS program of top of a function it shows an error if a global variable is created by mistake.

25
Q
Compare, which might we prefer and why?
save()
  .then(handleSuccess)
  .catch(handleError)
;
and
save().then(
  handleSuccess,
  handleError
);
A

We would prefer the first because it would catch an error from the .save() and .handleSuccess() functions. In the second example, an error in .save() would be caught but an error from handleSuccess() would be swallowed as there’s nothing there to catch the rejection

26
Q

Explain the time complexity of accessing a value in an array. Does it matter if we know the index or not?

A

Known index: O(1) constant because we’re only grabbing the one, not continuing to search through the array. Indices are like addresses to these elements in memory. Editing that element at that address is also O(1).

Unknown: Using something like arr.indexOf(‘C’) we get O(n) Linear because in the worst case we’d have to traverse the entire length of the array to find out if the element exists.

27
Q

Explain the time complexity of adding or removing an element at the beginning and end of an array

A

.push() and .pop() are O(1) Constant because it’s simply adding or removing to the end of the array. That’s one index that’s being affected

.unshift() adding or .shift() removing from the front of an array is O(n) because every other element in the array will have a new index as a result of these operations.

.splice() would depend on where in the array we’re splicing from however in the worst case it would be from the start resulting in O(n) time.

28
Q

List some common array methods that have O(n) time complexity

A

Array.filter(), Array.map(), Array.find(), Array.findIndex(), Array.reduce(), Array.forEach().

These all go through the array so it’s O(n).

Array.concat() is actually O(n + m) where n is the original and m is the second array. We’re creating a new array and to do so we have to go through the length of both arrays which might not be equal

29
Q

Compare an Array and Set.

A

Searching in an Array is linear O(n), with some mixed complexities for adding and deleting while methods used in Sets to search, delete and insert items are O(1) so the size of the data has virtually no bearing on run-time.

Arrays are indexed meaning the value is ordered by the index. Sets are a keyed collection, ordering data using keys. They’re iterable in the order of insertion and cannot contain any duplicate data

30
Q

What does use strict at the top of our code accomplish?

A

Voluntarily enforce stricter parsing and error handling. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions
It will throw a runtime error if we try to use undeclared variables which would stop us from accidentally creating global variables

31
Q

What is the browser event loop?

A

Checks the event queue and processes pending events.. If an event happens in the background (script onload event) while the browser is busy (processing an onclick), the event gets appended to the queue. When the onclick is complete, the queue is checked and the event is then handled (the onload script)

32
Q

How can we test if something is NaN?

A

Semi-reliable way is built in isNaN() or in ES6 Number.isNaN().

NaN is typeof ‘number’ and NaN === NaN is false so we’d run into issues trying to test that way.

33
Q

How can we test if something is an integer?

A

ES6 we’d use Number.isInteger().

Prior we’d use
function isInteger(x) { return (x ^ 0) === x; }
or
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

34
Q

How would we clone an object?

A
let obj = {a: 1 ,b: 2}
let objclone = Object.assign({},obj);

NOTE that this will only be a shallow clone!