Domanda di colloquio di Contentful

Questions about closures, promises and scoping in JavaScript.

Risposta di colloquio

Anonimo

22 ott 2017

While there is no concrete question in here, a brief explanation about these concepts in JavaScript context: 1. Closures: a closure is a function that has access to the scope of the call stack at the time of its definition (thus it is mathematically "closed" over its arguments, hence the name). What that means is the function can call, and "has knowledge" of all variables that were in scope when the function was defined, whether those variables have since then gone out of scope or not. In JS this is usually achieved by a nested function, where the inner function, when called, can call/modify the outer function's fields/variables since those were in scope when the inner function was DEFINED. 2. Promises are a programming construct that ensures that an async process will receive as input, a parameter of a specific type. 3. JavaScript, unlike many other languages, employes a function-based scope, NOT lexical scope. That is, all functions/variables defined within a certain function are ALL in scope for that function. That includes fields/variables/functions that are added to the function in a later stage (i.e. "monkey patching" the function). Lexical scoping functions have their scope limited to what is between a function's start definition and end definition, the "lexicon scope" (i.e. lexical) of the function. This is possible due to JavaScript's hoisting mechanism and what allows it to have closures (see earlier).