Difference between declaring with var or Let in javascript?

Asked

Viewed 29 times

0

Hi, my first post here. I’m starting to study javascript and I came up with a question between when to declare a variable with var or Let.

I’ll use a conditional code as an example:

let idade = 19;
let acesso = '';

if (idade < 16) {
  acesso = 'proibido';
} else if (idade >= 16 && idade <= 18) {
  acesso = 'permitido somente quando acompanhado por um maior de idade';
} else {
  acesso = 'permitido';
console.log(acesso)
}


if (idade < 10) {
  acesso = 'proibido';
} else if (idade >= 11 && idade <= 15) {
  acesso = 'permitido';
} else {
  acesso = 'proibido maiores de 18';
console.log(acesso)
}

What I understood about var and Let is that when I want a variable to be global we use var, and when we want to use the variable only in a block we use Let.

I think it is not very clear to me what a block is and why I have the question. I thought that a block would be between brackets {}, in the case of this code, I thought that the variables declared with Let at the beginning would only serve for the first case and in the second case would error, for not having declared variables, since they are in separate brackets.

  • Does this answer your question? https://answall.com/questions/206117/var-constou-let-qual-use

  • This answers your question? var, const or Let? Which to use?

  • The problem with your case is that you declared let in general scope, not within a block ( between { and }, like you said)

  • 1

    Thanks @Rafaeltavares, I totally get it! I don’t know how to vote on your reply but thank you!

  • There’s a little arrow up the side, but that wasn’t an answer, that’s a rs comment. No problem :)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.