Function (Custom & Inbuilt)
Learn how to create custom JavaScript functions and use inbuilt functions to write reusable and clean code.
What is a JavaScript Function?Link to this section
A function is a block of reusable code designed to perform a specific task. It executes when something invokes it, such as when your code calls its name.
This function takes a name and prints a greeting.
- `function` is the keyword used to declare a function
- `greetUser` is the **name** of the function
- `(name)` is the **parameter** container
- `{ ... }` is the **body** containing the executable code
Functions are used to organize code into logical blocks and avoid writing the same code multiple times.
Why Do We Need JavaScript Functions?Link to this section
Functions help us write modular and maintainable code by keeping repetitive logic in a single place.
- Calculate shop bills for multiple customers without repeating math formulas
- Validate user login details during sign-in and checkout
- Format prices with currency symbols across an e-commerce website
- Compute student marks and grades at the end of a term
- Display pop-up notifications with different text messages
- Convert temperatures from Celsius to Fahrenheit in weather apps
This function computes a 5 percent tax on any given price.
Instead of writing the tax calculation formula every time an item is priced, we call the calculateTax function.
About JavaScript FunctionsLink to this section
Functions work by accepting inputs called parameters, processing them, and optionally returning an output using the return keyword. They can be built into JavaScript language by default or written manually by developers as custom functions. Proper naming conventions and scope understanding are essential for writing bug-free functions.
| Function Type | Source | Example |
|---|---|---|
| Inbuilt Function | Provided by JavaScript | Math.sqrt(16) |
| Custom Function | Written by Developer | function sayHi() {} |
This function returns a value which is then stored in a variable.
Types and Forms of JavaScript FunctionsLink to this section
1. Function DeclarationLink to this section
A function declaration defines a named function using the function keyword. These functions are hoisted, meaning you can call them before they appear in the code.
note
2. Function ExpressionLink to this section
A function expression stores an anonymous function inside a variable. These are not hoisted, so they cannot be called before they are defined.
warning
3. Arrow FunctionLink to this section
Arrow functions provide a shorter syntax for writing functions using the fat arrow syntax. They are very popular in modern JavaScript development.
tip
4. Inbuilt String FunctionsLink to this section
JavaScript comes with many built-in methods for strings, allowing you to manipulate text without writing custom logic.
note
5. Inbuilt Math FunctionsLink to this section
The Math object provides inbuilt functions to perform mathematical operations easily.
tip
Parameters and Default ValuesLink to this section
Functions can accept multiple parameters. You can assign default values so that if an argument is missing, the default is used instead of returning undefined.
tip
Complete Coding ExampleLink to this section
This complete program calculates the final price of an item including tax using a custom function with default parameters.
This script combines custom functions, parameters, default values, and return statements to solve a real-world e-commerce calculation.
Important NotesLink to this section
- Functions help keep your code DRY, which stands for Don't Repeat Yourself.
- Parameters are variables listed inside the function definition parentheses.
- Arguments are the actual values passed to the function when it is called.
- The return statement stops function execution and sends a value back.
- If a function does not have a return statement, it returns undefined by default.
- Function declarations are hoisted, but function expressions are not.
- Arrow functions provide a concise syntax for writing short functions.
- Inbuilt functions like Math and String methods save time and effort.
- Variables declared inside a function are local to that function and cannot be accessed outside.
- Always use descriptive names for your custom functions.
SummaryLink to this section
In this lesson, you learned how JavaScript functions allow you to write reusable blocks of code. We explored custom function declarations, expressions, arrow functions, and inbuilt methods. Mastering functions is a vital step toward writing modular, professional, and efficient software.
Check Your UnderstandingLink to this section
Which keyword is used to define a custom function in JavaScript?
Practice ChallengesLink to this section
1. Greeting Generator
Write a custom function named sayHello that takes a name as a parameter and prints Hello [Name]! to the console.
Expected output
Hello Alice!Hint: Use string concatenation inside console.log.
2. Square Calculator
Create an arrow function that accepts a number and returns its square value.
Expected output
25Hint: Multiply the number by itself inside the arrow function.
3. Discount Applier
Write a function that takes a price and a discount percentage, then calculates and returns the discounted price.
Expected output
80Hint: Subtract the discount amount from the original price.
4. Grade Evaluator
Create a function that takes a student's score and returns 'Pass' if the score is 50 or higher, and 'Fail' otherwise.
Expected output
PassHint: Use an if-else statement inside the function.
5. Random Password Length
Write a function that returns a random whole number between 1 and 10 using inbuilt Math functions.
Expected output
A random number between 1 and 10Hint: Combine Math.random() and Math.floor().
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion