I don't get the answer for the question ,what will happen if i give like this? can anyone explain me please.Thanks in advance..
{
var x=10;
var y=10;
var sum;
sum=x+y;
}
console.log(sum);
I don't get the answer for the question ,what will happen if i give like this? can anyone explain me please.Thanks in advance..
{
var x=10;
var y=10;
var sum;
sum=x+y;
}
console.log(sum);
Wrapping code in curly braces creates a plain block. It's like a for
loop which only runs once.
{
// insert code here
}
is exactly equivalent to (assuming the variable i
doesn't get used anywhere other than in the for loop declaration):
for (let i = 0; i < 1; i++) {
// insert code here
}
This can affect variable scoping if you're using const
and let
, which have block scope, rather than function scope.
{
// declared with const; is not visible outside of block
const foo = 'foo';
}
console.log(foo);
With your code, though, all the variables are declared with var
, so they have function (or, here, global) scope, so putting the code into a block has no effect - x
, y
, and z
are global regardless.
As you have wrapped your code in curly braces it acts as plain block. since you have used 'var' for x, y and sum variables there is no effect for scoping. but if you use 'let' for x, y and sum variables then it will give following console error.
"Uncaught ReferenceError: sum is not defined"
In this case there is no effect x,y and sum acting as global.
This is the expected behavior of javascript. It happens because of Hoisting, anything declared with var it is hoisted at the top of the script file.
You should see this https://developer.mozilla.org/en-US/docs/Glossary/Hoisting