All About Variables
How to work with information in JavaScript
7 min readAug 6
--
Field notes while going through the JavaScript Roadmap
Variable Declarations in JavaScript
- A variable is a “named container” for a value
- To declare a variable in JavaScript, use the
let
,const
orvar
keyword - Here’s an example of a variable “message” initialised with the value of string “Hello”
let message;
message = "Hello";
// or
let message = "Hello";
- The string is now saved into memory
let
allows us to change the value that is stored in the variable as many times as we want- Previously, in older scripts,
var
was used instead oflet
(which was introduced in ECMAScript6)— they are similar, but not the same.var
is now considered “old-school” const
is another type of variable likelet
, however, the value of the variable cannot be changed — hence the shortened name for “constant”- Variables can store all sorts of data types — such as numbers, strings, booleans, arrays and objects
- JavaScript is a “dynamically typed language” which means that you don’t need to specify what data type a variable will contain before assigning a value
- While a constant must always store the same value, the content of the value can change. This can be seen when working with an object:
const bird = { species: "Kestral" };
console.log(bird.species); // "Kestral"
bird.species = "Striated Caracara";
console.log(bird.species); // "Striated Caracara"
typeof
deals with non-existent variables — i.e.undefined
— and therefore doesn’t lead to any errors
Hoisting
- Variable hoisting is when when the declaration of
functions
,variables
orclasses
are put into action before executing any other statements in the code - To describe what is happening through an analogy — it effectively brings all the variable declaration statements up to the top-most location
- The benefit of this is that no matter where functions and variables are declared, they are moved to top — no matter if…