DEV Community

Jasmin Song
Jasmin Song

Posted on • Edited on

Variables

A variable is a container where we can store a value.

let

  • can be reassigned but not redeclared

Image description

  • can declare let with a value when declaring the variable, or declare it and not give it a value.

  • with let arrays: you can update it at any point. let is the var keyword but block-scoped.

const

  • cannot be reassigned or redeclared

Image description

  • cannot declare const with a value and not give it a value. can't say const chicken; because const is supposed to say constant, so you need to know ahead of time what the value is going to be.

  • const array: the values can be updating the values/pushing onto the array. You're still changing the array. you're not updating the reference. pointing to the same array/object in memory. can't change the reference. We are not able to reassign the array itself but we can reassign any of its elements.

var

  • declares variables

  • declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

Image description

  • can declare a var with a value when you declare the variable, or declare it and not give it a value.

  • you can redeclare the variable at any time
    var x = 10; var x = "hi";
    You're not just updating/reassigning x, you are completely redeclaring it. can't do that with let or const.

hoisting

  • a variable can be used before it has been declared

  • when variables are set to undefined. declared before the rest of the code.

  • let and const get hoisted. they are not set to undefined like var.

  • var is scoped to the current execution context. scoped to their enclosing function if they are in a function. if not, they are part of the global scope.

  • let and const are block scoped. var is not block scoped. it is scoped to the current execution context.

  • when you declare var in global scope, it is added to the window object. const and let are not in the window object.

Top comments (0)