Functions
Prerequisites: Variables
A function is a reusable, named block of code that performs a specific task — written once, called as many times as needed.
Syntax
function functionName(parameter) {
// ...
}
Example
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Ada");
greet("Grace");
Expected output
Hello, Ada!
Hello, Grace!
A parameter can have a default value: function greet(name = "there").
Common mistakes
- Forgetting the parentheses when calling a function —
greetrefers to the function itself,greet("Ada")actually runs it.