DEV Community

Kemi Owoyele
Kemi Owoyele

Posted on

JavaScript variables and how to use them.

A variable is an identifier that represents a value. It is a named container for storing data. A value is any data that can be manipulated or operated upon within a program.
You do not need to specify the data type, as JavaScript does that on its own behind the scene. Additionally, it allows for dynamic type conversion, meaning you can convert data from one type to another as needed.

How To Create, Use, And Modify A Variable In JavaScript

The act of creating a variable is called variable declaration. To declare a variable in JavaScript, there are three keywords, var, let and const, followed by the variable name. A variable can be created without initially assigning a value to it. In such case the value of the variable will be “undefined".
For example
var name;
To assign value to the variable, use the equal sign. Assigning a value to a variable is known as initializing the variable.
var name = 'Mark ';
It can also be created and initialized at the same time.
Let gender = “male”;
var, let and const are the three keyword the we can use to create variables in JavaScript. With var and let, we can reassign values to variables whereas values assigned to const variables cannot be reassigned and are treated as constant values.
To use a variable, all you have to do is refer to the variable by name wherever you intend to use it.
console.log( name + 'is a ' + gender + 'student ')
trying to reassign the variables will result in an error if you use const but is possible if you use var and let.
example
const age = 14 ;
trying to reassign age will result in an error
age = 25 // Uncaught TypeError: Assignment to constant variable.
var firstName = 'Ade ';
var firstName = 'Ola ';//will reassign Ola as the new value of firstName
To modify a variable, use the equal to operator without the keyword.
Example;
Let count = 0;
count = count + 1;
console.log(count)

The differences between var, let and const

As discussed earlier, there are three keywords for creating variables in JavaScript. Each of these keywords has their unique attributes, and understanding these attributes will be very helpful for us when writing code to avoid unexpected outcomes.

Image description

JavaScript scope

Scope in JavaScript refers to how your variables can be accessed within your code. There are three major types of scope;
I. Global scope: variables with global scope can be accessed from anywhere in the code. They are variables written outside any function or code block. Globally scoped variables should be used only when necessary to avoid variable naming conflicts and ensure code readability
II. Function scope: function scoped variables are accessible from anywhere within the function they are declared in. Variables written in the function, but outside any specific block are accessible everywhere in the function.
III. Block scope: block scope applies to variables declared within any block of code, including if statements, for loops, and even curly braces {}. This means the variable is only accessible within that specific block.
To better illustrate variable scoping, I will use a house. The global variable will be areas outside the house, but inside the fence. Every occupant of that compound can access things or places in the compound, irrespective of the apartment. The function scope will be each apartment. People in each apartment can access things in the apartment that are not in specific bedrooms. The block scope would then be individual bedrooms. Things in the bedroom can be accessed by occupants of the bedroom but not those of another bedroom.
In JavaScript, variables declared with var keyword are function scopes. This means that even if the variable is declared in a block, it will still be available to other blocks in that function. This is not so with variables declared with let and const as they are block scoped and can only be accessed within the block of code they are declared in.

Hoisting

The default behavior of JavaScript is to move variable and function declaration to the top of the scope. This is why sometimes; it is possible to access a variable before it is declared. Hoisting behaves differently depending on how variable is declared and with functions.
Variable hoisting: variables declared with var are hoisted to the top of the function, or the global scope depending on if the variable was declared inside a function or in the global scope. The variable can also be accessed before they are declared but the value will be undefined.
Example;
console.log(x) // undefined
var x = 15;
console.log(x) // 15

Variables hoisted with let and const are hoisted to the top of the block scope they are declared in, but they are not initialized. Attempting to access these variables before they are declared will result in error
Example;
console.log(x)
// Uncaught ReferenceError: Cannot access 'x' before initialization
let x = 15;
console.log(x) // 15

temporary dead zone:Temporary dead zone(TDZ) is the zone between the beginning of the scope and the point where the variable is declared. Variables declared with var keyword can be accessed in the temporary dead zone, although the value will be undefined. On the other hand, variables declared with let and const will not be accessible in this zone. Trying to access them will result in reference error.
Function hoisting: functions are also hoisted to the top of their containing scope in JavaScript. This allows functions to be accessible before they are declared.
*Example:
*
`greet(); // hello

function greet () {
console.log('Hello ');
};
If the function is assigned to a variable, it will not be accessible before declaration.
**Example**:
greet(); // index.html:8 Uncaught TypeError: greet is not a function

var greet = function () {
console.log('Hello ');
};

Arrow functions are not accessible before declaration.
**Example:
**
greet(); // Uncaught ReferenceError: greet is not defined

greet =()=> {
console.log('Hello');
};
`

Variable immutability

An immutable variable is read-only, it means that the variable cannot be reassigned or modified. In JavaScript, you can create immutable variables using the const keyword.
The variables declared with const keyword cannot be re-assigned. The values however may still be modified. To achieve true immutability like in some other programming languages, you may have to use a library like immutable.js.
Immutability ensures consistency and predictability in programming. It also makes debugging and code maintenance easier.

Referencing a variable vs. coping the value of the variable.

There are two major data types in JavaScript. They are;
1. Primitive data types and;
I. Number
II. String
III. Boolean
IV. Undefined
V. Null
VI. Symbol
When you assign a variable with a primitive data type to another variable, it copies the value. This means that at that moment, the value of the new variable will be a copy of the old variable; if you change the value of the either variable it does not affect the value of the other.
Illustration

Image description

According to the illustration above, reassigning another value to firstName did not change the value of name. Neither did reassigning name change the value of firstName.

2. Non-primitive or object types
I. Objects
II. Arrays
III. Functions
Object data types could also the referred to as reference types. When you assign a variable holding an object data type as a value, it does not copy the value of the variable to the new variable. Instead, it stores the address of the variable in memory. Any changes/reassignment to either of the variables will affect the other.
Illustration

Image description
As illustrated above, changes to cities array automatically changed the values of cities2 array. Likewise, changes to cities2 array changed the values of cities.

The dos and don’ts of naming variables

When giving names to variables in JavaScript, there are a few rules that must be considered. Some of them include
I. Variable names are case sensitive. GetName is not the same as getName
II. Do not begin a variable name with a number
III. Spaces are not allowed in variable names.eg.
var get name; // Uncaught SyntaxError: Unexpected identifier 'name'

IV. JavaScript reserve keywords are not allowed as variable names. Reserve keywords are words with special meanings in JavaScript.
Eg.
var return; // Uncaught SyntaxError: Unexpected token 'return'

V. Variable names can consist of lower and upper case letters a-z, numbers and $ symbol, and _ underscore.
VI. For best practice and code readability, variable names should be meaningful. The name should properly describe what it is used for.

Uses of JavaScript variables

Most of the time, while programming, there is going to be a lot of work centered around accessing data, operating on data, manipulating data, retrieving data etc. The implication of these is that variables are inevitable in JavaScript as most of these data are stored in variables. Variables play a crucial role in programming. They are used extensively for various purposes. Some of these purposes include
1. For storing data: the primary purpose of variables is to hold data. JavaScript variables store data by associating a unique identifier (name) with the value assigned to it. Variables create named storage location in memory, and values assigned to the variables are stored in that memory location. You can store different data types in that location at different occasions.
2. Calculating numbers: variables can be used to perform mathematical calculations.
Example;
Let number1 = 5;
Let number2 = 15;
Let sumNumbers = number1 + number2;
Console.log(sumNumbers);

3. Manipulating text: variables are used to hold textual values. Hence they can be useful in combining/manipulating text, concatenating strings etc.
*Example;
*
Let name = 'Ola';
Let greetName =
welcome ${ name } to this event;
Console.log(greetName);

  1. Scope Management: Variables help manage the scope of data, ensuring that variables are accessible only within the appropriate context or function scope, thus preventing naming conflicts and unintended consequences.
  2. Looping over Arrays and Objects: Variables are commonly used to hold values while performing repetitive tasks over arrays and objects. Example: **let numbers = [1, 2, 3, 4, 5]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } 6. Storing User Input:** Variables can store values entered by users through input fields or other interactive elements in web applications. let userInput = prompt("Enter your name:"); Let greetUser =welcome ${ userInput } to this event; Console.log(greetUser); These are just the few examples that are relatable at this point. Variables are very important in JavaScript. There is very little that a programmer can do without using variables.

Best practices for Variables
After learning so much about variables, it is also important to discuss how to ensure that we use variables properly. Following best practices when writing variables will make our work easier, make it easier to avoid and detect bugs, and make our codes easier to read. Some of the recommended best practices include;
I. Use descriptive names when declaring variables: Avoid single letter variable names, avoid vague variable names eg.
Let x = 'something';
Let jhjh;

Names like this will make your code difficult to read in the future. The name of your variable should tell what that variable is used for. Example;
Let firstName = 'Ola ';
Let userNameInput = prompt('what is your name ');

II. Avoid global variables: global variables are available throughout the program. To avoid naming conflict or reinitializing variables, avoid them unless it is absolutely necessary.
III. Always declare variables at the top of the containing scope: to avoid dead zone related issues, declare variable at the top of the block where you intend to used them.
IV. Prefer to declare variables with const: to prevent unexpected behavior related to hoisting and scoping issues, use const if you do not intend to reassign the variable. Use let if you intend to reassign values, and var only when dealing with legacy codes.
V. Be conscious of JavaScript automatic type conversion: JavaScript is a dynamically typed language. This means that the data type of your variables is automatically generated. Understanding how JavaScript generates and converts data types will help you write better codes and avoid errors and unexpected outcomes.
VI. Declare arrays and objects with const: declaring objects and arrays with const will prevent accidental change of data type.

VII. Initialize variables immediately you declare them: to prevent undefined values and errors, always assign values to your variables as you are creating them.
Example;
Let count = 0;
Let userInput = null;

VIII. Be consistent: developing consistent habit in following the variable best practices, especially with naming consistency will make your codes more readable and easier to maintain and debug.
Conclusion
Proper understanding of JavaScript variables is very important, as it is fundamental to building any meaningful application in the language. With proper understanding of variables, you are in a better position to write clear and easy to maintain codes, debug errors and build meaningful applications.

Top comments (0)