This article will explain the different types of declarations, as well as how and when to use them in order to optimize your code and improve performance.
Primitive variables include numbers, strings, booleans, and special values (null, undefined), while non-primitive variables include objects, arrays, and functions.
Variables declared with let can be used for both primitive and non-primitive types. Variables declared with const must have a value assigned to them when they are declared and that value must be primitives. Non-primitives cannot be assigned using const due to their dynamic state.
Var vs. Let vs. Const – When to Use Which
Var should be used when declaring a variable that could be reassigned or updated at a later time.
Let should be used when declaring a variable that will only ever need to hold one value or is unlikely to ever change over the course of code execution.
Const should be used when declaring a variable that will always remain constant and never change throughout code execution.
Declaring a Variable
For example, if you wanted to store the value “5” in a variable named “num”, you would use a statement like this:
var num = 5;
The statements below could be used to declare variables with let and const as well.
let num = 5; const num = 5;
Understanding Scope Rules and Variable Lifecycle
The two main scopes are global and local, with global variables being available from anywhere within the program, while local variables only exist within a particular section of code. The variable’s lifecycle is determined by when it is declared and how far down in the code block its value persists or changes.