Variables in Javascript
Understanding Variables in JavaScript: The Key to Dynamic Programming
JavaScript is a dynamic, object-oriented programming language that is widely used for creating interactive web pages and web applications. One of the most fundamental concepts in JavaScript is variables. Variables are containers that hold data or values that can be used throughout the code. In this blog, we will take a closer look at variables in JavaScript and how they work.
Declaring Variables in JavaScript
In JavaScript, you can declare a variable using the var
, let
, or const
keywords followed by variable name. In the example given below we have declared a variable name “user” with let
keyword.
let user;
Assigning Values to Variables
Once you have declared a variable in JavaScript, you can assign a value to it using the = operator. For example:
let user;
user = 'Rahul';
You can also declare and assign a value to a variable in a single line:
let user = 'Rahul';
// Multiple variables can also be decalred simultaneously by separating them with comma
let firstName = 'Rahul', lastName = 'Jindal';
For variables created with var
and let
keyword, values stored can be updated anytime.
let user = 'user1';
user = 'user2';
As Javascript is a dynamic language, any variable can be assigned values of any data type at runtime. The dynamic behavior of JavaScript can lead to flexibility and ease of use, but also requires careful attention to type conversions and error handling to avoid unexpected behavior.
let myVariable = "Hello World"; // Initially assigning string type value
myVariable = 42; // Re-assigning variable with number type value
myVariable = true; // Re-assigning variable with boolean type value
Using "let”
in Javascript
- Declares block-scoped variables:-
let
keyword is used for declaring block-scoped variables. Block-scoped variables are those that are only accessible within the block of code in which they were declared. A block of code is generally identified as that code which is written inside the opening and closing parentheses.
if (true) {
let myVar = 'Hello World';
console.log(myVar); // Output: Hello World
}
console.log(myVar); //Output: Error: myVar is not defined
In this example, we have a block that declares a variable named “myVar” using the let
keyword. This variable is only accessible within the block of code identified by “if” condition. If we try to access the variable outside of the block, we will get an error message.
- Do not allow Re-declarations:-
let
variables cannot be re-declared within the same block of code. For example:
let myVar = "Hello World";
let myVar = "Bye World"; // Output: Error: Identifier 'myVar' has already been declared
- Allow to update values:- variables declared with
let
can be updated by assigning a new value to them. For example:
let myVar = "Hello World";
myVar = "Bye World";
console.log(myVar); // Output: Bye World
Using "const”
in Javascript
const
keyword is also used for declaring block-scoped variables but they cannot be reassigned once they have been initialized. To declare a variable with const
, you simply use the const
keyword followed by the variable name.
const myVar = "Hello World";
It is necessary to initialize the variable at the time of declaration, else error will be thrown.
They are useful for storing those values which are expected not to change throughout the code life cycle. One such example can be value of PI while doing some math operation.
There is a practice where constants whose values are known before the code compilation are generally written in uppercase, so that it will be easy to recognize them from the variables whose values will be determined during runtime.
const PI = 3.14;
const PAPER_SIZE = 'A4';
In the above example, we are having a variable PAPER_SIZE
which consists of 2 words. So, for uppercase constants such type of variables are joined using underscore.
Using “var”
keyword in Javascript
var
keyword is the oldest of the 3 keywords used for variable declaration and is similar to let
keyword but it is not commonly used today due to its quirks and limitations. It was these limitations because of which let
and const
was introduced in ECMAScript 6 (ES6) or ECMAScript 2015. We will now take a closer look on its uses and limitations.
- Declares function-scoped variables:- Variables declared with the
var
keyword in JavaScript have function scope. This means that when a variable is declared inside a function, it can be accessed from anywhere within that function, but it cannot be accessed outside of that function.
function sayHello() {
var message = 'Hello! How are you?'
console.log(message) // Output:- 'Hello! How are you?'
}
sayHello();
console.log(message) // Output: Error:- message is not defined
In earlier days, function-scoping limited the developers compared to block scope because function-scoped variables are accessible throughout the entire function, even if they are defined inside a separate block of code.
function sayHello() {
if (true) {
var message = 'Hello! How are you?'
console.log(message) // Output:- 'Hello! How are you?'
}
console.log(message) // Output:- 'Hello! How are you?'
}
sayHello();
console.log(message) // Outout: Error:- message is not defined
In the example, we can clearly see that “message” variable to be declared inside the “if” block but it was still accessible from outside of it, because of function-scoping. This can lead to unintended consequences, such as variable re-assignment or value overwriting, which can be difficult to debug.
At the time when only var keyword was available for variable declaration, to resolve the scoping issue, a new concepts was introduced called IIFE ( Immediately Invoked Function Execution ), which can be read in more detail from MDN web docs.
- Variable Re-declaration Allowed:- Another quirk of
var
is that it allows for re-declaration of variables within the same scope.
var myVar = "Hello World";
var myVar = "Bye World";
console.log(myVar); // Output: Bye World
This behavior can be confusing and lead to errors, particularly when working with larger codebases or collaborating with other developers.
- Accessing variables before declaration:-
var
declared variables can be accessed even before they are declared.
function myFunction() {
myVar = "Hello World"
console.log(myVar); // Output: "Hello World"
var myVar;
}
myFunction();
Here in the example we can see that “myVar” is accessible even before the declaration, while same will throw error when let
or const
being used.
This is happening because of a concept called Hoisting. In hoisting var
declaration is moved at the top of its scope and assigned “undefined” value before code execution starts. So, it will made variable accessible throughout the scope of the code. It works in a slightly different way for let
and const
.
We also need to remember that only declarations are hoisted not the assignments.
function myFunction() {
console.log(myVar); // Output: undefined
var myVar = "Hello World";
}
myFunction();
In the above code, we can see that value is not getting hoisted and variable is giving “undefined” as output.
In strict mode, variables declared with var
are still hoisted to the top of their scope, but if they are used before they are initialized, a “ReferenceError” will be thrown. This behavior helps to catch potential bugs in the code and makes it easier to reason about the behavior of variables.
Conclusion
In conclusion, variables are an essential concept in JavaScript that allow developers to store and manipulate data values. Understanding how to declare, assign and use variables is crucial for writing efficient and effective code. The introduction of let
and const
in ES6 has provided developers with more control over their variables, while the limitations of var
, such as scope issues and re-declaration, have encouraged the use of let
and const
in modern JavaScript development. Overall, variables are a fundamental building block of JavaScript programming, and mastering their use is essential for any aspiring developer.