JavaScriptFunction & Objects

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 TypeSourceExample
Inbuilt FunctionProvided by JavaScriptMath.sqrt(16)
Custom FunctionWritten by Developerfunction 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

Function declarations are hoisted to the top of their scope, allowing you to invoke them before their actual line of definition.

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

Trying to call a function expression before its definition will throw a TypeError.

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

If an arrow function contains only a single return statement, you can omit the curly braces and the return keyword for cleaner code.

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

Inbuilt functions save time by providing tested solutions for common operations like searching, slicing, and changing case.

5. Inbuilt Math FunctionsLink to this section

The Math object provides inbuilt functions to perform mathematical operations easily.

tip

Use Math.floor combined with Math.random to generate random whole numbers for games or lotteries.

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

Always provide sensible default parameters to prevent unexpected NaN or undefined errors in your calculations.

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

Javascript Function (Custom & Inbuilt) quiz
Question 1 of 6

Which keyword is used to define a custom function in JavaScript?

Practice ChallengesLink to this section

1. Greeting Generator

easy

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

easy

Create an arrow function that accepts a number and returns its square value.

Expected output

25

Hint: Multiply the number by itself inside the arrow function.

3. Discount Applier

medium

Write a function that takes a price and a discount percentage, then calculates and returns the discounted price.

Expected output

80

Hint: Subtract the discount amount from the original price.

4. Grade Evaluator

medium

Create a function that takes a student's score and returns 'Pass' if the score is 50 or higher, and 'Fail' otherwise.

Expected output

Pass

Hint: Use an if-else statement inside the function.

5. Random Password Length

hard

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 10

Hint: Combine Math.random() and Math.floor().

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion