본문 바로가기
Web/JavaScript

[JavaScript] Function

by llHoYall 2022. 6. 25.

Function in JS is objects. Especially, first-class objects.

The function is an important thing to understand JS.

Function Definition

There are 4 ways to define function.

Function Definition Statement

This is a statement, so it can be located in any place where there can be a statement.

function adder(x, y) {
  return x + y;
}

Since ambiguity occurs by function hoisting, it is not recommended.

console.log(adder(3, 4)); // 7

function adder(x, y) {
  return x + y;
}

Function Expression

This is an expression, so it can be evaluated to value.

const adder = function (x, y) {
  return x + y;
};

There is also no ambiguity caused by function hoisting.

console.log(adder(3, 4));
// ReferenceError: Cannot access 'adder' before initialization

const adder = function (x, y) {
  return x + y;
};

Function Constructor

There is Function() constructor.

const adder = new Function('x', 'y', 'return x + y');

This method doesn't create closure.

Arrow Function  

This method has been introduced since ES6.

const adder = (x, y) => x + y;

This method doesn't have a prototype property and doesn't create the arguments object.

It differs from this binding method as well.

Fundamentals

A function acts as a certain function.

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

console.log(`${adder(2, 3)}`); // 5

In the above example, I made a function for adding two numbers. The function takes two integer numbers and returns its summation.

 

You can call a function with its name and parentheses.

Functions can have or do not have parameters and can have or do not have return values.

If you input the arguments, it matches to parameters in order.

 

A function can be an argument or a return value because it is a first-class object.

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

function multiplier(num1, num2) {
  return num1 * num2;
}

console.log(`${multiplier(2, adder(2, 3))}`);
// 10 <- 2 * (2 + 3)
function print(param) {
  console.log(`${param}`);
}

function addAndPrint(num1, num2) {
  return print(num1 + num2);
}

addAndPrint(1, 2);
// 3

Function Scope

A function has its own scope.

let num1 = 5;
function printNumber() {
  let num1 = 10;
  console.log(`${num1}`);
}

console.log(`${printNumber()}`);
// 10

I defined two variables with the same name. If we call the function, it finds the variable in its own scope first not a global variable.

Nesting

A function can be nested.

function add(num1, num2) {
  let num3 = num1 + num2;
  function increase2(num3) {
    return num3 + 2;
  }
  return increase2(num3);
}

console.log(`${add(3, 4)}`);
// 9

A function increase2 is nested in the function add. If you call a function add, it calls increase2.

Recursive Function

A function can call itself.

function sum(num) {  
  if (num === 0) {
    return num;
  }
  return num + sum(--num);
}

console.log(`${sum(5)}`);
// 15 <- 5 + 4 + 3 + 2 + 1 + 0

The procedure is like this.

5 + sum(4) 
    => 4 + sum(3) 
           => 3 + sum(2) 
                  => 2 + sum(1) 
                         => 1 + sum(0) 
                         => 1 + 0
                  => 2 + 1
           => 3 + 3
    => 4 + 6
5 + 10

When you use a recursive function, if the call depth gets deeper, a stack overflow can occur.

So, you should use tail recursion.

Closures

JS allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function.

However, the outer function does not have access to the variables and functions defined inside the inner function.

Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function.

A closure is created when the inner function is somehow made available to any scope outside the outer function.

function outerFunc() {
  let outNum = 1;
  function innerFunc() {
    let inNum = 2;
    console.log(`${outNum + inNum}`);
  }
  return innerFunc;
}

let closure = outerFunc();
closure();
// 3

The inner function uses a variable of the outer function. So closure is created.

Function Parameters

There are some special types of parameters.

Default Parameters

In JS, the parameters of functions default to undefined. However, you can define the default value of it.

Arguments exceeding the number of parameters are ignored.

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

function withDefault(num1, num2 = 3) {
  return num1 + num2;
}

console.log(`${withoutDefault(1)}`);
// NaN <- 1 + undefined

console.log(`${withoutDefault(1, 2, 3)}`);
// 3 <- 1 + 2 (3 is ignored)

console.log(`${withDefault(1)}`);
// 4 <- 1 + 3 (default value)

console.log(`${withDefault(1, 2)}`);
// 3 <- 1 + 2

The default values should be set from the last parameter. In addition, you have to input the argument in all parameters without default values.

You need to keep this in mind.

Rest Parameters

The rest parameter allows us to use an indefinite number of arguments as an array.

function adder(initial, ...remaining) {
  let total = initial;
  for (let elem of remaining) {
    total += elem;
  }
  return total;
}

console.log(`${adder(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)}`);
// 55

IIFE (Immediately Invoked Function Expression)

This type of function runs as soon as it is defined.

It is called only once.

It can also be used as a named function, but it is usually used as an anonymous function.

const printName = (() => {
  const name = "HoYa";
  console.log(`${name}`);
})();
// HoYa

const value = (function (x , y) {
  return x + y;
}(3, 4));
console.log(value); // 7

'Web > JavaScript' 카테고리의 다른 글

[JavaScript] Class  (0) 2022.07.01
[JavaScript] Object  (0) 2022.06.26
[JavaScript] Control Flow Statements  (0) 2022.06.22
[JavaScript] Operators  (0) 2022.06.21
[JavaScript] Data Types  (0) 2022.06.19

댓글