JavaScript functions are fundamental building blocks of the JavaScript language. In this tutorial, we will learn what is a JavaScript function, how to create a function in JavaScript, and how to invoke it and return values from it.
Let’s dive in!
What is a function in JavaScript?
A function is a block of code that performs a specific task.
Functions are subprograms which are used to compute a value or perform a task.
Suppose you need to create a program to create a circle and color it. You can create two functions to solve this problem:
- a function to draw the circle
- a function to color the circle
Dividing a complex problem into smaller chunks makes your program easy to understand and reusable.
In other words, functions are a set of organized instructions that correspond to a certain task or specific functionality a user wants to implement in their program to achieve a single desired outcome.
The code inside a function runs only when it is needed, meaning only when it is called.
JavaScript has two types of functions:
- Built-in functions E.g:
alert()
,prompt()
andconfirm()
etc. - User-defined functions
How to declare functions in JavaScript
The syntax to declare a function is:
function nameOfFunction () { // function body }
- A function is declared using the
function
keyword. - The basic rules of naming a function are similar to naming a variable in JavaScript. It is better to write a descriptive name for your function. For example, if a function is used to add two numbers, you could name the function
add
oraddNumbers
. - The body of function is written within
{}
.
For example,
// declaring a function named greet() function greet() { console.log("Hello Sunil!"); }
How to call functions in JavaScript
In the above program, we have declared a function named greet()
. To use that function, we need to call it.
Here is how you can call the above greet()
function.
// function call greet();
So the complete program would be:
// program to print a text // declaring a function function greet() { console.log("Hello Sunil!"); } // calling the function greet(); //Output: Hello Sunil!
Call JavaScript function from HTML
You can call a JavaScript function from HTML using events.
You can call a function from any event we want and as many times.
When an event occurs like button click, mouse move, document load, etc then you can use some event handler to trigger the event which will call the function.
<!-- function called when page load --> <body onload="message()"> <h2>Use some event to call a function from HTML.</h2> <!-- function called when button clicked --> <button onclick="my_function()">Click</button> <script> function message() { alert("function executed!"); } </script> </body>
JavaScript function parameter
A function can also be declared with parameters. A parameter is a value that is passed when declaring a function.
The actual values that are passed in the function are known as arguments while the variable that is declared in the function is known as a parameter.
There are two terms used in functions: Arguments and Parameters. Parameters are the names that are listed in function definition. Arguments are the real values that are passed to the function when they are called.
The data type of JavaScript function parameter could be any valid data type, for example, string, number, array, etc.
// program to print the text // declaring a function function greet(name) { console.log("Hello " + name + ":)"); } // variable name can be different let name = prompt("Enter a name: "); // calling function greet(name); //Output - Enter a name: Sunil Hello Sunil :)
In the above program, the greet
function is declared with a name
parameter. The user is prompted to enter a name. Then when the function is called, an argument is passed into the function.
Returning a value from JavaScript function
The return
statement can be used to return the value to a function call.
The return
statement denotes that the function has ended. Any code after return is not executed.
If nothing is returned, the function returns an undefined
value.
Also, the return
value can be stored in a variable.
function multiply(a, b) { return a * b; } // storing return value in a variable var value = multiply(4, 6); console.log(value); //Output- 24
The return
value can be placed anywhere in the function but as soon as the function finds a return statement it stops further execution of the code in a function.
Also, you can use a return
statement without returning any value just to stop the execution of the function.
function pass(mark) { if (!mark) { console.log("Invalid Marks!"); return; } if (mark > 40) { console.log("Pass!"); return true; } else { console.log("Fail!"); return false; } } pass(60); //Output - Pass!
JavaScript function Expression
A function expression is any function that is passed as a value to a variable as in:
let multiply = function (firstNumber, secondNumber) { return firstNumber * secondNumber; }
After a function expression has been stored in a variable, the variable can be used as a function. They are always invoked (called) using the variable name as in:
let multiply = function (firstNumber, secondNumber) { return firstNumber * secondNumber; } multiply(3, 5) // 15 is seen in the console.
Yeah! That is a function expression.
Function Declaration vs Function Expression
These are two important differences between function declaration and function expression:
First, a function declaration can be hoisted but a function expression can’t be hoisted. It means you can use a function before it is declared while you can’t use a function before function expression is declared.
hello(); // run successfully function hello() { // function declaration return "Hello World!"; }
hello(); // error function not declared let hello = function() { // function expression return "Hello World!"; }
Secondly, a function declaration is loaded before execution of any code but function expression loads only when the interpreter reached that line of code.
JavaScript Arrow Function
In ES2015, JavaScript expressions are written as arrow functions.
An arrow function – also called “fat arrow” function is a more concise syntax for writing function expressions. It utilizes the arrow (=>
) that looks like a fat arrow.
const add = (a,b) => { return a+b; } console.log(add(10,5)); // expected output: 15
Arrow function expressions are somewhat a compact alternative to the normal function expressions; however, they are restricted and cannot be used for all situations.
Conclusion
In this tutorial, we covered the concept of JavaScript functions in details, covering the basics of functions, why we need them, the structure of a function, how to define them, how to call them, along with examples.
Add comment