JavaScript Function Declaration & Invocation Example
Direct Answer & Overview
A JavaScript function declaration defines a reusable, parameterized subroutine using the function keyword. In JavaScript, functions are first-class values that can be assigned to variables, passed as arguments, and returned from other functions.
JavaScript Source Code
function add(a, b) {
return a + b;
}
console.log(add(10, 20));How does this JavaScript code work?
Functions are the primary building blocks of modular JavaScript applications. Declaring a function with the `function` keyword creates an invocable object bound to the surrounding lexical scope. Function declarations are hoisted completely to the top of their enclosing scope, allowing them to be called before their syntactic declaration line. When invoked with arguments, parameter variables are initialized within the local execution frame, and the `return` statement terminates execution while passing a value back to the caller.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
30Common mistakes to avoid
- !Omitting the return statement, causing the function invocation to silently evaluate to undefined.
- !Passing fewer arguments than formal parameters without default values, setting unsupplied parameters to undefined.
- !Confusing function reference passing (add) with immediate function invocation (add(10, 20)).
- !Declaring duplicate functions with the same identifier in the same scope, silently overwriting earlier implementations.
Frequently Asked Questions
What is function hoisting in JavaScript?
Function declarations are hoisted in their entirety to the top of their scope during compilation. This means you can invoke a declared function earlier in the source file than its definition line.
What happens if a JavaScript function has no return statement?
If a function finishes executing without hitting an explicit return statement, it implicitly returns undefined to the calling expression.
What is the difference between a parameter and an argument?
Parameters are the named identifier placeholders defined in the function signature. Arguments are the actual concrete values passed into the function when it is invoked.
Can a JavaScript function return multiple values?
A JavaScript function can only return a single value, but that value can be an array or an object containing multiple properties, which can then be unpacked using destructuring.
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full functions tutorial →