A function is a block of code designed to perform a specific task. Instead of writing the same code again and again, you can write it once inside a function and reuse it whenever needed.
Think of a function like a machine:
You give it input (optional)
It processes the input
It gives you output (optional)
Why Use Functions?
Functions make your code:
Reusable: Write once, use many times
Cleaner: Break large code into smaller parts
Easier to debug: Problems are easier to find
More readable: Your code becomes easier to understand
How to Create a Function in JavaScript
The most common way to create a function is using the function keyword.
Example: Simple Function
Explanation:
functionis the keyword used to define a functiongreetis the function name()is where parameters go (empty here){}contains the code that runs when the function is called
To run the function, you must call it:
Output: Hello, welcome to JavaScript!
Functions with Parameters
Parameters allow you to pass data into a function.
Example:
Explanation:
nameis a parameterWhen you call
greetUser("Kushagra"), the value is passed to the function
Output: Hello Kushagra!
Functions with Return Values
A function can return a value using the return keyword.
Example:
Explanation:
The function takes two parameters:
aandbIt returns their sum using
returnThe returned value is stored in
result
Output: 8
Function Expression
You can also store a function inside a variable.
Example:
Explanation:
The function has no name (anonymous function)
It is stored in the variable
multiplyYou call it using the variable name
Arrow Functions (Modern JavaScript)
Arrow functions provide a shorter syntax and are widely used in modern JavaScript.
Example:
Arrow functions are cleaner and easier to read, especially for small functions.
Common Mistakes Beginners Should Avoid
Forgetting to call the function using
()Misspelling the function name
Not using
returnwhen a value is neededConfusing parameters with arguments