Getting Started
Functions
Functions are reusable blocks of code designed to perform specific tasks. They improve code organization, reduce repetition, and enhance maintainability.
Declaring a Function
A function is defined using the function
keyword, followed by a name, parentheses ()
, and a block of code {}
.
To execute a function, it must be called by its name with parentheses:
Function Parameters and Arguments
Functions can accept parameters (input values) and use them within their block.
Parameters are placeholders in the function definition.
Arguments are actual values passed to the function when called.
A function can have multiple parameters:
Return Statement
A function can return a value using the return
keyword.
Once
return
is executed, the function stops running.Returned values can be stored in variables for later use.
Function Expressions
Functions can be stored in variables as expressions.
Function expressions do not have a name (anonymous functions).
The function is called using the variable name.
Arrow Functions (ES6)
Arrow functions provide a shorter syntax for writing functions.
If the function has only one statement,
{}
andreturn
can be omitted.If there is only one parameter,
()
can be omitted:
Default Parameters
Functions can have default parameter values that apply when no argument is provided.
Rest Parameters (...
)
The rest parameter syntax allows a function to accept multiple arguments as an array.
The
...numbers
parameter gathers all arguments into an array.Useful when the number of arguments is unknown.
Callback Functions
A callback is a function passed as an argument to another function and executed later.
processUser
callsdone
after printing a message.Callbacks enable asynchronous programming and event handling.
Immediately Invoked Function Expressions (IIFE)
An IIFE runs immediately after it is defined.
Wrapped in parentheses to execute instantly.
Avoids polluting the global scope.
Conclusion
Functions are a fundamental part of JavaScript, allowing code reuse and modularity. The next section will explore objects and arrays, which are essential for organizing and managing data.
Join our Community Forum
Any other questions? Get in touch