Friday, 31 May 2024

Java Script: Functions

 Functions are blocks of code that can be named and reused.

Here’s how to declare a function:

EXAMPLE

function addTwoNumbers(x, y) {

       return x + y;

}

There’s a lot going on in the example above, so let’s look at each part individually.

  • The function is the keyword that starts declaring a function.

  • addTwoNumbers is the function’s name, which is customizable — just like variable names.

  • (x, y) are parameters, variable names for the inputs a function will accept.

  • return is the keyword that exits the function and shares an optional value outside.


Using functions

Once a function is defined, you can use it by referencing its name with parentheses () right after.

Note that a function doesn’t have to have parameters.

EXAMPLE:

function balajiTech() {

    return "Hello, world!";

}

balajiTech();

OutPut

Hello, world!


If a function _does_ have parameters, you’ll need to provide values inside the parentheses when using the function.

 EXAMPLE:

function square(number) {

    return number * number;

}

square(2);

OutPut

4


Benefits of Using a Function

  1. The function makes the code reusable. You can declare it once and use it multiple times.

  2. The function makes the program easier as each small task is divided into a function.

  3. The function increases readability.


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts