Function Scope

Function Scope

Having a hard time understanding function scope? I had, this is how I figured it out and now I am sharing it with you people.

ยท

2 min read

What is Function?

When we wrap a bunch of code in braces {code} so that we could use it as per our need. By simply calling the function name. It is not necessary for a function to have a name.

function sum( a, b ) {
         return a + b;
}

In the above example, the sum is the name of the function, a and b are parameters passed in and return is what function would give you back when called. So let's call our sum ( ) with arguments 4, 6

sum( 4, 6 ) // 10

What is Scope?

In general, scope means looking at something carefully. Here, the scope is the address of a variable. Now let us see an example of Function Scope!

function warden( ) {
       let prisoner = "I am in prison ๐Ÿ˜ญ";
       return prisoner;
}
let prisonerOne = "I am free ๐Ÿ˜Š";

When we call the function warden ( ) the variable prisoner is returned to us I am in prison ๐Ÿ˜ญ but not prisonerOne because the function warden( ) do not know anything about prisonerOne. Just for understanding purpose { } curly braces are the boundaries of prison. Anything defined inside braces would be part of the prison and would be only accessible by warden( )

When we call the variable prisonerOne we get I am free ๐Ÿ˜Š but when we call the variable prisoner we get an error.

Uncaught ReferenceError: prisoner is not defined

This is because the variable prisoner is scoped to the function warden( ). The variable that is scoped to the function cannot be accessed outside the function.

If you read till here, thank you. Hope this blog helped you understanding Function Scope

ย