Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

Scope of variables

Welcome to the third lesson of Module 2! In this journey, you will unravel the secrets of variable scope in functions, a crucial topic to understand how variables behave inside and outside functions, ensuring the organization and proper functioning of your code.

Global Scope

Variables declared outside any function have global scope.

They can be accessed and modified anywhere in the code, but we must be cautious about potential conflicts or pollution of the global scope.

Imagine a mailbox on a busy street. Anyone passing by can access or leave mail in the box.

Local Scope

Variables declared inside a function have local scope.

They can only be accessed within the function where they were declared. Outside the function, these variables are not visible.

Now, imagine a drawer with a lock inside a house. Only people inside the house have access to the drawer and its contents.

Let’s look at a practical example. Suppose we have a variable named “message” declared outside any function.

Next, we create a function “displayMessage” that prints the value of that variable. Inside the function, we can access and display the message normally.

Example:

let message = "Hello, world!"; // Global scope
function displayMessage() {
  let message2 = "Hello, Python!" // Local scope
  console.log(message); // Access to the global scope variable
}
displayMessage(); // Output: Hello, world!

Challenge:

  1. Create a JavaScript script that prompts the user for two numbers.
  2. Create a function to calculate the sum and difference between these numbers.
  3. Use variables with different scopes to store the results of the sum and difference.
  4. Display the results on the screen.

Remember:

  • Variable scope is a fundamental concept for writing organized code and avoiding errors.
  • Use the appropriate scope for each variable, according to its need for access and modification.
  • Avoid the use of global variables whenever possible, as they can make the code harder to understand and maintain.

Now that we understand the concept of variable scope, let’s move on to the next lesson: Anonymous Functions and Callbacks.

Entrar na conversa
Rolar para cima