Functions in JavaScript: User-Defined and Standard Library Functions

Functions in JavaScript: User-Defined and Standard Library Functions

09 Sep 2024
Beginner
508 Views
19 min read

JavaScript Functions

Functions are an essential segment of JavaScript programming. All programming languages start their basics with functions because they help developers break down complex problems into easy ones and make the code cleaner and more efficient.

In this JavaScript tutorial, we will learn about the crucial fundamentals of JavaScript functions, including function expressions, invocations, calling, return statements, and arrow functions.

Read More: JavaScript Interview Questions and Answers (Fresher + Experience)

What is a Function in JavaScript?

A function in JavaScript is a block of code written by the developer to perform a definite task, such as multiplying two numbers. It wraps a set of instructions that can be used throughout the program and is executed when it is called. By using functions, we can enhance our program's reusability and readability.

There are two types of functions in JavaScript:

  1. User-defined Functions: Created by users
  2. Standard Library Functions: Inbuilt functions in JavaScript

Here, we will look at User-defined and Standard library functions in JavaScript.

1. User-Defined Functions in JavaScript

In JavaScript, a programmer can create any function to perform any task, e.g., a function to calculate the area of a square. A user-defined function groups code to perform a specific task and that group of code is given a name (identifier). When a programmer invokes his created function in any part of the program, the body of that function executes.

There are some aspects of a user-defined function. They are

  1. Function Declaration
  2. Function Invocation
  3. Function Definition
  4. Function Parameters and Arguments
  5. Function Return

1. Function Declaration In JavaScript

To create a function in JavaScript, we should remember some essential points.

  • When creating a function in JavaScript, we should first use the function keyword.
  • After spacing, we should give the function name, which should be unique, and parameters within parenthesis ( ).
  • The body of the function is inside the curly braces { }.

Syntax of JavaScript Function

function fun_Name() {
  // code of body
}      

Example of JavaScript function

function myFunc() {
    console.log("Hello, World!");
}       

Diagram of Function Declaration In JavaScript

Explanation

Here, we have declared a function named myFunc() that prints the result Hello, World!. Each part of our function is below.

  • Function Keyword- The function keyword is used to declare or create a function.
  • Function Name- myFunc is the function name, followed by parenthesis ( ).
  • Function Body- console.log("Hello, World!") is the body of the function. It is executed when we call the function.

2. Function Invocation in JavaScript

In JavaScript, function invocation is the method to call or execute a function. You can call a function many times if you want. Function invocation happens when-

  • It is triggered by an event (when a user hits a button )
  • It is called directly by JavaScript code.
  • It also can be called by itself (self-invoked).

Syntax of Function Invocation

function fun_Name() {
  // code to be executed
}
//calling or invoking the function
fun_Name();       

Example of Function Invocation

function myFunc(){
    console.log("Hello, World!");}
// call or invoke the function
myFunc();

Output

Hello, World!

Diagram for Function Invocation in JavaScript

Explanation

In this example, we declare a function named myFunc(). Here's how the control of the program flows.

  1. When myFunc() is called, the program control follows the function definition.
  2. All the code inside the function is executed, and it prints the result: Hello, World!

3. Function Definition in JavaScript

In JavaScript, the function definition is the body of a function that contains information about the task and is executed when it is called. It is always inside the curly Braces { }.

Example of Function Definition

function myFunc() {
    console.log("Hello, World!");  // function definition
}myFunc(); 

Output

Hello, World! 

Explanation

In the above example, we have declared and called a function named myFunc(). It executes the function definition and prints the result: Hello, World!

4. Function Arguments and Parameters in JavaScript

In JavaScript,

  • A function argument is the value we pass to a function while calling it.
  • A function parameter is a variable that stores the function arguments. It is inside the parentheses and created during function declaration.

Syntax of Function Arguments and Parameter

// here name is the parameter
function func_Name(name) {
   // code of the body
}func_Name(Arguments); // function arguments      

Example of Function Argument with parameter

function myFunc(name) {// function declare with parameter
console.log(`Hello, ${name}!`);
}
myFunc('Jack'); //function call with arguments    

Output

Hello, Jack !   

Diagram for Function Argument with parameter

Explanation

In this example, we have declared a function named myFunc() with the parameter name.

  1. When myFunc is called with arguments Jack, the program controls follow the function definition.
  2. All the code inside the function is executed, and the results are printed with an argument. (E.g. Hello, Jack !)

Example - JavaScript Function with different arguments

function myFunc(name) {
    console.log(`Hello ${name}`);
}
myFunc("Amit"); // pass "Amit" as argument
myFunc("Rakesh"); // pass "Rakesh" as argument    

Output

Hello Amit 
Hello Rakesh    

Explanation

In the above example, we declared a function using the parameter myFunc(name).

  1. We called the function twice with arguments from John and David.
  2. It executed the function definition and printed Hello John and Hello David on the screen.

5. Function Return in JavaScript

In JavaScript, the function returns a definite value using the return statement. When a function executes and reaches the return statement, it stops the execution and sends the return value to the caller. If we don't use the"return" statement, the function returns 'undefined.'

Example of Function Return

// function to find square of a number
function findSqr(num) {
   // return square
    return num * num; 
}
// call the function and store the result
let square = findSqr(4);
console.log(`Square: ${square}`);     

Output

Square: 16    
Diagram for Function Return in JavaScript

Explanation

In this example, we declare a function findSqr(num) with the parameter and call the function by passing the arguments 4.

  1. After calling, the return statement is used to calculate the square of the root.
  2. Then, we store it in a square variable and print the result.

Function Expression in JavaScript

A function expression is the same as a function declaration, but we don't need to specify the function name, and it can be stored in a variable assignment.

Function Expression Syntax

let myFunction= function(param1, param2) {
// code of the body
}        

Example of Function Expression

const myFirst = function (number) {
return number * number;};
const x = myFirst(6);
console.log(x);       

Output

36   

Explanation

In this example, we declare a function with a parameter number without a function named and store it myFirst variable.

  1. After calling the function with an argument, the return statement is executed.
  2. We store the result in a variable x and print the result.

You can also compare JavaScript functions with

What is an Arrow function?

An Arrow function in JavaScript is a short method for writing a function expression. It was introduced in ECMA6(ES6). We use '=>' syntax to introduce the arrow function.

Example of Arrow Function

const sumNums = (a, b) => a + b;
// Calling the function
const result = sumNums(4,3);
console.log(result)

Output

7

Explanation

In this example, We declare a function expression with parameters a & b and add them together.
  1. Next, we call the function with arguments 4 & 3 and store it in the result variable.
  2. After that, print the output in the console.

2. Standard Library Functions in JavaScript

In JavaScript, there is an advantage in that the library provides some functions that can be directly used in the program without creating them. We need to call them using our code.
FunctionsWorking
toLowerCase()it returns the string in lowercase.
toUpperCaseIt returns the string in uppercase.
Math.sqrt()It calculates the square of a number.
Math.pow()It calculates the power of a number.
console.log()It prints the string in the quotation mark.

Example For Math.sqrt() Function

let squareRoot = Math.sqrt(3);
console.log("Square Root of 3 is", squareRoot);

Output

9

Explanation

In the above example, we have directly called the inbuilt library function Math.sqrt () with arguments 3. The log statement directly prints the result on the screen.

Summary

In this article, we discuss all the crucial aspects related to the JavaScript function. While reading this article, you won't face any difficulty, and it will help you clear your concepts quickly. For a practical understanding, consider our JavaScript Programming Course.

ScholarHat provides different types of Training and Certification Courses to help you in your end-to-end product development.

FAQs

A function in JavaScript is a block of code written by the developer to perform a definite task. It wraps a set of instructions that can be used throughout the program and is executed when it is called.

A function parameter is a variable that stores the function arguments. It is inside the parentheses and created during function declaration. While a function argument is a value, we pass to a function while calling it.

An Arrow function is a short method for writing a function expression. It was introduced in ECMA6(ES6). We use '=>' syntax to introduce the arrow function.

Take our Javascript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this