1. What is
the difference between “Var” and “Let” keyword?
- Var is in JavaScript since beginning, but ‘let’ was introduced in ES2015/ES6.
- The variable declared with ‘let’ keyword has block scope, ie. It will be destroyed/garbage collected after the end of the block. Whereas, the variable defined with ‘var’ keyword has Function Scope i.e. it will be garbage collected after the end of the function it is defined in & not the end of any block.
- Variables defined with ‘var’ gets hoisted at the top of its function, while the variables defined with ‘let’ doesn’t get hoisted.
For
Eg. lets have this script below :
let myfunction = function ()
{
if (true)
{
var v = 2;
let w = 1;
}
console.log(v);
console.log(w);
}
myfunction();
If we run the above script, var ‘v’
will be printed because it has function scope i.e it will exist till the end of
the function it is defined in, but the value of ‘w ‘will not be printed because
it is defined using ‘let’ having only block scope.
Similarly,
if the define the above function like this below i.e
if (true)
{
console.log(v);
console.log(w);
var v = 2;
let w = 1;
}
Then
the output will be : undefined (for var 'v') and error (for 'w' as
it is not defined.)
i.e.
‘v’ is undefined because its definition gets hoisted at the top of the function
it is defined in, but its value does not gets hoisted. So it is undefined.
But
the ‘w’ gives error because neither its value nor its definition gets hoisted
over the function it is defined in i.e it doesn’t exists before its definition.
2. What is the difference between “==” and “===”
operator?
1. Both are comparison operators.
2. "==" only compares the value, not the type.
3. "===" compares both the value as well as the type.
So, if we have
if ('1' == 1) will give True because it compares only the values.
but
if ('1' === 1) will give False, because it compares value as well
as the type.
3. What is the difference between
"let" and "const" keyword?
1.
Both are used to define variables.
2.
With "const", we can not re-assign the value to variable, but we can
modify the old value i.e for eg. if we have
const
c = 1;
c
=2;
console.log(c); // then it
will cause error since we are re-assigning the value to const.
but if we have
const
c = [1,2] ;
c.push(3);
console.log(c);
//
the output is "1,2,3" , because 'c' is assigned a object here and
therfore, we can modify the value of c, but we cannot reassign it.
Also,
if we have
const
c;
c=
1;
console.log(c);
//
it will cause error, because since during declaration c is not assigned any
value so the value 'undefined ' is automatically assigned to it. and hence we
cannot re-assign it in the next line.
0 comments:
Post a Comment