1. Fundamentals - Aimanizales/Javascript_learning GitHub Wiki

Variables

var

  • Globally scoped or function scoped.
  • Can be re-declared.
  • Hoisted¹ to the top of their scope and initialized = undefined.

let

  • Block-scoped² (only available for use within that block. eg: if/else, function, object...)
  • Can be updated but no re-declared (unless it's declared inside a block).
  • Hoisted to the top but not initialized like var.

const

  • Block-scoped like let.
  • Cannot be updated nor re-declared.
  • Must be initialized at the time of declaration.
  • Objects initialized with const cannot be updated...
  • ...but its properties can be updated.
  • Hoisted to the top without value (like let).

https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/


Scope

The current context of execution.

  • The context where values and expressions are "visible" or can be referenced.

  • Can be layered in a hierarchy (child scopes have access to parent scopes, but not vice versa).

  • There are two types: global and local.

    • Global: variables declared outside of a block (function that serves as a closure).
    • Local: variables declared inside of a block.

https://developer.mozilla.org/en-US/docs/Glossary/Scope

https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript


Hoisting

It's a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

How it works?

  1. Execute a JS code.
  2. The JavaScript engine creates a Global Execution Context (GEC) in two phases:
  • Phase 1 (creation):
    • JS engine moves variable and function declarations to the top of your code (hoisting).
    • JS engine places the function(s) declaration(s) in the heap memory.
  • Phase 2: The code is executed.

Function hoisting JavaScript engine also hoists the function declarations.

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting https://www.javascripttutorial.net/javascript-hoisting/


Footnotes

(1) Block: a chunk of code bounded by {}

⚠️ **GitHub.com Fallback** ⚠️