DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on • Edited on

JavaScript Function

What are Functions?

Functions are reusable code blocks designed for particular tasks. Functions are executed when they are called or invoked. Functions are fundamental in all programming languages

Why Use Functions?

  • Reuse code (write once, run many times)
  • Organize code into smaller parts
  • Make code easier to read and maintain
function welcome() {
  return "Hello World";
}
Enter fullscreen mode Exit fullscreen mode

Function Invocation (Function Call)

Function invocation is the process of calling a function to execute its code.

function greet() {
    console.log("Hello");
}

greet();   // Function Invocation or Function Call
Enter fullscreen mode Exit fullscreen mode

JavaScript Function Parameters

A function invocation executes the statements inside the function by using its name followed by parentheses ().

function add(a, b) {
    console.log(a + b);
}

add(10, 20);   // parentheses(inside the value arguments)
Enter fullscreen mode Exit fullscreen mode

JavaScript Function Return

He return statement is used to send a result back from a function. When return executes, the function stops running at that point. The returned value can be stored in a variable or used directly.

With return

function add(a, b) {
    return a + b;
}

let result = add(10, 20);
console.log(result);

output:
30
Enter fullscreen mode Exit fullscreen mode

Without return

function greet() {
    console.log("Hello");
}

let result = greet();
console.log(result);

output:
Hello
undefined
Enter fullscreen mode Exit fullscreen mode

What is a Function Expression?

A function expression is a function stored in a variable.

// Standard Function
function multiply(a, b) {
  return a * b;
}

// Function Expression
const multiply = function(a, b) {
  return a * b;
};
Enter fullscreen mode Exit fullscreen mode

Hoisting

  • Function declarations can be called before they are defined.
  • Function expressions can not be called before they are defined.

JavaScript Arrow Functions

A shorter and simpler way to write a function using the => operator. A concise function syntax introduced in ES6.

//Function Declaration
function add(a, b) {
    return a + b;
}


//Arrow Function
const add = (a, b) => {
    return a + b;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

A function expression is a way of creating a function by storing it in a variable. The function can be called using the variable name.

This is not correct. Function expression and storing a function in a variable are two different things.