Saturday, March 30, 2024

What are functions in Javascript?

 It is a block of code designed to perform a particular task when called.

Syntax:

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses () which is optional.

function name(parameter1, parameter2, parameter3) {

  // code to be executed

  // return something;

}

Functions often compute a return value. The return value is "returned" back to the "caller".

When JavaScript reaches a return statement, the function will stop executing.

Let us understand with an example.

let x = myFunction(1, 2);

function myFunction(a, b) {

// Function returns the sum of a and b

  return a + b;

}

console.log('sum is ==> '+x);

Output:

sum is ==> 3

No comments:

Post a Comment