Introduction
Functions are reusable code blocks designed to perform a particular task.
Functions are executed when they are called or invoked.
Functions are fundamental in all programming languages.
Functions are defined with the function keyword:
followed by the function name
followed by parentheses ( )
followed by brackets { }
The function name follows the naming rules for variables.
Optional parameters are listed inside parentheses: ( p1, p2, ... )
Code to be executed is listed inside curly brackets: { }
Functions can return an optional value back to the caller.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Why Functions?
Functions enable better code organization and efficiency.
With functions you can reuse the same code many times.
The same code, with different input, can produce different results.
Invoking JavaScript Functions
A JavaScript function runs when it is called.
To call a function, write the name followed by parentheses like name().
Example:
function sayHello() {
return "Hello World";
}
let greeting = sayHello();
Calling vs Referencing a Function
This is an important difference:
sayHello refers to the function itself. It returns the function.
sayHello() refers to the function result. It returns the result.
JavaScript Function Return
A function can return a value back to the code that called it.
The return statement is used to send a value out of a function
JavaScript Function Parameters
Parameters allow you to pass (send) values to a function.
Parameters are listed inside the parentheses in the function definition.
Functions with One Parameter
function sayHello(name) {
return "Hello " + name;
}
let greeting = sayHello("John");
Functions with Multiple Parameters
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
let name = fullName("John", "Doe");
JavaScript Function Arguments
Parameters vs. Arguments
In JavaScript, function parameters and arguments are distinct concepts:
Parameters are the names listed in the function definition.
Arguments are the real values passed to, and received by the function.
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
In this
a and b are parameters
4 and 5 are arguments
The argument 4 is assigned to the parameter a.
The argument 5 is assigned to the parameter b
Top comments (0)