The Wayback Machine - https://web.archive.org/web/20240906181940/https://www.geeksforgeeks.org/how-to-write-a-function-in-javascript/
Open In App

How to write a function in JavaScript ?

Last Updated : 15 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance code organization and maintainability.

Functions are one of JavaScript’s core building elements. In JavaScript, a function is comparable to a procedure—a series of words that performs a task or calculates a value—but for a process to qualify as a function, it must accept some input and produce an output with a clear link between the input and the result. To utilize a function, it must be defined in some place within the scope from which it will be called.

Function Definition

A Function Definition or function statement starts with the function keyword and continues with the following.

  • Function’s name.
  • A list of function arguments contained in parenthesis and separated by commas.
  • Statements are enclosed in curly brackets.

Syntax:

function name(arguments)
{
   javascript statements
}

Function Calling:

Function Calling at a later point in the script, simply type the function’s name. By default, all JavaScript functions can utilize argument objects. Each parameter’s value is stored in an argument object. The argument object is similar to an array. Its values may be accessed using an index, much like an array. It does not, however, provide array methods.  

JavaScript
function welcome() {
    console.log("welcome to GfG");
}

// Function calling
welcome();

Output
welcome to GfG

Function Arguments:

A function can contain one or more arguments that are sent by the calling code and can be utilized within the function. Because JavaScript is a dynamically typed programming language, a Function Arguments can have any data type as a value.

JavaScript
function welcome(name) {
    console.log("Hey " + "" + name + " " + "welcome to GfG");
}

// Passing arguments
welcome("Rohan");

Output
Hey Rohan welcome to GfG

Return Value:

A return statement is an optional part of a JavaScript function. If you wish to return a value from a function, you must do this. Return Value should be the final statement of a function.

JavaScript
function welcome() {

    // Return statement
    return "Welcome to GfG";
}

console.log(welcome());

Output
Welcome to GfG

Function Expression:

We may assign a function to a variable and then utilize that variable as a function in JavaScript. Function Expression is known as a function expression.

JavaScript
let welcome = function () {
    return "Welcome to GfG";
}

let gfg = welcome();

console.log(gfg);

Output
Welcome to GfG

Types Of Functions in JavaScript

1. Named function:

A Named function is one that we write in code and then use whenever we need it by referencing its name and providing it with some parameters. Named functions come in handy when we need to call a function several times to give various values to it or run it multiple times.

JavaScript
function add(a, b) {
    return a + b;
}
console.log(add(5, 4));

Output
9

2. Anonymous function:

We can define a function in JavaScript without giving it a name. This nameless function is referred to as the Anonymous function. A variable must be assigned to an anonymous function.

JavaScript
let add = function (a, b) {
    return a + b;
}
console.log(add(5, 4));

Output
9

3. Nested Functions:

A function in JavaScript can contain one or more inner functions. These Nested Functions fall within the purview of the outer function. The inner function has access to the variables and arguments of the outer function. However, variables declared within inner functions cannot be accessed by outer functions.

JavaScript
function msg(firstName) {
    function hey() {
        console.log("Hey " + firstName);
    }

    return hey();
}

msg("Ravi");

Output
Hey Ravi

4. Immediately invoked function expression:

The browser executes the invoked function expression as soon as it detects it. Immediately invoked function expression has the advantage of running instantly where it is situated in the code and producing direct output. That is, it is unaffected by code that occurs later in the script and can be beneficial.

JavaScript
let msg = (function() {
    return "Welcome to GfG" ;
})();
console.log(msg);

Output
Welcome to GfG


Previous Article
Next Article

Similar Reads

How to write a function that returns array elements larger than a number in JavaScript ?
Given an array arr and number n and the task is to write a function that returns an array whose items are larger than n. Example: Input: arr = [65, 16, 0, 6, 64, 1, 68] n = 16 Output: [65, 64, 68] Input: arr = [6, 46, 54, 6, 56, 54, 65, 4, 65] n = 50 Output: [54, 56, 54, 65, 65] To achieve this we have the following approaches : Approach 1: Using A
4 min read
How to write a simple code of Memoization function in JavaScript ?
Memoization is a programming technique that we used to speed up functions and it can be used to do whenever we have an expensive function ( takes a long time to execute). It relies on the idea of cache {}. A cache is just a plain object. It reduces redundant function expression calls. Let's understand how to write a simpler code of the Memoization
3 min read
How to write a program that will return true if the bottom of the page is visible in JavaScript ?
The task is to return true if the bottom of the page is visible. We can achieve this by simply using the height of the window and the height of the scrolled window. Approach: Here we will first create a function that will be called whenever you use the scroll.Now we will check whether the bottom is visible each time when the function is called usin
1 min read
How to write an inline IF statement in JavaScript ?
We can write an inline IF statement in javascript using the methods described below. Method 1: In this method we write an inline IF statement Without else, only by using the statement given below. Syntax: (a < b) && (your code here) Above statement is equivalent to if(a < b){ // Your code here } Example: Below is the implementation of
2 min read
How to write shorthand for document.getElementById() method in JavaScript ?
The task is to select the elements with id by using the shorthand for document.getElementById() with the help of JavaScript. we're going to discuss a few techniques. Approach 1:Define a function that returns the document.getElementById('idName').This method takes IDName as the first and only argument.Call the method with ID as the argument.Example:
2 min read
How to write a cell phone number in an international way using JavaScript ?
E.164 format is used to convert a phone number into an international format. It is an internationally recognized standard that defines a general numbering plan. The international number format according to E.164 is as follows: [+][country code][area code][local phone number] +: Plus sign country code: International country code. It comes after the
3 min read
Why split the <script> tag when writing it within document.write() method in JavaScript ?
The code within the script tag is executed when the browser processes the tag. The document.write() method is used to delete all the existing content from the HTML document and inserts the new content specified within document.write() method. However, before the browser loads a page it builds the DOM tree by parsing the HTML markup. Whenever a scri
2 min read
How to write a program that takes a predicate and array, like Array.filter(), but only keeps x if pred(x) === false in JavaScript ?
The predicate in JavaScript is the same as the predicate maths which returns true or false. The predicate is just like a function that determines whether the passed arguments satisfy the given condition or not. The predicate returns only true or false. In this article, let us see the working of the predicate with arrays when it is passed with a fun
3 min read
Write a program to convert an array of objects to a CSV string that contains only the columns specified using JavaScript
When we want to store multiple values in one variable then instead of a variable, we use an array. which allows you to store multiple types of data for example you could have a string, an integer, etc. In this article, we will learn to convert the array objects to CSV string data. Given array objects ( key: value ) to CSV string comma-separated val
3 min read
How to Write JavaScript Articles on GeeksforGeeks ?
GeeksforGeeks allows coding lovers to display their programming skills by writing Javascript-based articles. However, a lot of individuals (especially college students or beginners) find it challenging to describe their learnings and talents and contribute to GeeksforGeeks. But now the problem has been solved. This article will guide you through th
5 min read
Javascript Program To Write Your Own atoi()
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn) Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted
5 min read
How to write a switch statement in JavaScript?
In JavaScript, a switch statement is a control flow statement that evaluates an expression and executes code based on matching cases. It provides a more concise and readable way to handle multiple possible conditions compared to nested if...else statements. Syntax:switch (expression) { case value1: // code block to be executed if expression matches
2 min read
How to Write a While Loop in JavaScript ?
In JavaScript, a while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. Syntax:while (condition) { // code block to be executed while condition is true}The loop continues to execute the block of code within its curly braces ({}) as long as the specified condition evaluates to true.
1 min read
How to write an Alert Box in JavaScript ?
In JavaScript, you can use the alert() function to display an alert box with a message to the user. The alert box typically contains a message and an OK button, allowing the user to acknowledge the message. Syntax:alert("message");Example: Here, the alert() function is called with the message "Hello, world!". When executed in a browser environment,
1 min read
Explain about Read and Write of a file using JavaScript
Handling file operations such as reading and writing is a common requirement in many JavaScript applications, especially on the server side using Node.js. This article explains how to perform these operations using Node.js's built-in fs (File System) module. The fs ModuleThe fs module provides an API for interacting with the file system in a manner
3 min read
JavaScript Program to write data in a text File
In this article, we are going to learn how can we write data in a text file. There is a built-in Module or in-built library in NodeJs that handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for writing operations is written. Import fs-module in the program and use functions to w
3 min read
PHP | Gmagick write() Function
The Gmagick::write() function is an inbuilt function in PHP which is used to write an image to the specified filename. This is an alias of Gmagick::writeimage() function. Syntax: Gmagick Gmagick::write( string $filename ) Parameters: This function accepts a single parameter $filename which holds the name of the file. Return Value: This function ret
2 min read
Node.js GM write() Function
The write() function is an inbuilt function in the GraphicsMagick library which is used to write an image to a file. If a file already exists, then it will be overwritten. The function returns the true value of success. Syntax: write( filename ) Parameters: This function accepts single parameters as mentioned above and described below: filename: Th
2 min read
How to write asynchronous function for Node.js ?
The asynchronous function can be written in Node.js using 'async' preceding the function name. The asynchronous function returns an implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event loop. Async functions will always return a value. Await function can be used inside the asynchronous funct
2 min read
How to write a function to get rows from database by multiple columns conditionally ?
MongoDB, the most popular NoSQL database, we can get rows from the database by multiple columns conditionally from MongoDB Collection using the MongoDB collection.find() function with the help of $or or $and operators. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in Mo
2 min read
How to write a function in Typescript ?
Writing a function in TypeScript is similar to writing it in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type. Syntax: Let's see a basic TypeScript function syntax (with two arguments) function functionName(arg1: <arg1Type
4 min read
How to write Into a File in PHP ?
In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file has to close by using the PHP fclose() function. S
2 min read
How to write shortcode in WordPress ?
If you see the text in brackets, then that is the Shortcode. In this article, we learn about how to write the shortcode in WordPress. First, we discuss WordPress Shortcodes. In WordPress, there are security filters that could not allow writing any dynamic code into WordPress elements like posts, pages, and widgets. That's why for writing dynamic co
4 min read
How to write a form in different line using Bootstrap ?
Bootstrap is an open-source front-end framework for developing standard & decorative websites or web applications that are fast and user-friendly. Bootstrap includes templates based on HTML and CSS for tables, forms, buttons, etc. Bootstrap also uses JavaScript and helps us to create responsive designs. Forms are a crucial building block of eve
2 min read
How to write a:hover in inline CSS?
It is called pseudo-selector and used to select all the elements when the user move mouse over the elements. It can be used on all the element. A <!DOCTYPE html> element must be declared in the document to see the working of this selector in all the elements. Example 1: C/C++ Code <!DOCTYPE html> <html> <head> <title>a
2 min read
HTML DOM write() Method
The write() method in HTML is used to write some content or JavaScript code in a Document. This method is mostly used for testing purposes. It is used to delete all the content from the HTML document and inserts the new content. It is also used to give additional text to an output that is opened by the document.open() method. This method is quite s
2 min read
Node.js Buffer.write() Method
The Buffer.write() method writes the specified string into a buffer, at the specified position. If buffer did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written. Syntax: buffer.write( string, offset, length, encoding ) Parameters: This method accept four
2 min read
How to write ReactJS Code in Codepen.IO ?
Now everything is online, some people use VScode to write react.js code and face most of the difficulty. The VScode requires setting for writing React.js code and Many beginners faced difficulty to use VScode so, for them, it is good and easy to use codepen. The codepen provide you with an online platform to create react, HTML, CSS, and JavaScript
2 min read
Node.js Stream writable.write() Method
The writable.write() method is an inbuilt application programming interface of Stream module which is used to write some data to the Writable stream. The callback function is called once the data has been completely handled. Syntax: writable.write( chunk, encoding, callback) Parameters: This method accepts three parameters as mentioned above and de
2 min read
Node.js fs.write() Method
File-writing is an important aspect of programming. Every programming language has a well-defined file module that can be used to perform file operations. JavaScript and Node.js also have file module which provides various inbuilt methods for performing read, write, rename, delete and other operations on files. The file module of Node.js is called
4 min read