JavaScript Functions
A JavaScript function is a block of code designed to perform a specific task. Functions are executed when they are called (invoked).
Functions help make code reusable, organized, and easier to manage.
Basic Function Example
A function is defined using the function keyword, followed by a name and parentheses.
Example
Try this code
Function with Parameters
Functions can take parameters (inputs) to work with different values.
Example
Try this code
Function with Return Value
A function can return a value using the return keyword.
Example
Try this code
Why Use Functions?
- They reduce code repetition
- They make code easier to read
- They help organize programs
- They allow reuse of logic
Function Naming Rules
- Use meaningful names (e.g., calculateSum)
- Names can contain letters, numbers, _ and $
- Names should not start with numbers
- Use camelCase for better readability
Calling a Function
A function runs when it is called. You can call it by writing its name followed by parentheses.
Example
Try this code