JavaScript Flashcards

1
Q

how do you write an immediately invoked function?

A
  • wrap in parenthesis

(function someFunc() {
.. do some stuff ..
})();

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

what is the prototype in javascript?

A
  • a prototype in javascript is a property on a function or object that points to an object.
  • allows us to share methods across all instances of a function
  • built in methods live in the prototype: Array and Object for instance
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what does creating an object with the “new” keyword do?

A
  • creates an instance of an object that has a constructor function.
  • the prototype of the new object is set the same as the prototype of the constructing function
  • ‘this’ variable is made to point to the newly created object.

const mochi = Animal(‘Mochi’, 13);

function Animal(name, age) {
  let animal = Object.create(Animal.prototype);
  animal.name = name;
  animal.age = age;
  return animal;
}

const rocko = new Animal(‘Rocko’, 9);

function Animal(name, age) {
  // let this= Object.create(Animal.prototype); // 'new' keyword will do this for you automatically
  this.name = name;
  this.age = age;
  // return this;  // 'new' keyword will do this for you automatically
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  • what are closures and what are they used for?
  • can you name 2 common uses for closures?
  • write a function with using closures and private variables
A
  • a closure is an inner function that references variables in the outer scope from its inner scope even after the outer function has returned.

the closure prevents the outer scope from accessing anything inside the inner scope.

  • Used For:
      • object data privacy
      • event handlers
      • callback functions
      • partial applications(?)
      • currying
      • other functional programming patterns
const counterFunc = function someFunc() {
  var counter = 0;
  return {
    increment() {
      return ++counter;
    }
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is the “lexical environment”?

A
  • a data structure that holds the IDENTIFIER (variables/functions) to VARIABLE (reference to object or primitive value) mapping
  • also holds a reference to the outer (PARENT) lexical environment
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what is the lexical scope?

A
  • defines the scope of a variable by where the variable is declared in the source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

how do you create a private variable in JavaScript?

A
function secretVariable() {
  var private = 'private keyword';
  return function() {
    return private;
  }
}

var getPrivateVariable = secretVariable();

console.log(getPrivateVariable());

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