All About Variables

How to work with information in JavaScript

Emily Y Leung
7 min readAug 6, 2023

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 their scope is global or local

Sequence of variable declaration

Declaration > Initialisation / Assignment > Usage
// Assignment
str = "Hoisting";

// Usage
console.log(str) // "Hoisting"

// Declaration
var str;

In the above example, while the variable str was declared after it was initialised, the effect of hoisting means that the variable declaractions are executed first before initialising the value. Therefore, the code will be read in this order:

// Declaration
var str;

// Assignment
str = "Hoisting";

// Usage
console.log(str); // "Hoisting"
  • JavaScript only hoists declarations, not initialisations. However let declarations are not hoisted
  • An undeclared variable is assigned the value undefined at execution and is also of type undefined
  • All undeclared variables are global variables
function hoist() {
a = 20; // Undeclared variable
var b = 100; // Scoped variable
}

hoist();

console.log(a); // Output: 20

console.log(b); // Output: ReferenceError: b is not defined
  • A ReferenceError is thrown when trying to access a previously undeclared variable
  • When using var the output would have been undefined . However, the introduction of let means that we will get a ReferenceError
console.log(hoist); // Output: ReferenceError: hoist is not defined

let hoist = "The variable has been hoisted.";
  • const variables must be declared and initialised before use
  • It is recommended to always declare variables regardless of whether they are in a function or global scope
  • Variables declared with let and const remain uninitialised at the beginning of execution, while variables declared with var are initialised with a value of undefined

Hoisting Functions

  • A function as a whole can be hoisted and be called before the declaration
fun(); // Calling before declaration

function fun() { // Declaring
console.log("Function is hoisted");
}

// "Function is hoisted"
  • If a function is used as an expression, an error will occur if we try to access it before assignment
fun(); // Calling the expression

let fun = () => { // Declaring
let name = "Jane Doe";
console.log(name);
}

// Uncaught ReferenceError: fun is not defined

Order of Precedence

  • Variable assignment takes precedence over function declaration
  • Function declaration take precedence over variable declaration
  • Function declarations are hoisted over variable declarations but not over variable assignments

Strict Mode

  • In ES5, JavaScript created a utility that opts into restricting how we declare and use variables — strict-mode
  • It explicitly throws errors that would otherwise come through as silent errors
  • It fixes mistakes and prohibits syntax errors which will likely be defined in future versions of JavaScript
  • Strict mode behaves differently depending on the browser used — so make sure to run tests
"use strict";

console.log(hoist); // Output: ReferenceError: hoist is not defined

hoist = "Hoisted";

Class Declarations

  • You must declare a class before you can use it
var Square = new Polygot();
Square.height = 10;
Square.width = 10;
console.log(Square); // Output: TypeError: Polygot is not a constructor

var Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
}

Variable Naming Rules

Rules we must follow

  • Names can only contain alphanumeric characters (a-z, A-Z, 0–9). _ and $ characters are also allowed — first-name is not valid
  • Names cannot begin with a digit — 2nd is not valid
  • Names cannot contain spaces — first word is not valid
  • Names cannot use reserved keywords — return is not valid

Be descriptive

  • username is better than uname

Don’t be overly descriptive

  • While there is no limit to the length of the variable name, it’s better to have a shorter descriptive name
  • firstname is better than thefirstnameofuser

Abbreviate long words

  • dbname is better than databasename

Use a casing convention to break words

  • camelCasing — used for naming functions
  • PascalCasing — used for naming React components
  • snake_casing — can also be used for naming functions
  • SCREAMING_SNAKE_CASING — used for constants

Naming convention examples

////////////////////////////////

// CONSTANTS
var daysUntilTomorrow = 1; // bad
var DAYS_UNTIL_TOMORROW = 1; // good

////////////////////////////////

// BOOLEAN
var visible = true; // bad
var isVisible = true; // good

////////////////////////////////

// FUNCTIONS

// bad
function name(firstName, lastName) {
return `${firstName} ${lastName}`;
}

// good
function getName(firstName, lastName) {
return `${firstName} ${lastName}`;
}

////////////////////////////////

// COMPONENTS

// bad
function userProfile(user) {
return (
<div>
<span>First Name: {user.firstName}</span>
<span>Last Name: {user.lastName}</span>
</div>
);
}

// good
function UserProfile(user) {
return (
<div>
<span>First Name: {user.firstName}</span>
<span>Last Name: {user.lastName}</span>
</div>
);
}

Summary of variable naming rules

  • camelCase convention is commonly used to define variables that have multiple words
  • Names can contain alphanumeric characters, but it cannot begin with a digit
  • $ and _ can also be used in names. They are symbols that have no special meaning
  • Names cannot contain spaces
  • Variable names are case sensitive
  • Make sure to avoid using JavaScript reserved words when defining variable names — examples include: return , for , function , etc
  • Choose a convention and stick to it

File naming conventions

  • In frontend applications, PascalCase is commonly used for naming React components — UserProfile.js
  • In backend applications, kebab-case is commonly used — user-route.js

Variable Scopes

  • Scope refers to the visibility of a variable and how it can be used after it is declared
  • There are 3 types of scope — Global, Function and Block
  • Before ES6 (2015), Global and Function scopes were available with the var keyword. ES6 introduced the Block scope via the let and const keywords
  • If you assign a value to variable that has not yet been declared, it will automatically become a global variable

Global Scope

  • Variables declared outside any function can be accessed from anywhere
let carName = "Volvo";

// Code here can use carName

function myFunction() {
// Code here can also use carName
}
  • var , let and const all provide this scope
  • If you assign a value to variable that has not yet been declared, it will automatically become a global variable
  • Whether you have a script tag or JavaScript file, anytime you declare a global variable, it will be available anywhere in the application
// main.js

const first = "wes";
<script src="./main.js"></script>
<script>
console.log(first); // Output: wes
</script>
  • When you create a global variable in the JavaScript file — you can access global variables from other JavaScript code that’s running on the same page
  • In the browser, the global scope is called the window
const first = "wes";
let second = "bos";
var age = 100;
  • However, if we loaded the above code into the same HTML file, we would get a different result when we try to access these values in the browser console
window.first; // Output: undefined

window.second; // Output: undefined

window.age; // Output: 100
  • Turns out, while first and second are globally scoped, they are not attached to the window like var is
  • Functions are also accessible to the window — only const and let do not

Function Scope

  • Variables declared within a function and therefore only used within that function — they are known as “local” variables — and is not accessible outside the function
  • var , let and const all provide this scope
// Code here can NOT use carName

function myFunction() {
let carName = "Volvo"; // Code here CAN use carName
}

// Code here can NOT use carName
  • If variables are not found inside of a function (but are referenced), it will go up a level higher and look for that variable in that scope
  • Shadowed variables are variables that are initialised in the parent and child scope with the same name — which means you cannot access the parent variable because it’s been over-written with the child scope variable

Block Scope

  • Any part of JavaScript code that’s bounded by curly braces {}
  • These variables cannot be accessed outside that block
  • This only applies to let and const keywords
{
let x = 2;
}

// x can NOT be used here
  • var keyword does not have block scope
{
var x = 2;
}

// x CAN be used here

--

--

Emily Y Leung
Emily Y Leung

Written by Emily Y Leung

Creative. Problem solver. Learning programming in public | emilyyleung.github.io

No responses yet