Loading lessons...
Function Basics
Function Basics
A function is a block of reusable code that runs when you call it.
Declaring a function
function sayHello() {
console.log("Hello!");
}
Calling a function
sayHello();
Every time you call it, the code inside runs again.
Why use functions?
- Reuse code instead of writing it twice.
- Keep code organized and readable.
- Make changes in one place.
- Break big problems into small pieces.
Functions with names
Functions are declared with the function keyword, a name, parentheses, and a body:
function name() {
// body
}
Function hoisting
Function declarations are hoisted, meaning you can call a function before it is declared in the file:
sayHello(); // works even though it is defined later
function sayHello() {
console.log("Hello!");
}
TL;DR
- A function is reusable code defined with
function name() { }. - Call it with
name(). - Functions keep code organized and reusable.
- Function declarations are hoisted.