Skip to content

JavaScript Functions#

JavaScript Functions#

  • In JavaScript, to declare a function, you use the function keyword, followed by the function name, a list of parameters, and the function body.
  • A function can accept zero, one, or multiple parameters. In the case of multiple parameters, you need to use a comma to separate two parameters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function functionName() {
    // function body
    // ...
}

function functionName2(parameter1) {
    // function body
    // ...
}

function functionName2(parameter1, parameter2) {
    // function body
    // ...
}
  • In JavaScript we can store functions as variables, pass them to other functions as arguments, and return them from other functions as values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function add(a, b) {
    return a + b;
}

let sum = add;

function average(a, b, fn) {
    return fn(a, b) / 2;
}

let result = average(10, 20, sum);

console.log(result); //output 15
  • Since functions are values, we can return a function from another function.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function compareBy(propertyName) {
  return function (a, b) {
    let x = a[propertyName],
      y = b[propertyName];

    if (x > y) {
      return 1;
    } else if (x < y) {
      return -1;
    } else {
      return 0;
    }
  };
}
let products = [
  { name: 'iPhone', price: 900 },
  { name: 'Samsung Galaxy', price: 850 },
  { name: 'Sony Xperia', price: 700 },
];

// sort products by name
console.log('Products sorted by name:');
products.sort(compareBy('name'));
console.table(products);

// Products sorted by name:
//┌─────────┬──────────────────┬───────┐
//│ (index) │       name       │ price │
//├─────────┼──────────────────┼───────┤
//│    0    │ 'Samsung Galaxy' │  850  │
//│    1    │  'Sony Xperia'   │  700  │
//│    2    │     'iPhone'     │  900  │
//└─────────┴──────────────────┴───────┘



// sort products by price
console.log('Products sorted by price:');
products.sort(compareBy('price'));
console.table(products);

//Products sorted by price:
//┌─────────┬──────────────────┬───────┐
//│ (index) │       name       │ price │
//├─────────┼──────────────────┼───────┤
//│    0    │  'Sony Xperia'   │  700  │
//│    1    │ 'Samsung Galaxy' │  850  │
//│    2    │     'iPhone'     │  900  │
//└─────────┴──────────────────┴───────┘

Anonymous Functions#

  • An anonymous function is a function without a name. Note that if we don’t place the anonymous function inside the (), we’ll get a syntax error. The () makes the anonymous function an expression that returns a function object.
1
2
3
(function () {
   //...
});
  • An anonymous function is not accessible after its initial creation. Therefore, we often need to assign it to a variable. When we assign an anonymous function to a variable, we don't need to wrap it into the () anymore.
1
2
3
4
5
let show = function() {
    console.log('Anonymous function');
};

show();
  • Like the normal JavaScript function we can use the Anonymous Functions as arguments to other functions.
1
2
3
setTimeout(function() {
    console.log('Execute later after 1 second')
}, 1000);
  • the anonymous functions can be executed immediately after the declaration, we just need to put () right after the anonymous functions.
1
2
3
(function () {
    console.log('Immediately invoked function execution');
})();
1
2
3
4
5
6
7
8
let person = {
    firstName: 'John',
    lastName: 'Doe'
};

(function () {
    console.log(person.firstName} + ' ' + person.lastName);
})(person);

Arrow Functions#

  • ES6 introduced arrow function expressions that provide a shorthand for declaring anonymous functions
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let show = function () {
    console.log('Anonymous function');
};

let show = () => console.log('Anonymous function');


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

let add = (a, b) => a + b;   

JavaScript Recursive Function#

  • A recursive function is a function that calls itself until it doesn’t. And this technique is called recursion.
  • A recursive function always has a condition to stop calling itself. Otherwise, it will call itself indefinitely. So a recursive function typically looks like the following:
1
2
3
4
5
6
7
8
function recurse() {
    if(condition) {
        // stop calling itself
        //...
    } else {
        recurse();
    }
}

See Also#

References#