In JavaScript
In JavaScript
1. var:
Variables declared with var are function-scoped,
meaning they are only visible within the function where
they are declared. If declared outside any function, the
variable is global.
var is hoisted to the top of its scope, which means you
can use the variable before it is declared in the code.
var allows redeclaration of the same variable within the
same scope.
Ex 1:
function example() {
if (true) {
var x = 10;
}
console.log(x); // Outputs 10, despite being declared inside the 'if' block
}
Ex 2:
function example() {
console.log(x); // Outputs 'undefined' due to hoisting
var x = 10;
console.log(x); // Outputs 10
}
example();
2 let:
Variables declared with let have block scope, meaning they
are only visible within the block (enclosed by curly braces)
where they are defined.
let is also hoisted, but it is not initialized until the actual
declaration is encountered in the code. This is known as the
"temporal dead zone."
Unlike var, let does not allow redeclaration of the same
variable within the same scope.
Ex 1:
function example() {
if (true) {
let x = 10;
}
console.log(x); // Error: x is not defined
}
Ex 2:
function example() {
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 10;
console.log(x); // Outputs 10
}
example();
3.const:
Variables declared with const are also block-scoped.
const is used for constants, and once a value is
assigned to a const variable, it cannot be reassigned.
Like let, const is hoisted and subject to the temporal
dead zone.
It is important to note that while the variable itself is
immutable, the value it holds may not be if it is an
object or an array. This means you cannot reassign a
new value to a const variable, but you can modify its
properties or elements.
Ex 1:
const PI = 3.14;
PI = 4; // Error: Assignment to a constant variable
const obj = { key: 'value' };
obj.key = 'new value'; // Valid, because the object itself is mutable
2.typeOf ()??
2. **Checking Objects:**
3. **Checking Functions:**
let x;
typeof x; // "undefined"