- JavaScript Basics
- JavaScript Tutorial
- JavaScript: where to write
- JavaScript: how to display
- JavaScript: keywords
- JavaScript: comments
- JavaScript: variables
- JavaScript: operators
- JavaScript: data types
- JavaScript Conditional Statements
- JavaScript: if-else
- JavaScript: switch
- JavaScript: for loop
- JavaScript: while loop
- JavaScript: do-while loop
- JavaScript: break and continue
- JavaScript Popup Boxes
- JavaScript: alert box
- JavaScript: confirm box
- JavaScript: prompt box
- JavaScript Popular Topics
- JavaScript: functions
- JavaScript: innerHTML
- JavaScript: getElementById()
- JavaScript: getElementsByClassName()
- JavaScript: getElementsByName()
- JavaScript: getElementsByTagName()
- JavaScript: querySelector()
- JavaScript: querySelectorAll()
- JavaScript: document.write()
- JavaScript: console.log()
- JavaScript: boolean
- JavaScript: events
- JavaScript: Math object
- JavaScript: Math.random()
- JavaScript: Number()
- JavaScript: parseInt()
- JavaScript: parseFloat()
- JavaScript Arrays
- JavaScript: array
- JavaScript: find length of array
- JavaScript: add element at beginning
- JavaScript: add element at end
- JavaScript: remove first element
- JavaScript: remove last element
- JavaScript: get first index
- JavaScript: get last index
- JavaScript: reverse an array
- JavaScript: sort an array
- JavaScript: concatenate arrays
- JavaScript: join()
- JavaScript: toString()
- JavaScript: from()
- JavaScript: check if value exists
- JavaScript: check if array
- JavaScript: slice an array
- JavaScript: splice()
- JavaScript: find()
- JavaScript: findIndex()
- JavaScript: entries()
- JavaScript: every()
- JavaScript: fill()
- JavaScript: filter()
- JavaScript: forEach()
- JavaScript: map()
- JavaScript Strings
- JavaScript: string
- JavaScript: length of string
- JavaScript: convert to lowercase
- JavaScript: convert to uppercase
- JavaScript: string concatenation
- JavaScript: search()
- JavaScript: indexOf()
- JavaScript: search() vs. indexOf()
- JavaScript: match()
- JavaScript: match() vs. search()
- JavaScript: replace()
- JavaScript: toString()
- JavaScript: String()
- JavaScript: includes()
- JavaScript: substr()
- JavaScript: slice string
- JavaScript: charAt()
- JavaScript: repeat()
- JavaScript: split()
- JavaScript: charCodeAt()
- JavaScript: fromCharCode()
- JavaScript: startsWith()
- JavaScript: endsWith()
- JavaScript: trim()
- JavaScript: lastIndexOf()
- JavaScript Date and Time
- JavaScript: date and time
- JavaScript: Date()
- JavaScript: getFullYear()
- JavaScript: getMonth()
- JavaScript: getDate()
- JavaScript: getDay()
- JavaScript: getHours()
- JavaScript: getMinutes()
- JavaScript: getSeconds()
- JavaScript: getMilliseconds()
- JavaScript: getTime()
- JavaScript: getUTCFullYear()
- JavaScript: getUTCMonth()
- JavaScript: getUTCDate()
- JavaScript: getUTCDay()
- JavaScript: getUTCHours()
- JavaScript: getUTCMinutes()
- JavaScript: getUTCSeconds()
- JavaScript: getUTCMilliseconds()
- JavaScript: toDateString()
- JavaScript: toLocaleDateString()
- JavaScript: toLocaleTimeString()
- JavaScript: toLocaleString()
- JavaScript: toUTCString()
- JavaScript: getTimezoneOffset()
- JavaScript: toISOString()
- JavaScript Regular Expression
- JavaScript: regular expression
- JavaScript: RegEx . (dot)
- JavaScript: RegEx \w and \W
- JavaScript: RegEx \d and \D
- JavaScript: RegEx \s and \S
- JavaScript: RegEx \b and \B
- JavaScript: RegEx \0
- JavaScript: RegEx \n
- JavaScript: RegEx \xxx
- JavaScript: RegEx \xdd
- JavaScript: RegEx quantifiers
- JavaScript: RegEx test()
- JavaScript: RegEx lastIndex
- JavaScript: RegEx source
- JavaScript Programs
- JavaScript Programs
JavaScript Function (with Examples)
The development of websites has been revolutionized by the flexible programming language JavaScript. Functions are a crucial component of the JavaScript programming language, whether you're creating a straightforward website or a sophisticated web application. Code can be packaged up, made reusable, and better organized overall with the help of functions.
This post is published to cover the following information regarding the function in JavaScript:
- What is a function in JavaScript
- How to Create and Define a Function in JavaScript
- How to Execute a Function in JavaScript
- JavaScript Function Return Value
- Why do we need a Function in JavaScript
- JavaScript Function Examples
- JavaScript Function with 1 Parameter Example
- JavaScript Function with 2 Parameters Example
- JavaScript Function with 3 Parameters Example
What is a Function in JavaScript?
A function in JavaScript is a block of code used to perform a defined task. For example:
function printHello() { console.log("Hello"); }
The above function named printHello() prints the Hello on the console output when it is called or invoked.
How to Create and Define a Function in JavaScript
To create and define a function in JavaScript, follow the syntax given below:
function functionName(para1, para2, para3, ..., paraN)
{
// block of code to define the function
}
where:
- function is the keyword used to define a function.
- functionName is the name of the function. To learn more about naming variables and functions, see Variable Naming Rules.
- para1, para2, para3, and paraN are the list of parameters. Parameters are optional.
For example:
function message() { document.getElementById("paraOne").innerHTML = "Hey, JavaScript is fun!"; document.getElementById("paraTwo").innerHTML = "Is not it?"; }
How to Execute a Function in JavaScript
To execute a function, we need to call it. For example:
message();
calls a function named message(). For example:
<!DOCTYPE html> <html> <body> <p id="paraOne"></p> <p id="paraTwo"></p> <script> function message() { document.getElementById("paraOne").innerHTML = "Hey, JavaScript is fun!"; document.getElementById("paraTwo").innerHTML = "Is not it?"; } message(); </script> </body> </html>
JavaScript Function Return Value
The return statement, or keyword, is used to return a value from a function after executing it. For example:
function cube(num) { return num*num*num; }
return the cube of num. Therefore, whatever the value we passed to the function named cube(), its cube will be returned. For example:
<!DOCTYPE html> <html> <body> <p>Cube of 5 = <span id="res"></span></p> <script> function cube(num) { return num*num*num; } document.getElementById("res").innerHTML = cube(5); </script> </body> </html>
Cube of 5 =
The value 5 from cube(5) is initialized or copied to num (the parameter of the cube() function), and using the return statement or keyword, the value of num*num*num, which will be 5*5*5 or 125, will be returned. Therefore, the following statement from the above (previous) example:
document.getElementById("res").innerHTML = cube(5);
will become:
document.getElementById("res").innerHTML = 125;
Wherever the return statement occurs in a function, the execution of the function will be terminated. For example:
<!DOCTYPE html> <html> <body> <p id="paraOne"></p> <p id="paraTwo"></p> <script> function message() { document.getElementById("paraOne").innerHTML = "Hey, JavaScript is fun!"; return; document.getElementById("paraTwo").innerHTML = "Is not it?"; } message(); </script> </body> </html>
That is, all the blocks of code available after the return statement in a function will be skipped to execute.
Why do we need a function in JavaScript?
We need a function in JavaScript to wrap some blocks of code in a function so we can use them multiple times. That is, we need a function to execute some block of code or statement multiple times, or the required number of times, without writing that block of code multiple times. For example:
<!DOCTYPE html> <html> <body> <p>Cube of 8 = <span id="resOne"></span></p> <p>Cube of 12 = <span id="resTwo"></span></p> <p>Cube of 33 = <span id="resThree"></span></p> <script> function cube(num) { return num*num*num; } document.getElementById("resOne").innerHTML = cube(8); document.getElementById("resTwo").innerHTML = cube(12); document.getElementById("resThree").innerHTML = cube(33); </script> </script> </body> </html>
Cube of 8 =
Cube of 12 =
Cube of 33 =
The code to calculate the cube of a number is created once and used three times. This is how the use of functions benefits us.
Please note: A variable defined inside a function is local to the function where it is defined.
JavaScript Function Examples
Now, I think it is time to give some examples regarding the function in JavaScript to clear up all the remaining doubts. Let me start with a function without parameters.
JavaScript Function without Parameter Example
<!DOCTYPE html> <html> <body> <script> function codescracker() { console.log("My name is Justin"); console.log("I'm from 'St. Louis, USA'"); console.log("I'm here since last 4 years."); } codescracker(); </script> </body> </html>
The snapshot given below shows the sample output produced by the above JavaScript function, for example:
JavaScript Function with One Parameter Example
<!DOCTYPE html> <html> <body> <p>∛64 = <span id="res"></span></p> <script> function codescracker(num) { return Math.cbrt(num); } document.getElementById("res").innerHTML = codescracker(64); </script> </body> </html>
∛64 =
JavaScript Function with Two Parameters Example
<!DOCTYPE html> <html> <body> <p>Gross Salary = $68400 and Tax Deduction@22%</p> <p>Actual Salary after Tax Deduction = <span id="res"></span></p> <script> function inHandSalary(totalSalary, taxPercentage) { let taxAmount = (taxPercentage*totalSalary)/100; return (totalSalary-taxAmount); } document.getElementById("res").innerHTML = inHandSalary(68400, 22); </script> </body> </html>
Gross Salary = $68400 and Tax Deduction@22%
Actual Salary after Tax Deduction =
JavaScript Function with Three Parameters Example
<!DOCTYPE html> <html> <body> <p>Principle Amount = $60000, Rate of Interest = 7.8%, Time = 4 Years</p> <p>Simple Interest based on above values = <span id="res"></span></p> <script> function si(p, r, t) { return ((p*r*t)/100); } document.getElementById("res").innerHTML = si(60000, 7.8, 4); </script> </body> </html>
Principle Amount = $60000, Rate of Interest = 7.8%, Time = 4 Years
Simple Interest based on above values =
In similar ways, you can pass as many parameters as required to the JavaScript function. It is up to you and your application's requirements.
JavaScript instanceof
The JavaScript instanceof operator is used to check whether the prototype property of a constructor appears in the prototype chain of an object or not. For example:
<!DOCTYPE html> <html> <body> <p id="xyz"></p> <script> function myFun(x, y, z) { this.x = x; this.y = y; this.z = z; } const v = new myFun(10, 20, 30); document.getElementById("xyz").innerHTML = v instanceof myFun; </script> </body> </html>
JavaScript instanceof syntax
The syntax of the instanceof operator in JavaScript is:
object instanceof constructor
It returns a boolean value (true or false).
« Previous Tutorial Next Tutorial »