Code Blocks for Specific Tasks: Functions
Functions
are reusable blocks of code designed to perform specific tasks.
You create a function by using one or more lines of code enclosed in curly braces { }
to form a block
, and then you give this block a name.
function sayHello() { console.log('Hello'); console.log('Nice to meet you'); }
In the example above, the function that prints the messages 'Hello' and 'Nice to meet you' is named sayHello
.
The function contains two console.log
commands within the curly braces { }
, forming a single block.
When the function is called, the code inside the function is executed, printing the messages 'Hello' and 'Nice to meet you' on separate lines.
function sayHello() { console.log('Hello'); console.log('Nice to meet you'); } sayHello(); // Hello // Nice to meet you
Why Use Functions?
The main goal of using functions is to enhance reusability of code.
Once a function is defined, it can be invoked multiple times using its name.
This reduces code duplication and improves maintainability.
How to Declare a Function
In JavaScript, functions are defined by using the function
keyword, followed by the function name and parameters.
function add(a, b) { return a + b; }
Here, add
is the name of the function, and a
and b
are its parameters.
The curly braces { }
contain the code that executes when the function is called, and the return
keyword is used to yield the function's result.
How to Call a Function
Calling a function means executing the code inside it.
To call a function, append parentheses ()
to the function’s name.
const result = add(10, 20); // 30
In this example, add(10, 20)
calls the add
function, and 10
and 20
are the arguments
passed to it.
Upon invocation, 10
and 20
are assigned to the function's parameters a
and b
, respectively, executing the code return a + b
and returning 30
.
The value 30
returned by return
is stored in the constant result
.
What's the Difference Between Parameters and Arguments?
Parameters
are variables used internally when defining a function, whereas arguments
are the actual values passed when a function is called.
function multiply(a, b) { return a * b; } const result = multiply(2, 3); // 6
For instance, in the multiply
function, a
and b
are the parameters, and the values 2
and 3
are the arguments passed during the function call.
What keyword is used to define a function in JavaScript?
def
func
function
fnc
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result