1
const phrase = 'Hello';

if (true) {
  const user = 'John';

  var sayHi = () => {
    console.log(`${phrase}, ${user}`);
  };
}

sayHi(); // Hello, John
console.log(user); // ReferenceError: user is not defined

user and sayHi both defined inside if block, but sayHi is available outside the block, in the same time user is not. Why?

Jack
  • 73
  • 1
  • 6
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Pete Sep 16 '19 at 10:15
  • And read this https://developer.mozilla.org/en-US/docs/Glossary/Scope – Pete Sep 16 '19 at 10:23
  • Thank you guys. I got it. I found this from https://javascript.info/closure#function-in-if . I think the author made an mistake, the result is not an error. It will work. – Jack Sep 16 '19 at 10:26

4 Answers4

1

Whenever you use var to define a variable, the variable is hoisted - which means its declaration is moved to the top of the current scope. However this is not true for scoped variables that are created using let/const, where the variables are only defined in the scope they were created

Gilad Bar
  • 1,302
  • 8
  • 17
0
const phrase = 'Hello';
const user = 'John';

if (true) {
  var sayHi = () => {
    console.log(`${phrase}, ${user}`);
  };
}

sayHi(); // Hello, John
console.log(user); // This will work now, this answer is similar to @Saurabh Agrawal
Veera
  • 397
  • 1
  • 4
  • 21
0

A block scope is the area within if, switch conditions or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block. In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.

In you program the user is scoped constant which is only accessible inside if block. That's that why you are getting undefined when you use outside the if block.

See this reference.

MH2K9
  • 11,951
  • 7
  • 32
  • 49
0

The variable was created using 'const' keyword inside the scope of the if statement, in simple words it was created inside the opening '{' and closing '}' so it can only be accessed inside the brackets, because 'const' and 'let' have block scope. Check out the full explanation here.

Vlad Tanasie
  • 63
  • 1
  • 10