Named Functions
Function declarations define a named function using the function keyword.
They are hoisted, so you can call them before the declaration.
JavaScript Tutorial
Function declarations define named functions with the function keyword.
They are hoisted, which means you can call them before they are defined.
Hoisted functions are convenient for organizing code and separating logic from usage.
They also produce clearer stack traces because the function has a name.
function name(params) { ... }function greet(name) {
return "Hello " + name;
}
console.log(greet("Riya"));Declare a function with a name and call it later.
console.log(add(2, 3));
function add(a, b) {
return a + b;
}Function declarations can be used before they appear in code.
Function declarations define a named function using the function keyword.
They are hoisted, so you can call them before the declaration.
Function declarations are hoisted with their bodies.
This means the function is available anywhere in its scope.
Use declarations for core, reusable logic and public APIs.
They are easier to debug because they have stable names.
function formatPrice(amount) {
return "$" + amount.toFixed(2);
}
console.log(formatPrice(99));Use declarations for reusable formatting logic.
function isAdult(age) {
if (age < 18) return false;
return true;
}
console.log(isAdult(20));Return early to keep logic simple.
Without
const add = function(a, b) {
return a + b;
};With
function add(a, b) {
return a + b;
}Only function declarations are hoisted, not expressions.
Pass data as parameters instead of relying on globals.
Keep functions small and focused.
JavaScript moves declarations to the top of their scope before execution.
Yes, both the name and body are hoisted.
They provide named, reusable functions that can be called anywhere in scope.
Practice: Write a function declaration that calculates the area of a rectangle.
// TODO: function area(width, height)
One Possible Solution
function area(width, height) {
return width * height;
}
console.log(area(5, 3));Yes, the entire declaration is hoisted.
Yes, later declarations overwrite earlier ones in the same scope.
For reusable or core functions that you want available throughout a scope.
Try calling the function before and after the declaration.