Function Scope Tutorial
Hey there, coder! Welcome to our Function Scope tutorial. In this tutorial, we'll explore how variables defined outside a function can be accessed within that function.
Step 1: Create a variable outside a function
Open your index.js
file and add the following code:
let outerVariable = "I'm defined outside the function!"
This code defines a variable outerVariable
with the string value "I'm defined outside the function!"
.
Step 2: Define a function
Add the following code below the outerVariable
declaration:
function accessOuterVariable() { // We'll access the outerVariable here}
This code defines a function named accessOuterVariable
.
Step 3: Access the outer variable inside the function
Inside the accessOuterVariable
function, add the following code:
function accessOuterVariable() { console.log(outerVariable)}
This code logs the value of outerVariable
to the console.
Step 4: Run the code
Click the Run button to execute the code. Observe the console output.
What do you see in the console? That's right! The output is "I'm defined outside the function!"
. This demonstrates that the outerVariable
defined outside the function can be accessed within the accessOuterVariable
function.
Why does this work?
In JavaScript, variables defined outside a function are in the global scope. When a function is executed, it has access to all variables in the global scope. This means that the accessOuterVariable
function can "see" the outerVariable
defined outside of it.
Real-world example
Think of a scenario where you have a user's name stored in a variable outside a function. You can then use that variable inside a function to greet the user by name.
Code so far
let outerVariable = "I'm defined outside the function!"
function accessOuterVariable() { console.log(outerVariable)}
accessOuterVariable()
What's next?
In the next tutorial, we'll explore Arrow Functions, a concise way to define functions in JavaScript.
Before you go...
Take a moment to experiment with the code. Try modifying the outerVariable
value or adding more variables outside the function. See how it affects the output.
That's it for now! You've learned about Function Scope in JavaScript. Click the Run button again to see the output, and then move on to the next tutorial to learn about Arrow Functions.
Tests