Next →

Functions and Scope in JavaScript

Functions are reusable blocks of code designed to perform a particular task. They help make your code modular and organized.

Defining a Function

You can define a function using the function keyword:

function greet(name) {
	return "Hello, " + name + "!";
}

Calling greet("Alice") will return "Hello, Alice!".

Function Parameters and Return Values

Functions can take inputs (parameters) and return outputs.

Understanding Scope

Scope determines where variables are accessible.

Example:

function testScope() {
	let localVar = "I'm local";
	console.log(localVar); // works
}
console.log(localVar); // error — localVar is not defined

Why Scope Matters

Proper use of scope helps prevent naming conflicts and bugs.