Logo

dev-resources.site

for different kinds of informations.

Hoisting with closures example

Published at
8/9/2021
Categories
javascript
closures
snippets
Author
ama
Categories
3 categories in total
javascript
open
closures
open
snippets
open
Author
3 person written this
ama
open
Hoisting with closures example

Try guessing what is the output of the following snippet:

function one() {
  function two() {
    console.log(`closure var1 - ${var1}`);
  }

  three();
  var var1 = 'var1';   
}

one();
Enter fullscreen mode Exit fullscreen mode


It yields hoisting var1 - undefined, because of hoisting of var1 variable (it is allocated in memory with value undefined), but it is not initialised with the value var1 by the time the closure is executed.

But, if we use setTimeout(), by the time the callback closure function is executed var1 will have been initialised and its value is printed:

function one() {
 setTimeout(function() {
  console.log(`closure var1 - ${var1}`);
 }, 0);
  var var1 = 'var1';
}

one();

//output
closure var1 - var1
Enter fullscreen mode Exit fullscreen mode

Shared with ❀️ from Codever. Β  πŸ‘‰ Β  use the copy to mine functionality to add it to your personal snippets collection.

closures Article's
30 articles in total
Favicon
Understanding Closures in PHP: Key Differences and Use Cases
Favicon
JavaScript Closures in Depth: Unlocking the Power of Lexical Scope
Favicon
Understanding Closures in JavaScript
Favicon
Mastering Closures and Decorators in Python: From Basics to Advanced
Favicon
Understanding Closure in JavaScript.
Favicon
Let's Understand JavaScript Closures: A Fundamental Concept
Favicon
Memoization in JavaScript
Favicon
Closures: Performance implications
Favicon
Closures: Lifting the hood
Favicon
A Practical Introduction to Closures in JavaScript
Favicon
Unlocking New Possibilities: Rust Compiler Backend Brings Closures to the .NET Universe!
Favicon
πŸ“¦πŸ”“Closures in JavaScript visualized
Favicon
useClosure() {work, backwards in returnValuesAsInput (backwards, work)}
Favicon
Mastering Closures in JavaScript: A Comprehensive Guide
Favicon
# "JavaScript Closures: Demystified."
Favicon
Closures - JavaScript
Favicon
Exploring Advanced JavaScript Techniques: Closures, Prototypes, and Hoisting
Favicon
Unlocking JavaScript Magic: A Beginner's Guide to Closures
Favicon
JavaScript Closures: Understanding the Power of Functions
Favicon
Closures in javascript
Favicon
JavaScript Closure
Favicon
Groovy Gotchas - Loops, Closures, Scope, and Jenkins DSLs
Favicon
Understanding closures in JavaScript
Favicon
Javascript Currying and partials
Favicon
The ultimate explanation of closures
Favicon
Understanding Closures in JavaScript
Favicon
Closures and Memoization
Favicon
A Simple Explanation of JavaScript "Closures"
Favicon
Hoisting with closures example
Favicon
Closures in JavaScript

Featured ones: