Define a Function in Javascript

Define a Function in Javascript: Define a Function in Javascript is the Functions are the basic building block of JavaScript. Functions allow us to encapsulate a block of code and reuse it multiple times. Functions make JavaScript code more readable, organized, reusable, and maintainable.

function (arg1, arg2, arg3,…)
//write function code here

In JavaScript, a function can be defined using the function keyword, followed by the name of a function and parentheses. Optionally, a list of input parameters can be included within the parentheses. The code block that needs to be executed when the function is called is written within curly braces.

Defining a Function in JavaScript

The following defines a function named greet that will display an alert box.

Example: Define a Function
function greet() {
alert(“Hello World!”);

The above greet() function does not include any input parameters. It contains a single statement that displays an alert message.

Now, you can call or invoke the greet function by using the function name followed by the () operator, as shown below. When you call a function, JavaScript will execute the codes written inside the calling function.

Example: Calling a Function

Function Expression

A function expression in JavaScript is a function that is stored as a value, and can be assigned to a variable or passed as an argument to another function.

Example: Function Expression
var add = function (num1, num2) {
return num1 + num2;

var result = add(10, 20);//returns 30

Arrow Functions

Arrow functions are a shorthand syntax for defining anonymous functions in JavaScript. Arrow Functions They have compact syntax compared to anonymous functions. However, they do not have their own this value in Arrow Functions.

Example: Arrow Function
let square = num => num * num;

let result = square(5);
console.log(result); //25

Function Parameters

You can pass values to a function using parameters. A function are have one or more parameters and the values will be passed by the calling code.

Example: Function Parameters
function greet(firstName, lastName) {
alert(“Hello ” + firstName + ” ” + lastName);

greet(“Steve”, “Jobs”);

JavaScript is a dynamic type scripting language, so a function parameter can have a value of any data type.

Example: Function Parameters
function greet(firstName, lastName) {
alert(“Hello ” + firstName + ” ” + lastName);

greet(“Bill”, “Gates”);
greet(100, 200);

Javascript training in hyderabad


Enquiry Now
close slider
Scroll to Top
Call Now Button