-1

I read an article that we don't need to use var keyword anymore but I ran into a problem in my code where I could not use my variable inside an if block because I had declared it using let.

How could I solve this problem if we don't need to use var?

let elementWidth = el.getBoundingClientRect().width
let windowWidth = window.width // 400 px

if (windowWidth > elementWidth) {
    elementWidth += 200
}

console.log(elementWidth) // 400 px
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Liga
  • 3,291
  • 5
  • 34
  • 59
  • what's wrong with the code? – holydragon Feb 26 '19 at 10:39
  • I can't access elementWidth inside if block – Liga Feb 26 '19 at 10:39
  • 3
    "I can't access elementWidth inside if block" — Yes, you can. The condition just isn't true (or `elementWidth` was 200 before you added 200 to it making it 400) – Quentin Feb 26 '19 at 10:40
  • 1
    let is block scoped which means that it will only available inside the `{}` where it was declared in. `var` will also be available in other locations. You should avoid using `var` nowadays – messerbill Feb 26 '19 at 10:40
  • Possible duplicate of [let vs var performance](https://stackoverflow.com/questions/37016466/let-vs-var-performance) – Devsi Odedra Feb 26 '19 at 10:41
  • 2
    Not a duplicate of either of those. The question is about a specific bug but there is no [mcve] to use to reproduce it. – Quentin Feb 26 '19 at 10:42

1 Answers1

0

"let" variable will not change the values outside of block scope as if, for statement

for( let j = 0; j < 3; j++ ) {
    console.log(i);// i = 3
};
console.log(j); //undefined

"var" is for function scope, a global scope like

    for( var i= 0; i < 3; i++ ) {
    console.log(i);
};
console.log(i);// i = 3

for more https://edgecoders.com/function-scopes-and-block-scopes-in-javascript-25bbd7f293d7

LikaBoss
  • 1
  • 3