All About Variables

How to work with information in JavaScript

Emily Y Leung

--

Field notes while going through the JavaScript Roadmap

Photo by Luca Bravo on Unsplash

Variable Declarations in JavaScript

  • A variable is a “named container” for a value
  • To declare a variable in JavaScript, use the let , const or var 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 of let (which was introduced in ECMAScript6)— they are similar, but not the same. var is now considered “old-school”
  • const is another type of variable like let , 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 or classes 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…

--

--