Dev.to WebDev 🛠 Dev 👁 1 📖 1 min read

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 Fun

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";
}

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

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)

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

Without return

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

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

output:
Hello
undefined

What is a Function Expression?

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.

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

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

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;
};
📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.