JavaScript Functions

By onjsdev

Functions is core part of JavaScript programming. It allows to create reusable blocks of code.In this article, we will explore the fundamentals of JavaScript functions, including their syntax, types, parameters, return values, and various ways to define and invoke them.

Function Syntax

A JavaScript function can be defined using the function keyword followed by the function name, a set of parentheses for optional parameters, and a block of code enclosed in curly braces. Here's the basic syntax:

function functionName(parameter1, parameter2, ...) {
  // Code to be executed

The function name should be descriptive and follow naming conventions. Parameters are optional, and multiple parameters can be separated by commas. The code inside the function block is executed when the function is invoked.

Function Types

JavaScript supports three types of functions: named functions ,anonymous functions and arrow functions.

Named Functions

A named function is one that has a specified name. It can be defined using the syntax mentioned earlier. Here's an example:

function greet(name) {
  console.log(`Hello, ${name}!`);

Anonymous Functions

An anonymous function, also known as a function expression, doesn't have a specific name. Instead, it's assigned to a variable or used as an argument to another function. Here's an example:

const greet = function(name) {
  console.log(`Hello, ${name}!`);

In this case, the function is assigned to the greet variable, and the variable can be used to invoke the function.

Function Parameters and Return Values

Parameters are placeholders for values that can be passed to a function when it is invoked. They allow functions to receive inputs and perform actions based on those inputs. Functions can have zero or more parameters. Here's an example with parameters:

function addNumbers(a, b) {
  return a + b;

In this example, the addNumbers function takes two parameters, a and b, and returns their sum using the return statement.

Return values are the output of a function that can be used further in the program. The return statement specifies the value to be returned from the function

Invoking Functions

Once a function is defined, it can be invoked or called to execute the code inside its block. Function invocation is done by using the function name followed by parentheses. Here are a few examples:

greet("John"); // Output: Hello, John!

const result = addNumbers(3, 5);
console.log(result); // Output: 8


JavaScript functions are an essential part of the language, it enables code to reuse. The functions that can be defined in three ways accept inputs and return outputs.

Thank you for reading