Unit 2, Lesson 1

$\textbf{Variables in Node.JS}$
$\text{Written by:} $
$\text{Dev Singh, Class of 2022}$
$\text{Last Revised: March 2020}$

Unlike languages that you may be used to, such as Python, Node.JS and JavaScript have 3 types of variables: var, let, and const. let and const are more specific types of the generic variable declaration var. Any data type can be stored in any variable, however, they are all slightly different. Let's take a look at these differences.

var

var is the most generic form of variables in JS. It could contain a constant value or one that is changeable. var exists in the function scope (its value is present throughout the function in which it was declared).var is also hoisted to the top of the block, meaning that the variable has been initialized in its scope before its value has been declared. var also adds values to the global object property.

In [1]:
var someVarString = `hello, world!`

let

let was introduced with the ECMAScript 6th edition draft. It is designed to store changing values. Its scope is different from var in that it is only accessible in the block that it was defined. let is not hoisted as “var” is; this means that calling a let-declared variable before it has been assigned a value will result in a ReferenceError. let does not add values to the global object property. Redefining a let as a new variable will result in an error.

In [2]:
let someLetString = 'hello, let world!'

const

const was also introduced in the ECMAScript 6th edition draft. It is designed to store non-changing values. Reassigning the value of a const will cause an error (to which there are some exceptions). It follows the same rules as let.

In [3]:
const someConstString  = 'hello, const world!'

Additional Resources