Skip to content

Instantly share code, notes, and snippets.

@flacial
Last active October 5, 2021 12:29
Show Gist options
  • Save flacial/70a991ec355ab18ea4de662a088960e5 to your computer and use it in GitHub Desktop.
Save flacial/70a991ec355ab18ea4de662a088960e5 to your computer and use it in GitHub Desktop.
Let, const, and var in (hopefully) laymans terms

We can begin by knowing what they share in common, storing data. Imagine data as boxes.

Brief definitions for a general idea:

var: used to store a box that will probably change later (mutable).
let: similar to var but a bit different (mutable).
const: used to store a box that won't change later (immutable).

Block, Function, and Global scopes:

We've to first know what's scope before knowing the difference between them.

scope: the part of the code for which a variable is defined.

Examples:

Global scope: anything outside of a function.
Block scope: anything inside curly brackets {}.
Function scope: anything in a function.

function b() {
  //Function scope
}

For now, you can think of each scope as its own room.

Difference between var and (let and const):

In Global scope: all of them can be accessed from other functions and blocks.

const a = 20
var b = 30

function c() {
   console.log(a, b) // 20, 30
}

In Function scope: var, let, and const can't be accessed from outside of the function.

function d() {
   let a = 10
   var b = 20
   const c = 30
}

console.log(a, b, c) // Error: a, b, and c are not defined

In Block scope: var can be accessed from outside of the block ({}), but let and const cannot, and that's the main difference.

{
   var a = 30
   let b = 2000
}

console.log(a, b) // 30, Error: b is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment