Functions in JavaScript part-3

Introduction to JavaScript functions:

When developing an application, you often need to perform the same action in many places. For example, you may want to show a message whenever an error occurs.

To avoid repeating the same code all over places, you can use a function to wrap that code and reuse it.

JavaScript provides many built-in functions such as parseInt(), parseFloat() prompt() In this tutorial, you will learn how to develop custom functions.

Declare a function :

To declare a function, you use the function keyword, followed by the function name, a list of parameters, and the function body as follows:


function functionName(parameters) {
    // function body
    // ...
}

The function name must be a valid JavaScript identifier. By convention, the function names are in camelCase and start with verbs like getData(), fetchContents(), and isValid().

Basically, it consists of the following:

  • Function keyword

  • The name of the function

  • Parentheses (which can take in parameters, or also be empty)

  • The body of the function (wrapped in curly braces).

Here's an example:

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

This function won't do a thing – in this case, output Hello world – unless you call it. The term for this is invoking the function.

Here’s how to call the function:

sayHello();

//output: Hello world

Here’s another example:

function sum(num1, num2){
    return num1 + num2;
}

To invoke this function, we call it like this:

sum(1, 2);

//output: 3

You can see a slight difference between our first function example and the second.

If you guessed that it's the content within the parenthesis of the second function, then you’re right!

The function sum() took in two parameters when we defined it – num1, and num2. And when we call it, we passed in two values – the arguments, 1 and 2. Let me explain what these two terms (parameters and arguments) mean.

A parameter is a variable you pass to a function when you declare it.

Suppose you want your function to be dynamic, so that it applies the function’s logic to different sets of data at different times. That’s where parameters come in handy. This way, your function doesn’t just output the same result repeatedly. Instead, its result is dependent on the data you pass in.

An argument, on the other hand, is the value equivalent to the parameter that you pass to the function when you call it.

So the syntax for declaring a function with parameters will look like this:

function nameOfFunction(parameters){
    //function body.....
}

And to invoke it:

nameOfFunction(arguments)

Parameters vs. Arguments

The terms parameters and arguments are often used interchangeably. However, they are essentially different.

When declaring a function, you specify the parameters. However, when calling a function, you pass the arguments that are corresponding to the parameters.

For example, in the nameOffFunction() function, the parameters is the parameter and the arguments string is an argument that corresponds to the parameters parameter.

Returning a value

Every function in JavaScript implicitly returns undefined unless you explicitly specify a return value. For example:

function say(message) {
    console.log(message);
}

var result = say('Hello');
console.log('Result:', result);

Output:

Hello
Result: undefined

To specify a return value for a function, you use the return statement followed by an expression or a value, like this

return expression;

For example, the following add() function returns the sum of the two arguments:

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

The following shows how to call the add() function:

var sum = add(10, 20);
console.log('Sum:', sum);

Output:

Sum: 30

The following example uses multiple return statements in a function to return different values based on conditions:

function compare(a, b) {
    if (a > b) {
        return -1;
    } else if (a < b) {
        return 1;
    }
    return 0;
}

console.log(compare(20, 10))

The compare() function compares two values. It returns:

  • -1 if the first argument is greater than the second one.

  • 1 if the first argument is less than the second one.

  • 0 if the first argument equals the second one.

The function immediately stops executing immediately when it reaches the return statement. Therefore, you can use the return statement without a value to exit the function prematurely, like this:

function say(message) {
    // show nothing if the message is empty
    if (! message ) {
        return;
    }
    console.log(message);
}

say("hello")

In this example, if the message is blank (or undefined), the say() function will show nothing.

The function can return a single value. If you want to return multiple values from a function, you need to pack these values in an array or an object.

Anonymous Functions (Function Expressions):

You can also define functions without giving them a name. These are often used as arguments for other functions or assigned to variables. They're called anonymous functions or function expressions.

var multiply = function(x, y) {
  return x * y;
};

var product = multiply(4, 6);
console.log(product); // Output: 24

Arrow Functions:

Arrow functions provide a shorter syntax for writing functions. They are especially useful for writing concise functions with a single expression.

var divide = (a, b) => a / b;
console.log(divide(10, 2)); // Output: 5

Default Parameters:

You can provide default values for function parameters. If an argument is not passed, the default value will be used.

function greet(name = "Guest") {
  console.log(`Hello, ${name}!`);
}

greet();         // Output: Hello, Guest!
greet("Alice");  // Output: Hello, Alice!

Summary

  • Use the function keyword to declare a function.

  • Use the functionName() to call a function.

  • All functions implicitly return undefined if they don’t explicitly return a value.

  • Use the return statement to return a value from a function explicitly.

  • The arguments variable is an array-like object inside a function, representing function arguments.

  • The function hoisting allows you to call a function before declaring it.