2667. Create Hello World Function
Context
Section titled “Context”This question tests the concept of Closures in JavaScript
Definition of Closure
Section titled “Definition of Closure”To understand closures, it’s important to first understand lexical scoping. In JavaScript, variables declared within a function are only accessible within that function, and any nested functions within it. However, a nested function can “remember” the variables from the outer function even after the outer function has returned. This is because the inner function has access to the variables in the outer function’s lexical scope.
Example
Section titled “Example”function outer() { const name = "Bob";
function inner() { console.log(`Hello, ${name}!`); }
return inner;}
const greeting = outer();greeting(); // logs "Hello, Bob!"In this example, outer defines a variable name and a function inner . inner is defined within outer, so it has access to name in outer’s lexical environment. When outer is called and returns inner, a closure is created that retains access to name. This means that even though outer has finished running and name is technically out of scope, inner can still access it and log a greeting with it.
2nd Example
Section titled “2nd Example”function counter() { let count = 0;
return function() { count++; console.log(count); }}
const increment = counter();increment(); // logs 1increment(); // logs 2increment(); // logs 3In this example, counter returns a function that increments and logs a variable count each time it’s called.
count is defined within counter, so it’s not accessible outside of it.
However, when counter returns the inner function, a closure is created that retains access to count.
This means that each time increment is called, it can still access and modify count.
Solution
Section titled “Solution”function createHelloWorld() { const greeting = "Hello World";
return function() { return greeting; };}