Variables
Variables are used to store data in a program. They act as containers that hold values, which can be used and manipulated throughout the program. In JavaScript, variables are declared using the var
, let
, or const
keywords. This data is stored in the memory of the computer and can be accessed and modified as needed.
How Variable works
When a variable is declared in JavaScript, a memory space is allocated to store the value associated with that variable. The value can be assigned to the variable using the assignment operator (=
). Once a value is assigned to a variable, it can be accessed and manipulated using the variable name. With the variable name, you can perform various operations such as reading, updating, and deleting the value stored in the variable. Think of boxes used to organize items in a room. Each box has a label (variable name) and can store different items (values).
Declaring Variables
In JavaScript variables, can be declared in four ways:
- Automatically without any keywords
- Using the
var
keyword - Using the
let
keyword - Using the
const
keyword
- The
let
andconst
keywords were introduced in ECMAScript 6 (ES6) in 2015. - The
var
keyword is the old way of declaring variables in JavaScript introduced in ECMAScript 3 (ES3) in 1999 and is not recommended for modern JavaScript development.
1. Automatically without any keywords
In JavaScript, you can declare a variable without using any keyword. This is not recommended as it can lead to unexpected behavior and is considered bad practice. When a variable is declared without any keyword, it is automatically assigned to the global object (window
in the browser). This can cause conflicts with other variables and functions in the global scope. This is how you can declare a variable without any keyword:
// Declaring a variable without any keyword
variableName = value;
A good example is this code:
x = 10;
y = 20;
z = x + y;
console.log(z); // Output: 30
2. Using the var
keyword
The var
keyword can also be used to declare a variable in JavaScript. It is function-scoped, meaning that it is accessible only within the function in which it is declared. If a variable is declared outside a function using the var
keyword, it becomes a global variable and is accessible throughout the program. This is how you can declare a variable using the var
keyword:
var variableName = value;
A good example is this code:
var x = 10;
var y = 20;
var z = x + y;
console.log(z); // Output: 30
3. Using the let
keyword
The let
keyword was introduced in ECMAScript 6 (ES6) and is used to declare block-scoped variables. A block is a set of statements enclosed in curly braces ({}
). Variables declared using the let
keyword are accessible only within the block in which they are declared. This is how you can declare a variable using the let
keyword:
let variableName = value;
A good example is this code:
let x = 10;
let y = 20;
let z = x + y;
console.log(z); // Output: 30
4. Using the const
keyword
The const
keyword was also introduced in ECMAScript 6 (ES6) and is usually used to declare block-scoped variables. Variables declared using the const
keyword are constant and cannot be reassigned a new value. This means that the value of a constant variable remains the same throughout the program. This is how you can declare a variable using the const
keyword:
const variableName = value;
A good example is this code:
const x = 10;
const y = 20;
const z = x + y;
console.log(z); // Output: 30
If you try to reassign a new value to a constant variable, you will get an error:
const x = 10;
x = 20; // Error: Assignment to constant variable.
When to use var
, let
, or const
- Always use
const
by default and only uselet
if you need to reassign the variable. - Always declare your variables at the top of the function or block to avoid hoisting issues.
- Always use
let
orconst
to avoid global variables and unexpected behavior. - Always use
const
if the type of the variable will not change especially for functions and objects. - Only use
var
if you are working with legacy code or need to support older browsers.
Identifiers
An identifier is a name given to a variable, function, class, or object in JavaScript. It is used to identify and reference the entity it represents. Identifiers are case-sensitive, meaning that myVar
, MyVar
, and MYVAR
are different identifiers. Identifiers must follow certain rules and conventions to be valid in JavaScript.
Variable Naming Rules
When naming variables in JavaScript, you should follow these rules:
- They can contain letters, digits, underscores (
_
), and dollar signs ($
). - Variables must begin with a letter, an underscore (
_
), or a dollar sign ($
). - Variables are case-sensitive (
myVar
,MyVar
, andMYVAR
are different variables). - They should be descriptive and meaningful to make the code more readable.
- They should not be reserved keywords or predefined names in JavaScript(identifiers).
- Variables should follow the camelCase naming convention (e.g.,
myVariableName
). - They should not start with a digit (e.g.,
1variable
is invalid).
Multiple Variable Declarations
In Javascript, you can declare many variables in a single line:
let x = 10, y = 20, z = 30;
console.log(x, y, z); // Output: 10 20 30
These declarations can even span multiple lines:
let x = 10,
y = 20,
z = 30;
console.log(x, y, z); // Output: 10 20 30
Also, you can declare variables without assigning a value. A variable declared without a value will have the value undefined
:
let x;
console.log(x); // Output: undefined
It is also important to note that when using the var
keyword, you can redeclare a variable without any errors. This can lead to unexpected behavior and is considered bad practice:
var x = 10;
var x = 20;
console.log(x); // Output: 20
When using the let
or const
keyword, you cannot redeclare a variable in the same scope. This will result in an error:
let x = 10;
let x = 20; // Error: Identifier 'x' has already been declared
Hoisting
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use a variable or function before it is declared in your code. However, only the declaration is hoisted, not the initialization. This can lead to unexpected behavior if you are not aware of how hoisting works.
In simple words, hoisting is a concept where the interpreter would "hoist" (raise, lift) the declaration of functions, variable and classes to the top of the scope they were defined, before executing the code. This makes function accessible before the line where they were defined. The difference between declaring a variable and initializing it is that declaring a variable is when you create a variable without assigning a value to it, while initializing a variable is when you assign a value to the variable. Initialization is not hoisted, only the declaration is hoisted. Some people refer to initialization as assignment or defining a variable.
Variable Hoisting
When using the var
keyword to declare a variable, the variable declaration is hoisted to the top of the function or global scope. This means that you can use the variable before it is declared in your code:
console.log(x); // Output: undefined
var x = 10;
In that example, the variable x
is hoisted to the top of the scope, so the code is interpreted as:
var x;
console.log(x); // Output: undefined
x = 10;
This is different from using the let
or const
keyword, where the variable declaration is hoisted to the top of the block scope but is not initialized:
console.log(x); // Error: Cannot access 'x' before initialization
let x = 10;
The code is interpreted as:
let x;
console.log(x); // Error: Cannot access 'x' before initialization
x = 10;
I personally recommend trying the examples to see how hoisting works in JavaScript as it requires some practice to understand it fully.
Conclusion
Variables are an essential part of programming and are used to store data in a program. In JavaScript, variables can be declared using the var
, let
, or const
keywords. It is important to follow best practices when declaring variables to avoid unexpected behavior and make the code more readable and maintainable. Understanding how variables work and how they are hoisted in JavaScript is crucial for writing efficient and bug-free code.
In the next section, we will learn about data types in JavaScript and how they are used to represent different kinds of values in a program.
Made with ❤️ by Fasakin Henry