- JavaScript Basics
- JS Home
- JS Syntax
- JS Placements
- JS Output
- JS Statements
- JS Keywords
- JS Comments
- JS Variables
- JS var
- JS let
- JS const
- JS var Vs let Vs const
- JS Operators
- JS Arithmetic Operators
- JS Assignment Operators
- JS Comparison Operators
- JS Logical Operators
- JS Bitwise Operators
- JS Ternary Operator
- JS Operator Precedence
- JS Data Types
- JS typeof
- JS Conditional Statements
- JS Conditional Statement
- JS if Statement
- JS if...else Statement
- JS switch Statement
- JS Loops
- JS for Loop
- JS while Loop
- JS do...while Loop
- JS break Statement
- JS continue Statement
- JS break Vs. continue
- JavaScript Popup Boxes
- JS Dialog Box
- JS alert Box
- JS confirm Box
- JS prompt Box
- JavaScript Functions
- JS Functions
- JS setTimeout() Method
- JS setInterval() Method
- JavaScript Events
- JS Events
- JS onclick Event
- JS onload Event
- JS Mouse Events
- JS onreset Event
- JS onsubmit Event
- JavaScript Arrays
- JS Array
- JS Find Length of Array
- JS Add Elements at Beginning
- JS Add Element at End
- JS Remove First Element
- JS Remove Last Element
- JS Get First Index
- JS Get Last Index
- JS Reverse an Array
- JS Sort an Array
- JS Concatenate Arrays
- JS join()
- JS toString()
- JS from()
- JS Check if Value Exists
- JS Check if Array
- JS Slice an Array
- JS splice()
- JS find()
- JS findIndex()
- JS entries()
- JS every()
- JS fill()
- JS filter()
- JS forEach()
- JS map()
- JavaScript Strings
- JS String
- JS Length of String
- JS Convert to Lowercase
- JS Convert to Uppercase
- JS String Concatenation
- JS search()
- JS indexOf()
- JS search() Vs. indexOf()
- JS match()
- JS match() Vs. search()
- JS replace()
- JS toString()
- JS String()
- JS includes()
- JS substr()
- JS Slice String
- JS charAt()
- JS repeat()
- JS split()
- JS charCodeAt()
- JS fromCharCode()
- JS startsWith()
- JS endsWith()
- JS trim()
- JS lastIndexOf()
- JavaScript Objects
- JS Objects
- JS Boolean Object
- JavaScript Math/Number
- JS Math Object
- JS Math.abs()
- JS Math.max()
- JS Math.min()
- JS Math.pow()
- JS Math.sqrt()
- JS Math.cbrt()
- JS Math.round()
- JS Math.ceil()
- JS Math.floor()
- JS Math.trunc
- JS toFixed()
- JS toPrecision()
- JS Math.random()
- JS Math.sign()
- JS Number.isInteger()
- JS NaN
- JS Number()
- JS parseInt()
- JS parseFloat()
- JavaScript Date and Time
- JS Date and Time
- JS Date()
- JS getFullYear()
- JS getMonth()
- JS getDate()
- JS getDay()
- JS getHours()
- JS getMinutes()
- JS getSeconds()
- JS getMilliseconds()
- JS getTime()
- JS getUTCFullYear()
- JS getUTCMonth()
- JS getUTCDate()
- JS getUTCDay()
- JS getUTCHours()
- JS getUTCMinutes()
- JS getUTCSeconds()
- JS getUTCMilliseconds()
- JS toDateString()
- JS toLocaleDateString()
- JS toLocaleTimeString()
- JS toLocaleString()
- JS toUTCString()
- JS getTimezoneOffset()
- JS toISOString()
- JavaScript Browser Objects
- JS Browser Objects
- JS Window Object
- JS Navigator Object
- JS History Object
- JS Screen Object
- JS Location Object
- JavaScript Document Object
- JS Document Object Collection
- JS Document Object Properties
- JS Document Object Methods
- JS Document Object with Forms
- JavaScript DOM
- JS DOM
- JS DOM Nodes
- JS DOM Levels
- JS DOM Interfaces
- JavaScript Cookies
- JS Cookies
- JS Create/Delete Cookies
- JavaScript Regular Expression
- JS Regular Expression
- JS RegEx .
- JS RegEx \w and \W
- JS RegEx \d and \D
- JS RegEx \s and \S
- JS RegEx \b and \B
- JS RegEx \0
- JS RegEx \n
- JS RegEx \xxx
- JS RegEx \xdd
- JS RegEx Quantifiers
- JS RegEx test()
- JS RegEx lastIndex
- JS RegEx source
- JavaScript Advance
- JS Page Redirection
- JS Form Validation
- JS Validations
- JS Error Handling
- JS Exception Handling
- JS try-catch throw finally
- JS onerror Event
- JS Multimedia
- JS Animation
- JS Image Map
- JS Debugging
- JS Browser Detection
- JS Security
- JavaScript Misc
- JS innerHTML
- JS getElementById()
- JS getElementsByClassName()
- JS getElementsByName()
- JS getElementsByTagName()
- JS querySelector()
- JS querySelectorAll()
- JS document.write()
- JS console.log()
- JS instanceof
- JavaScript Programs
- JavaScript Programs
JavaScript Function (with Examples)
This post is published to provide all the information regarding the function in JavaScript like:
- 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 the defined task. For example:
function printHello() { console.log("Hello"); }
The above function named printHello() prints the Hello on the console output, when it will be 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 work of function }
where:
- function is the keyword used to define a function
- functionName is the name of the function. You need to follow some rules while naming a function. Refer to rules to name a variable to understand regarding naming of a variable or function name
- para1, para2, para3, paraN are the list of parameters. Parameters list 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 stament 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) initialized or copied to num (the parameter of 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 above (previous) example:
document.getElementById("res").innerHTML = cube(5);
will become:
document.getElementById("res").innerHTML = 125;
Wherever the return statement occur in a function, the execution of the function will get 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 block of codes 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 block of code in a function to use it multiple times. That is, we need a function to execute some block of code/statement multiple or 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 is used for 3 times. This is the way, the use of function benefits us.
Please note: Variable defined inside a function is local to the function where it is defined.
JavaScript Function Examples
Now I think, it is the time to take some examples regarding the function in JavaScript, to clear all the remaining doubts. Let me start with a function without parameter.
JavaScript Function without Parameter Example
<!DOCTYPE html> <html> <body> <script> function fresherearth() { console.log("My name is Justin"); console.log("I'm from 'St. Louis, USA'"); console.log("I'm here since last 4 years."); } fresherearth(); </script> </body> </html>
The snapshot given below shows the sample output produced by above JavaScript function example:
JavaScript Function with 1 Parameter Example
<!DOCTYPE html> <html> <body> <p>∛64 = <span id="res"></span></p> <script> function fresherearth(num) { return Math.cbrt(num); } document.getElementById("res").innerHTML = fresherearth(64); </script> </body> </html>
∛64 =
JavaScript Function with 2 Parameter 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 3 Parameter 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 use as many number of parameters as required to the JavaScript function. It is up to you and your application's requirement.
« Previous Tutorial Next Tutorial »