Rahul
Rahul

Reputation: 1005

Can a function belong to just the block scope it is declared in?

If I declare a function inside an {...} block it is available outside the scope of the block. Can functions be attached just to block scope without using any special declarations like immediately invoked functions.

Upvotes: 0

Views: 40

Answers (2)

MinusFour
MinusFour

Reputation: 14423

Yes you can, if you make it strict.

'use strict';
{
   function myFunction(){}
}
myFunction(); //error

The reason function declarations are hoisted out is because this behavior wasn't defined early enough and implementations extended the behavior in such a way. This was fixed on ES6 but only under strict code.

A compatibility layer was offered through Annex B for non-strict code.

Upvotes: 1

Quentin
Quentin

Reputation: 943999

Function declarations are scoped in the same way as var declarations (to the function).

If you want to scope something to a block, use const or let.

You can use a function expression or arrow function to provide a value to a const or let declaration.

Upvotes: 2

Related Questions