DEV Community

Cover image for Functions in Javascript
Manikandan K
Manikandan K

Posted on

Functions in Javascript

Function

A Function is a block of code that perform some specific task.

Declaration

To declare a Function with Function name the block of code that needs repeat.

Syntax:
function function_name() {
    // block-of code
}
Enter fullscreen mode Exit fullscreen mode
  1. function declared with the function keyword.
  2. block of code within {}.

Calling a function:

To call that function where we need it?

Syntax:
function_name();
Enter fullscreen mode Exit fullscreen mode

Example

function greet() {
    console.log('Hello world');
}

greet(): // Hello world

Enter fullscreen mode Exit fullscreen mode

Function parameters

  • A function can declare with parameters.
  • A parameter is a value that is passed when declaring a function.
function greet(name) {
    console.log(`Hello ${name}`)
}

greet('Manikandan');  // Hello Manikandan

Enter fullscreen mode Exit fullscreen mode

Explanation
Here 'name' is a parameter, when it declare with greet function creation.

Function return

  • return statement can be used to return a value to a function call.

  • return denotes function has ended. Any codes after the return statement are not executed.

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

const result = add(10, 20);
console.log("sum is: ", result); // sum is:  30
Enter fullscreen mode Exit fullscreen mode

Example:
If I want to add three student marks total. I write a code for calculateTotal for each student. So the same code repeats three times.

When I write it to a function and call three times for three students.
So, Here code is written once. But use it three times.

Function like that write code once, and we call when it needs.

function calculateTotal(mark_1, mark_2, mark_3) {
    const totalMark = mark_1 + mark_2 + mark_3;
    return totalMark;
}

const student_1 = calculateTotal(90, 45, 60);
console.log('Student_1 total: ', student_1);

const student_2 = calculateTotal(80, 70, 50); 
console.log('Student_2 total: ', student_2);

const student_3 = calculateTotal(55, 45, 65);
console.log('Student_3 total: ', student_3);

/* 
Student_1 total:  195
Student_2 total:  200
Student_3 total:  165
*/

Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)