JavaScript concepts: Variables, types and scopes
How to store data in a temporary container
There will come a time in your life as a developer when you find yourself needing to store some information when crafting awesome applications. That moment will happen almost two seconds after you open your first index.js. So it is best that we tackle this concept early on.
A variable lets you store information - a value - in a word and keeps it available to you throughout your javascript file or function, depending on the declaration you use. In other words: It is a temporary container in which you can store anything you like.
const x = 'I am some value';
console.log(x) //'I am some value'
In JavaScript, you declare a variable, assign it a value and use that value for further computations. It is good to know the distinction between a variable and a value. The variable will not become the value you assign it to, but rather it will be the box the value lives in.
let y;
y = 'Value 1';
console.log(y) // 'Value 1'
y = 'Another value';
console.log(y) // 'Another value'
In the above examples, I am doing something that is considered a bad practice: Calling your variables non-descriptive names like x and y. If you want to keep your code clear, use descriptive names that describe what the variable is or contains. It will make your own life and the life of the developers who need to be able to read and understand your code a whole lot easier.
Variable declarations
As I mentioned before, you have to declare a variable before it can exist. This simply means you tell JavaScript that a word from now on will contain a value and that you'd like to use that value. There are three official declarations for JavaScript variables: var, let and const. They all have their characteristics and choosing one over the other will have an impact on your results. Let's discuss each one.
Var
The OG variable. For a while, var was the only way to declare a variable. var has some issues that its successor let solves.
Var:
can be reassigned to a new value
can be initialized before it will be declared
is somewhat outdated and let is nowadays preferred over var.
var greeting = 'Hello'; // initialized
var greeting = 'Good morning'
function speak() {
console.log(greeting);
}
speak(); // 'Good morning'
var greeting; // declared
Let
The successor of var. Let has a lot of the same properties but fixes a few issues that var seemed to have.
Let:
can be reassigned to a new value
has to be declared before it can be initialized
is best used when you are certain that the variable needs to be reassigned at a later point.
let greeting;
greeting = 'Good morning';
function speak() {
console.log(greeting);
}
speak(); // 'Good morning'
greeting = 'Good evening';
speak(); // 'Good evening'
Const
Const is short for 'constant', a type of variable that cannot be reassigned.
Const:
cannot be reassigned to a new value
must be initialized when you declare it
is best used when you are certain that you will not reassign your variable to a different value.
const greeting = 'Good morning'; function speak() { console.log(greeting); } speak(); // 'Good morning' greeting = 'Good evening'; // Uncaught TypeError: Assignment to constant variable.
Variable types
Now that we know what the declarations of variables mean, let's take a look at the type of information a variable can contain.
Strings
A string is a piece of text enclosed by single or double quotation marks.
const stringExample = 'This variable contains a string. It can be as long as you like!';
Number
A number is either a whole number (10) or a decimal number (1.34). Be mindful that you do not wrap a number value in quotation marks. If you do, JavaScript will treat it as a string.
const wholeNumberExample = 30;
const decimalNumberExample = 0.345;
Boolean
A boolean is a true or false value. The value of these types of variables can only be true or false. This type is used a lot in combination with JavaScript conditionals in which a condition is tested.
const booleanExample = true;
// Or when using a condition:
const conditionalExample = 3 > 2; // true
Array
When you want to store a few different values in the same variable, you can typically use an array. Enclosed by square brackets, an array holds multiple values and can be easily accessed using index numbers. JavaScript index numbers begin at 0. The 0 indicates the first slot in the array.
const arrayExample = ['guinea pig', 'cat', 'dog', 'lion'];
arrayExample[0]; // guinea pig
arrayExample[3]; // lion
Object
Up until now the types usually contain either a single value or more values. A JavaScript object contains more information on a value. It resembles a real-life object, like for instance a cookie. A cookie can contain information about the ingredients, size and type. An object can be recognized by the { } curly brackets or moustaches.
const cookieExample = {
type: 'Chocolate',
ingredients: ['flour', 'sugar', 'salt', 'eggs'],
size: 'Large'
}
cookieExample.type // Chocolate
cookieExample.size // Large
Variable scopes
When we say 'variable scope', we mean the space in which the variable can be accessed and used. It refers to the availability of the variable. We will discuss the different variable scopes and explore this concept a bit with some examples.
Global scope
A variable declared outside of block scope or function scope can be used anywhere in the same JavaScript file. Var, let and const all adhere to the global scope when declared outside of any function. When a variable is initialized within the global scope, it is a global variable.
let name;
const greeting = 'Good morning ';
var restOfGreeting = 'Nice to meet you';
function alertMe() {
name = 'Dumbledore ';
alert(greeting + name + restOfGreeting);
}
name = 'Harry '; // This can be accessed here.
greeting = 'Hello '; // This can be accessed here.
restOfGreeting = 'How are you today?'; // This can be accessed here.
alertMe();
Function scope
Each function in JavaScript creates its own scope. Local variables have a function scope: They are created when a function is initialized and deleted when a function has run. Var, let and const all behave similarly within a function: They cannot be accessed outside of the function.
function alertMe() {
let name;
const greeting = 'Good morning ';
name = 'Dumbledore';
alert(greeting + name);
}
name = 'Harry'; // This cannot be accessed here.
greeting = 'Hello'; // This cannot be accessed here.
alertMe();
Block scope
Variables declared inside a { } block will only be accessible within this { } block. This scope is relatively new. When let and const were introduced in ES6 (2015), the block scope came with them. Let and const both cannot be used outside of the { } block if they are declared in this block. Var, however, can be accessed outside of the block scope.
{
let name;
const greeting = 'Good morning ';
var restOfGreeting = 'Nice to meet you';
}
name = 'Harry'; // This cannot be accesses
greeting = 'Hello'; // This cannot be accessed
restOfGreeting = 'Goodbye'; // This can be accessed here.
Key points:
Use descriptive variable names
Use let instead of var if you need to reassign a variable
Use const in all other cases
Be mindful of the scope in which your variable lives