DEV Community

yevastepanyan
yevastepanyan

Posted on

Functions In JavaScript

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example

// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
  return p1 * p2;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript Function Syntax

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

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Function Return

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

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

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

A function can return zero or one value using return keyword.

Example
Return value From a Function

function Sum(val1, val2) {
    return val1 + val2;
};

var result = Sum(10,20); // returns 30
Enter fullscreen mode Exit fullscreen mode

Example
Calculate the product of two numbers, and return the result:

let x = myFunction(4, 3);   // Function is called, return value will end up in x

function myFunction(a, b) {
  return a * b;             // Function returns the product of a and b
}
Enter fullscreen mode Exit fullscreen mode

The result in x will be:

12
Enter fullscreen mode Exit fullscreen mode

Why Functions?

You can reuse code: Define the code once, and use it many times.

You can use the same code many times with different arguments, to produce different results.

Example
Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
Enter fullscreen mode Exit fullscreen mode

The () Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Accessing a function without () will return the function object instead of the function result.

Example

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Enter fullscreen mode Exit fullscreen mode

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Example
Instead of using a variable to store the return value of a function:

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
Enter fullscreen mode Exit fullscreen mode

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";
Enter fullscreen mode Exit fullscreen mode

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Example

// code here can NOT use carName

function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}

// code here can NOT use carName 
Enter fullscreen mode Exit fullscreen mode

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Nested Functions

In JavaScript, a function can have one or more inner functions. These nested functions are in the scope of outer function.
Inner function can access variables and parameters of outer function. However, outer function cannot access variables defined inside inner functions.

Example

function ShowMessage(firstName){
    function SayHello() {
        alert("Hello " + firstName);
    }
    return SayHello();
}
ShowMessage("Steve");
Enter fullscreen mode Exit fullscreen mode

Points to Remember :

  • JavaScript a function allows you to define a block of code, give it a name and then execute it as many times as you want.
  • A function can be defined using function keyword and can be executed using () operator.
  • A function can include one or more parameters. It is optional to specify function parameter values while executing it.
  • JavaScript is a loosely-typed language. A function parameter can hold value of any data type.
  • You can specify less or more arguments while calling function.
  • All the functions can access arguments object by default instead of parameter names.
  • A function can return a literal value or another function.
  • A function can be assigned to a variable with different name.
  • JavaScript allows you to create anonymous functions that must be assigned to a variable.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

JavaScript allows you to create anonymous functions that must be assigned to a variable

This is incorrect in two ways:

  • The very act of assigning an anonymous function to a variable gives it a name - making it no longer an anonymous function (test this by checking the name property of the function).
  • You can use anonymous functions without assigning them to a variable. This is in fact one of the only ways in which they are actually true anonymous functions. An example of this is an IIFE - where an anonymous function is defined and immediately called.