Welcome to Lesson 7! Functions and scope are foundational concepts in JavaScript that allow you to write modular, reusable, and organized code. Functions encapsulate logic, allowing you to perform tasks multiple times without rewriting code, while scope determines the accessibility of variables within different parts of your program.
Let’s start with functions. A function is a block of code designed to perform a specific task. Functions can take input values, called parameters, perform operations, and return results. A basic function looks like this:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
Functions can also return values, which allows them to be used in expressions or stored in variables:
function add(a, b) {
return a + b;
}
let sum = add(5, 3); // sum is 8
Modern JavaScript also supports arrow functions, which provide a shorter syntax:
const multiply = (a, b) => a * b;
let result = multiply(4, 5); // 20
Functions can also be assigned to variables, passed as arguments to other functions (callbacks), and returned from other functions, enabling higher-order programming:
function greetUser(callback) {
let name = prompt("Enter your name:");
callback(name);
}
greetUser(name => console.log("Welcome, " + name));
Scope in JavaScript refers to the accessibility of variables. Variables defined inside a function are in local scope and are inaccessible outside that function. Variables defined outside any function are in global scope and can be accessed anywhere:
let globalVar = "I am global";
function showLocalVar() {
let localVar = "I am local";
console.log(globalVar); // accessible
console.log(localVar); // accessible
}
console.log(globalVar); // accessible
console.log(localVar); // Error: localVar is not defined
JavaScript also has block scope using let and const. Variables declared with var are function-scoped and can lead to unintended behavior:
{
let x = 10;
const y = 20;
var z = 30;
}
console.log(x); // Error
console.log(y); // Error
console.log(z); // 30
Closures are a powerful concept related to scope. A closure is created when a function remembers variables from its outer scope, even after the outer function has executed:
function outer() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
let counter = outer();
counter(); // 1
counter(); // 2
Understanding closures is essential for managing private data and creating functions with memory. They are commonly used in callbacks, event handlers, and module patterns.
Another important topic is function hoisting. In JavaScript, function declarations are hoisted to the top of their scope, which means they can be called before they are defined in the code. Function expressions, however, are not hoisted:
sayHello(); // Works
function sayHello() {
console.log("Hello!");
}
sayHi(); // Error
const sayHi = function() {
console.log("Hi!");
};
Functions are essential for abstraction. By creating well-named functions, you can hide complex logic behind simple calls, making your code readable and maintainable. Examples include calculating totals, validating input, and manipulating arrays.
Practice exercises include creating a simple calculator with separate functions for addition, subtraction, multiplication, and division; writing functions to manipulate arrays; or using closures to maintain counters or private state.
By the end of this lesson, you should be able to:
- Create and call functions with parameters and return values
- Understand and apply scope, including local, global, and block scope
- Work with closures and understand their practical applications
- Differentiate between function declarations and expressions
- Use functions to organize and modularize your code
Next, we will explore Arrays & Objects, which allow you to store and manage collections of data efficiently, an essential skill for building real-world applications.