Variables are building blocks of any programming language and variable is something that can change its value. Variables are containers that can hold value.
- Purpose: Variables holds a value and one can reuse variables as many times as needed. The value of the variable can be changed.
- In JavaScript Variables are used to store values and are declared using the ‘var’, ‘let’, or ‘const’ keywords. Variables in Javascript can hold different types of values including primitive values and references to non-primitive values.
Variable Declaration
- Each variable has name and process of variable creation is called variable declaration
- There are three reserved keywords used to declare a variable.
- var, let, const
var
- variables declared with ‘var’ have function scope or global scope, meaning they are accessible within the function or globally throughout the program.
- They can be declared and assigned values multiple times within the same scope.
- Variables declared with ‘var’ are hoisted to the top of their scope, so they can be accessed before they are declared.
- JavaScript process all the declarations before it starts to execute the program. Thus, declaring the variable anywhere inside the code is equivalent to declaring it at the top of the code. Therefore, JavaScript gives the ability to use the variable before their declarations in the code. This behavior of variables is termed as var hoisting
var v1; variable declaration
var v2 = “cat” // variable initialization
Example
<html>
<body>
<script>
{
var a;
document.write(a+"</br>")
}
document.write("Outside the block a is" + a + "</br>");
var b = 10;
document.write("b="+b+"</br>")
b = "Java Script"
document.write("After reassigning b="+b+"</br>")
</script>
</body>
</html>
let
- let introduces block scoping, which means that variables declared with ‘let’ are limited to the block (enclosed within curly braces{ }) in which they are defined including any nested blocks
- Key features:
- Block scope: variables declared with ‘let’ have block scope, which means they are accessible only within the block in which they are declared and not outside of it
- Hoisting: let variables are hoisted to the top of their scope, but they are not initialized until the actual declaration. This means that trying to access a ‘let’ variable before its declaration will result in Reference Error
- Redefinition: It is not possible to declare the same variable within the same scope using let. This leads to syntax error
Code
if (true) {
// console.log(x); // error ReferenceError: Cannot access 'x' before initialization
let x = 10;
console.log(x);
}
// console.log(x); // ReferenceError: x is not defined
Output
const
- Introduced in ECMAScript 2015 ( ES6)
- ‘const’ is used to declare constants.
- Variables declared with ‘const’ have block scope, similar to ‘let’
- ‘const’ variables are read – only and cannot be reassigned once they are assigned a value
- ‘const’ variables are not hoisted to the top of their scope.
- An initializer for a constant is required; i.e., one must specify its value in the same statement in which it is declared.
<html>
<body>
<script>
{
const a;
document.write(a+"</br>")
}
</script>
</body>
</html>
<html>
<body>
<script>
{
const a = 10;
document.write("Inside block a = "+a+"</br>")
}
document.write("Outside block a = "+a+"</br>")
</script>
</body>
</html>
Choosing the appropriate keyword (‘var’, ‘let’ or ‘const’) depends on the desired scope and mutability of the variable.
Characteristics
JavaScript is Loosely typed
JavaScript is known as untyped/loosely/weakly typed language. This means that we do not have to specify the data type in advance unlike other languages.
var x;
x = 5;
In the variable declaration, we no need to specify the data type for x
Javascript is dynamically typed
JavaScript is dynamically typed language meaning that once a variable is created with var, any kind of value can be stored in it.
var x = 5; // x is assigned with number value
x = “JavaScript”; // x is assigned with string
In Java Script, you can reassign value of any type to the existing variable declared with “let”, “var”
let
Introduced in ECMAScript 2015 (ES6), ‘let’ allow for block – level scopingVariables declared with ‘let’ have block scope, meaning they are accessible only within the block in which they are defined.They can be reassigned but cannot be redeclared within the same block scope
<html>
<body>
<script>
{
let a;
document.write(a+"</br>")
a = 10; // let a = 10 leads to error
document.write(a+"</br>")
}
let b = 10;
document.write("b="+b+"</br>")
b = "Java Script"
document.write("After reassigning b="+b+"</br>")
</script>
</body>
</html>
Summary
- With var and let, one can create variable and later on assign. But for const, variable declaration and assignment should happen in one line.
- Variable declaration is a statement and variable assignment is an expression
- For let and var variables, variables can be re initialized, whereas for const it is not possible
- If try to access variable that is declared later using “let” or “const”, then reference error: Variable is not defined arises. When variable is declared using “var” or “let” its value will be automatically set to undefined.
Static typed vs. dynamic typed:
Static typed: Type of each variable is defined before code is executed
Dynamic typed: Type of the variable will be set dynamically depending on the value that we assigned to the variable. In other words, the type of the variable is set dynamically during code execution. And this type can change during code execution.
Java Script is dynamically typed language,
- This is advantage, as it is easy to assign values to the variables and type of the variable is set during the code execution.
- This is drawback, for example: if a variable “num” is assigned with a number, then accidentally if the value is changed to string (because this is possible in JavaScript) and if pass the variable num to a function which is expecting number, will throw error and it will be difficult to find where it is reassigned if the source code is large.
- Possible solution: Use const, because variable initial declaration and assignment happens at one line and re-assignment is not possible.
Dynamic typing is JS
Consider the below example where initially a is assigned with 100 (a number), then true (a boolean) then Java Script (a string) and finally to object. It will not produce any error
Hoisting is a behavior in Java Script where variable and function declarations are moved to the top of their respective scope during the compilation phase before the code is executed i.e., the variables and functions can be used before they are actually declared in the code. Only the declarations are hoisted not the initializations or assignments.
Example
console.log(x); // Undefined
var x = 10;
The variable x is hoisted to the top of its scope, and the console.log statement runs without any error. However, x is undefined at that point because the initialization var x = 10; is not hoisted, only the declaration var x; is hoisted.
Views: 23