Lesson 5: Functions and Scope

“Write modular, reusable, and maintainable blocks of JavaScript code.”

Lesson 5: Functions and Scope

What is a Function?

A [function] is a self-contained block of instructions designed to perform a specific task. Functions allow us to write a piece of code once and reuse it across our application instead of repeating ourselves.

To learn more, check the official reference on MDN Functions Guide.

---

Declaring and Calling Functions

To build a standard function, we use the function keyword, followed by a name, parentheses for inputs (parameters), and curly braces encapsulating the operation.

function greetUser(firstName) {
return Hello, ${firstName}! Welcome back.;
}

// Executing (calling) the function
let greeting = greetUser("John");
console.log(greeting);

#### Visual Output Demonstration:
Hello, John! Welcome back.

---

Modern Syntax: Arrow Functions

ES6 introduced a shorter, cleaner way to write functions using [arrow functions].

#### Code Example: Converting standard to arrow function
// Standard Function:
function multiply(a, b) {
return a * b;
}

// Arrow Function alternative:
const multiplyArrow = (a, b) => a * b;

console.log(multiplyArrow(6, 7));

#### Visual Output Demonstration:
42

*Note: Arrow functions with single-expression bodies feature implicit returns, meaning you don't even need the return keyword!*

---

Scope: Global vs. Local

[Scope] refers to the accessibility of variables in different parts of your code. JavaScript has global scope, function scope, and block scope.

#### Code Example: Visualizing Scope Barriers
let globalMessage = "I am visible everywhere!";

function showScopes() {
let localMessage = "I am only visible inside this function.";
console.log(globalMessage); // Accessing global scope works!
console.log(localMessage); // Accessing local scope works!
}

showScopes();

console.log(globalMessage);
// console.log(localMessage); // Error: localMessage is not defined

#### Visual Output Demonstration:
I am visible everywhere!
I am only visible inside this function.
I am visible everywhere!

---

Frequently Asked Questions (FAQs)

#### Q1: What is the difference between parameters and arguments?
* Parameters are the placeholders defined in the function declaration (e.g., firstName inside function greetUser(firstName)). Arguments are the actual values passed to the function when you call it (e.g., "John" in greetUser("John")).

#### Q2: What is block scope?
* Block scope limits variables declared with let or const to the curly braces {} they are defined inside (like an if statement or a loop). They cannot be accessed outside of those braces.

#### Q3: What is a callback function?
* A [callback function] is a function passed into another function as an argument. The outer function then executes the callback to complete an operation or respond to an event.

Shanawar AliFounder and developer at S Pro Coder, sharing practical coding and technology guides.