JavaScript Function

You are Here:

What is Function?

A function is a collection of statements, either named or unnamed (anonymous), that can be called from elsewhere within a JavaScript program.

Functions can accept arguments, which are input values passed into the function. Within a function, those arguments passed into the function can be acted upon and the results returned to the caller of the function via a return value.

When to Use Function?

Functions are perfect when you have something that needs to happen multiple times within a program. Rather than defining the same code multiple times, you can use a function to perform that action.

Function without Arguments

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click me</button> <p id="point"></p> <script> var x = document.getElementById("point"); function myFunction(){ x.innerHTML = "You clicked."; } </script> </body> </html>

Syntax

function name(parameter1, ..., parameterN){ //code block } //or name = function(parameter1, ..., parameterN){ //code block }

Parameter Values

ValueTypeExplanation
parameter1, ..., parameterNOptionalSpecifies the values which will be passed by the function call.

Assign Function to a Variable

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click me</button> <p id="point"></p> <script> var x = document.getElementById("point"); myFunction = function(){ x.innerHTML = "You clicked."; } </script> </body> </html>

Function with Argument

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Passing value as function parameter</p> <p id="point"></p> <script> var x = document.getElementById("point"); function add(a, b){ return a+b; } x.innerText = add(5, 4); </script> </body> </html>

Passing Array as Argument

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Passing array as function parameter</p> <p id="point"></p> <script> var x = document.getElementById("point"); var arr = [1, 2, 3, 4, 5]; function sumOfArray(a){ var sum = 0; for(var i = 0; i < a.length; i++) sum += a[i]; return sum; } x.innerText = sumOfArray(arr); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author