DEV Community

Anandhi P
Anandhi P

Posted on

Function in javascript

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 .

Program:*

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

Output:

Hello

Calling a Function

Calling a function means executing or running the function.

After creating a function, we can call it by using the function name followed by parentheses ().

Example

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

greet();
Enter fullscreen mode Exit fullscreen mode

greet() is used to call the function. When the function is called, the code inside the function is executed.

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

Function Parameters

  • Parameters allow us to send values to a function.
  • Parameters are written inside parentheses () when we define a function.
  • The values passed to the function are called arguments.

Example

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

add(10, 5);
Enter fullscreen mode Exit fullscreen mode

Output:

15
Enter fullscreen mode Exit fullscreen mode

Function Return Values

  • A function can return a value to the code that called it.
  • The return statement is used to return a value from a function.
  • The returned value can be stored in a variable or used in another operation.

Example

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

let result = add(10, 10);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

20
Enter fullscreen mode Exit fullscreen mode

Here:

  • return a + b → returns the result from the function.
  • add(10, 5) → calls the function.
  • result → stores the returned value.

Function Arguments

Function parameters and arguments are different.

  • Parameters are the names written inside the parentheses when defining a function.
  • Arguments are the actual values passed to the function when calling it.

Example

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

add(10, 5);
Enter fullscreen mode Exit fullscreen mode

Here:

  • a and bParameters
  • 10 and 5Arguments

Simple way to remember:

Parameter = Name
Argument = Value

Top comments (0)