H
H
HelloWhatsupp2020-04-14 13:40:38
JavaScript
HelloWhatsupp, 2020-04-14 13:40:38

Why is a variable declared inside a loop not considered an error?

If you declare any variable, and after it declare another variable with the same name, then there will be an error (Identifier 'max' has already been declared)

let max;
let max;

But if you declare a variable inside the loop, then no error will occur.
for (let i = 0; i < 10; i++) {
  let max;
  console.log(i);
}

Why? The loop, on the other hand, repeats the sequence of actions specified in the code block, and therefore re-declares the variable, but no error occurs.
About the question
Да, возможно вопрос глупый, но ответа в интернете я на него не нашел, поэтому прошу просто ответить на него. Спасибо

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2020-04-14
@HelloWhatsupp

let and const act up to the nearest brackets, new brackets - new context

A
Alexander Skusnov, 2020-04-14
@AlexSku

You would write what kind of language, but there are rules: curly braces define a block, and inside the block a new level of nesting and local variables, i.e. a local variable is not related to an external variable of the same name.
You can try like this:

let max;
{let max;}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question