Tuesday 14 November 2017

javascript - Advantages of using let over var within a function





Say I have a piece of code like
this:



const number =
3;


function fooFunction() {
let numberTwo =
5;
var answer = number + numberTwo;
return
answer;
}

finalAnswer =
fooFunction();

console.log(finalAnswer);



Assuming
an ES2015 compatible browser, what would be the advantages/disadvantages of using the
above code, over:



const number =
3;

function fooFunction() {
var numberTwo =
5;
var answer = number + numberTwo;
return
answer;
}


finalAnswer =
fooFunction();

console.log(finalAnswer);


Are
there any advantages or disadvantages, given they both return the same
number?



Answer




As others have mentioned, in your example you
can use let and var interchangeably.
The difference is that let is block-scoped and
var is
not.




For example with
var you can do this (prints
'foo'):



data-hide="false" data-console="true">
class="snippet-code">
function printFoo(param) {
if (param)
{
var x = "foo";
}


console.log(x);

}

printFoo("hello");





You
cannot do this with let because let x
is scoped to the if block and therefore is not
defined.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...