JavaScript - Functions




JavaScript - Functions

Functions are the central working units of JavaScript. Nearly every script you'll write uses one or more functions. Therefore it is important that you understand what a function is and how it works.

A function is a subprogram designed to perform a particular task. Functions are executed when they are called. This is known as invoking a function. Values can be passed into functions and used within the function. Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined. Functions are objects.

There are a few different ways to define a function in JavaScript, A Function Declaration defines a named function. To create a function declaration you use the function keyword followed by the name of the function. When using function declarations, the function definition is hoisted, thus allowing the function to be used before it is defined.

function name(parameters){
  statements
}

A Function Expressions defines a named or anonymous function. An anonymous function is a function that has no name. Function Expressions are not hoisted, and therefore cannot be used before they are defined. In the example below, we are setting the anonymous function object equal to a variable.

let name = function(parameters){
  statements
}

An Arrow Function Expression is a shorter syntax for writing function expressions. Arrow functions do not create their own this value.

let name = (parameters) => {
  statements
}

What is JavaScript Functions

A function is a block of code that performs an action or returns a value. Functions are custom code defined by programmers that are reusable, and can therefore make your programs more modular and efficient. In this tutorial, we will learn several ways to define a function, call a function, and use function parameters in JavaScript.

Defining a Function

Functions are defined, or declared, with the function keyword. Below is the syntax for a function in JavaScript.

function nameOfFunction() {
    // Code to be executed
}

The declaration begins with the function keyword, followed by the name of the function. Function names follow the same rules as variables — they can contain letters, numbers, underscores and dollar signs, and are frequently written in camel case. The name is followed by a set of parentheses, which can be used for optional parameters. The code of the function is contained in curly brackets, just like a for statement or an if statement.

In our first example, we’ll make a function declaration to print a greeting statement to the console.

// Initialize greeting function
function greet() {
    console.log("Hello, World!");
}

Here we have the code to print Hello, World! to the console contained inside the greet() function. However, nothing will happen and no code will execute until we invoke, or call the function. You can invoke a function by writing the name of the function followed by the parentheses.

// Invoke the function
greet();

Now we will put those together, defining our function and invoking it.

// Initialize greeting function
function greet() {
    console.log("Hello, World!");
}

// Invoke the function
greet();

With the call for greet();, the function will run and we will receive the Hello, World! as the program’s output.

Hello, World!

Learn by example.

function triple(x) {
  return x + x + x;
}

triple(8)                     // 24
triple("ho ")                 // "ho ho ho "
function even(x) {
  return x % 2 == 0;
}

even(-8)                      // true
even(27)                      // false
// Returns whether x exactly divides y
function divides(x, y) {
  return y % x === 0;
}

divides(5, 20)                // true
divides(2, 17)                // false
// Returns whether a given year is a leap year, according to the
// rules of the Gregorian calendar. A year is a leap year if it
// is (1) divisible by 4 but not 100, or else (2) is divisible
// by 400.
function isLeapYear(y) {
  return divides(4, y) && !divides(100, y) || divides(400, y);
}

isLeapYear(1963)              // false
isLeapYear(1968)              // true
isLeapYear(2000)              // true
isLeapYear(2100)              // false
isLeapYear(2200)              // false
isLeapYear(2399)              // false
isLeapYear(2400)              // true
isLeapYear(920481910)         // false
isLeapYear(9204810000)        // true
function halfOf(x) {
  return x / 2;
}

halfOf(-8)                    // -4
halfOf(27)                    // 13.5
function isLongerThan(s, n) {
  return s.length > n
}

isLongerThan("sos", 2)        // true
isLongerThan("sos", 3)        // false
function salePrice(originalPrice, discountPercent) {
  return originalPrice - (originalPrice * discountPercent / 100.0);
}

salePrice(200, 10)            // 180
salePrice(157.95, 15)         // 134.2575
salePrice(157.95, 100)        // 0
function circleArea(radius) {
  return Math.PI * radius * radius;
}

circleArea(3)                 // 28.274333882308138
circleArea(1.492705)          // 6.999996901568007
function sum(a) {
  let result = 0;
  for (let x of a) {
    result += x;
  }
  return result;
}

sum([])                       // 0
sum([8])                      // 8
sum([3, 9, 5, -2])            // 15
function average(a) {
  return sum(a) / a.length;
}

average([3, 9, 5, -2])        // 3.75
average([8])                  // 8
average([])                   // NaN, but should it be???

Function Expressions

In the last section, we used a function declaration to get the sum of two numbers and return that value. We can also create a function expression by assigning a function to a variable. Using our same add function example, we can directly apply the returned value to a variable, in this case sum.

// Assign add function to sum constant
const sum = function add(x, y) {
    return x + y;
}

// Invoke function to find the sum
sum(30, 5);
35

Now the sum constant is a function. We can make this expression more concise by turning it into an anonymous function, which is an unnamed function. Currently, our function has the name add, but with function expressions it is not necessary to name the function and the name is usually omitted.

// Assign function to sum constant
const sum = function(x, y) {
    return x + y;
}

// Invoke function to find the sum
sum(200, 3);
600

In this example, we’ve removed the name of the function, which was add, and turned it into an anonymous function. A named function expression could be used to aid in debugging, but it is usually omitted.

Parameters vs. Arguments.

If you’re new to JavaScript, you may have heard the terms parameters and arguments used interchangeably. While very similar, there is an important distinction to make between these two keywords. Parameters are used when defining a function, they are the names created in the function definition. In fact, during a function definition, we can pass in up to 255 parameters, Parameters are separated by commas in the (). Here’s an example with two parameters param1 & param2 -

const param1 = true;
const param2 = false;
function twoParams(param1, param2){
  console.log(param1, param2);
}

Arguments, on the other hand, are the values the function receives from each parameter when the function is executed (invoked). In the above example, our two arguments are true & false.