difference in var let and const
var:
* hoisted(global scope)
* function scope
let:
* block scope
* reassignable
* not redeclarable
const:
* block scope
* not reassignable
* not redeclarable
difference in var let and const
var:
* hoisted(global scope)
* function scope
let:
* block scope
* reassignable
* not redeclarable
const:
* block scope
* not reassignable
* not redeclarable
difference between var and let and const in javascript
var variable1 // declared using var
const variable2 // declared using const
myFunction1();
function myFunction1() {
variable1 = "hello!";
console.log(variable1);
// "hello!"
}
myFunction2();
function myFunction2() {
variable2 = "hello!";
// error: variable2 is a constant and can not be redifined
}
myFunction3(true);
myFunction3(codition) {
if(condition) {
let variable3 = "helo!" // declared using const
}
variable3 = "hello!";
// error: variable3 is out of scope
}
/*
Therefore,
var:
-can be declared outside any function to be used inside any function
-can be declared inside any function or any other {} which are of only if or if-else or switch etc. and can be used anywhere inside the function
-can be changed again and again anywhere
let:
-can be declared outside any function to be used inside any function
-if declared inside any function or any other {} which are of only if or if-else or switch etc. and can't be used anywhere inside the function and can be only used inside statement
- can be changed again and again only inside the statement in which they are made in
const:
-can be declared outside any function to be used inside any function
-can be declared inside any function or any other {} which are of only if or if-else or switch etc. and can be used anywhere inside the function
-cannot be changed again and agan anywhere, if tried to, will result in an error
*/
difference between var, let, const
// var is a function scope ***
if(true){
var varVariable = 'This is var';
var varVariable = 'This is var again';
}
console.log(varVariable); // This is var again
// let is a block scope ***
if(true){
let letVariable = 'This is let';
let letVariable = 'This is let again';
// let variable can't re-define but we can re-assign value
console.log(letVariable); // let letVariable = 'This is let again';^SyntaxError: Identifier 'letVariable' has already been declared
}
console.log(letVariable); //ReferenceError: letVariable is not defined
// const variable can't re-define and re-assign value
// const is a block scope ***
if(true){
const constVarible = {
name: 'JavaScript',
age: '25 years',
};
constVarible.name = 'JS';
console.log(constVarible) // {name: 'JS',age: '25 years'} <= we can update const variable declared object
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us