Functions Flashcards

1
Q

What does this return?

console.log(square(5));

var square = function(n) { 
  return n * n; 
}
A

TypeError: square is not a function

If you define a function as a variable, the variable name will be hoisted but you cannot access until JS execution encounters its definition.

If this was not assigned to a variable, would not return an error.

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

What is execution context? Explain 2 types.

A

An execution context is an abstract concept of an environment where the JavaScript code is evaluated and executed.

  • Global execution context: The code that is not inside any function is in the global execution context. It performs two things: it creates a global object which is a window object (in the case of browsers) and sets the value of this to equal to the global object.
  • Functional execution context: Every time a function is invoked, a brand new execution context is created for that function. Each function has its own execution context, but it’s created when the function is invoked or called.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a lexical environment?

A

A structure that holds identifier-variable mapping, where identifier refers to the name of variables/functions, and the variable is the reference to actual object or primitive values.
Every time the JavaScript engine creates an execution context to execute the function or global code, it also creates a new lexical environment to store the variables defined in that function during the execution of that function.

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

How does a function expression differ from a function declaration?

A

Function declarations are hoisted, which means they are moved to the top of their scope by the interpreter. This allows you to call it anywhere in your code. You can only call function expressions linearly. Thus function expressions are more predictable and structured. Assigning them to let and const also provides control is it can be re-assigned or not.

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

What is hoisting?

A

During compile phase, just microseconds before your code is executed, it is scanned for function and variable declarations. All these functions and variable declarations are added to the memory inside a JavaScript data structure called Lexical Environment. So that they can be used even before they are actually declared in the source code. Conceptually, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code

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

What is temporal dead zone?

A

A time span between variable creation and its initialization where they can’t be accessed.

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

What will this output?
let a;
console.log(a);
a = 5;

A

Undefined.
Here during the compile phase, the JavaScript engine encounters the variable a and stores it in the lexical environment, but because it’s a let variable, the engine does not initialize it with any value.* *Would have same result with var because the assignment does not get hoisted, just the variable name.
During the execution, when the engine reaches the line where the variable was declared, it will try to evaluate its binding (value), because the variable has no value associated with it, it will assign it undefined.

Without the declaration of “let a” at the top, the output would be a Reference Error: a is not defined.

console.log(a); 
var a = 5;

This however would not return an error but show undefined (variable name hoisted, but not assignment.)

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

Explain functional programming.

A

FP is based around the concept of “pure functions”, which avoid shared state, mutable data and side-effects. Given the same inputs, a pure function always returns the same output. It does not have side effects

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

What’s the difference between imperative and declarative programming?

A

Imperative programming is concerned with how you do something. It spells out the steps in the most essential way, and is characterized by for and while loops, if and switch statements, and so on. OOP is an example of imperative programming.
Declarative programming is concerned with what to do, and it abstracts away the how by relying on expressions. This often results in more concise code, but at scale, it can become more difficult to debug because it’s that much less transparent. Functional programming is an example of declarative programming.

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

What is a closure?

A

A closure is the combination of a function and the lexical environment (the scope of the function- identifiers it has access to) within which that function was declared. 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.

What makes closures powerful is when a function is returned from another function. When a function is declared in a function, but returned and run outside of where it was declared it will still have access to the scope it was declared in because of closure.

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods (any exposed method defined within the closure scope)

const getSecret = (secret) => {
  return {
    get: () => secret
  };
};
console.log(secret)
// ReferenceError: secret is not defined
const obj = getSecret(1);
const actual = obj.get();
console.log(actual)
//1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is scope and describe the types.

A

Scope determines the accessibility of variables. Scope determines where the identifier, such as a variable or function name, is visible and accessible.
Variables declared within a function have local scope and can only be accessed from within the function.
A global variable has global scope and all scripts and functions on a web page can access it.

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

How do call() and apply() work and what is the difference?

A

They both allow up to set the value of this ourselves.

call() is a method directly invoked onto a function. We first pass into it a single value to set as the value of this; then we pass in any of the receiving function’s arguments one-by-one, separated by commas.

apply() does the same thing but rather than passing arguments one-by-one, separated by commas – apply() takes the function’s arguments in an array.

Example:
const dave = {
  name: 'Dave'
};
function sayHello(message) {
  console.log(`${message}, ${this.name}. You're looking well today.`);
}
Either:
sayHello.call(dave, 'Hello')
or 
sayHello.apply(dave, ['Hello'])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};
const unboundGetX = module.getX; 
const boundGetX = unboundGetX.bind(module); 
const otherGetX = () => module.getX(); 

1) console.log(unboundGetX())
2) console.log(boundGetX())
3) console.log(otherGetX())

Given above, what will these each return?

A
1) The function gets invoked at the global scope. Simply invoking a normal function will set the value of this to the global object
// expected output: undefined
2) Bind makes the module the value of this, allowing it to access x
// expected output: 42
3) This uses an anonymous closure. getX is being used as a method on module, setting this to module.
// expected output: 42
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a wrapper object? Give an example using a string.

A

Whenever you try to access a property of a string str (a primitive data type with no properties), JavaScript coerces the string value to an object, by new String(str). This object is called a wrapper object.

It inherits all string methods, and is used to resolve the property reference. Once the property has been resolved, the wrapper object is discarded.

Example:
var str = 'hello';

this:
var upper = str.toUpperCase();
console.log(upper); // –> HELLO

...basically translates to:
var upper = (new String(str)).toUpperCase().

The same concept applies to numbers and booleans

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

What is a decorator?

A

Decorator is a wrapper around a function that alters its behavior. The main job is still carried out by the function.
Decorators can be seen as “features” or “aspects” that can be added to a function. We can add one or add many. And all this without changing its code!

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

What is recursion?

A

A programming term that means calling a function from itself. Recursive functions can be used to solve tasks in elegant ways.

17
Q

What is a benefit of using the module pattern?

A

It uses closures to create private and public properties of an object, which isn’t provided by JavaScript by default.

When used with an IIFE, it prevents pollution of the global scope (which hinders the chance of variable name collisions) – the IIFE helps prevent access to it’s variables.

let diana = (function () {
  let secretIdentity = 'Diana Prince';
  return {
    introduce: function () {
      console.log(`Hi! I am ${secretIdentity}`);
    }
  };
})();
18
Q

What are the key ingredients to the revealing module pattern?

A

1) An IIFE (wrapper)
2) The module content (variables, methods, objects, etc.)
3) A returned object literal

19
Q

What is functional programming?

A

Functional Programming is a programming paradigm that emphasizes using clean functions to create code. This paradigm tries to avoid reassigning values to variables and tries to avoid code that would create unintended side effects. It keeps the processing within functions.

20
Q

What is a pure function?

A

A function that will always return the same output if given the same input, and which has no side effects.

21
Q

What is a side effect?

A

An effect on your overall program from running a function, that did not come from the return statement of that function.

22
Q

What is an immutable value?

A

Unchanging. Immutable values are ones which, once declared, cannot be changed.

23
Q

What is a high order function?

A
  • returns a function

- receives a function as an argument