Functions and Scope
In JavaScript, functions are an essential building block for organizing and reusing code. They allow you to encapsulate a set of instructions and execute them whenever needed.
A function in JavaScript can be defined using the function
keyword, followed by a name, a list of parameters (enclosed in parentheses), and a block of code (enclosed in curly braces).
Here's an example of a simple function that adds two numbers:
1function addNumbers(a, b) {
2 return a + b;
3}
4
5const result = addNumbers(3, 5);
6console.log(result); // Output: 8
In this example, we have a function called addNumbers
that takes two parameters a
and b
. It returns the sum of the two numbers. We can call this function by passing arguments 3
and 5
, and it will return the result 8
.
When a variable is declared inside a function, it has local scope, which means that it can only be accessed within that function. On the other hand, variables declared outside of any function have global scope and can be accessed from anywhere in the code.
Here's an example that demonstrates variable scope:
1function printNumber() {
2 const number = 10;
3 console.log(number); // Output: 10
4}
5
6printNumber();
7console.log(number); // Error: number is not defined
In this example, the variable number
is declared inside the printNumber
function and can only be accessed within that function. If we try to access the variable outside of the function, it will result in an error.
Understanding the concept of functions and how they impact variable scope is crucial for writing modular and maintainable JavaScript code.