JavaScript - The Complete Guide 2022

Section 6: More about Functions - Beyond function basic() {}

olivia_yj 2022. 10. 14. 18:10

The goals

๐Ÿ’ช๐ŸปDifferent Ways of Creating Functions

โœŒ๐ŸปAnonymous Functions

๐Ÿ‘๐ŸปCallback Functions & Functions in Functions

๐Ÿ‘๐ŸปDefault Arguments & Rest Operator

๐Ÿ‘Š๐ŸปBind() & More

 

What We Already Know

Functions are "Code on Demand"

Variables and constants created in functions "belong" to that function

Functions CAN take parameters (arguments) and CAN return a value

Functions can be called multiple times (with different arguments)

Functions can be called "directly" and "indirectly"

 

๋งค๊ฐœ๋ณ€์ˆ˜ vs ์ธ์ž

์ด ๊ฐ•์˜์—์„œ "๋งค๊ฐœ๋ณ€์ˆ˜"์™€ "์ธ์ˆ˜"๋ผ๋Š” ๋‹จ์–ด๋ฅผ ๊ฐ™์€ ์˜๋ฏธ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๋“ฃ๊ฒŒ ๋  ๊ฒ๋‹ˆ๋‹ค.

์—„๋ฐ€ํžˆ ๋งํ•˜์ž๋ฉด ์ด ๋‘˜์€ ์ฐจ์ด๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•  ๋•Œ ๊ด„ํ˜ธ ์•ˆ์— ์ง€์ •ํ•˜๋Š” ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค.

  1. function sayHi(name) { ... }

์ด ์˜ˆ์‹œ์—์„œ name์€ ๋งค๊ฐœ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค.

์ธ์ˆ˜๋Š” ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ํ•จ์ˆ˜์— ์ „๋‹ฌํ•˜๋Š” ๊ตฌ์ฒด์ ์ธ ๊ฐ’์ž…๋‹ˆ๋‹ค.

  1. sayHi('Max');

๋งค๊ฐœ๋ณ€์ˆ˜ name ์— ๋Œ€ํ•ด 'Max' ๋Š” ํ•จ์ˆ˜์˜ ์ธ์ˆ˜ ์ž…๋‹ˆ๋‹ค.

๋‘ ๊ฐœ๋…์€ ๋งค์šฐ ๋ฐ€์ ‘ํ•˜๊ฒŒ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ์ €๋Š” ์ข…์ข… "ํ•จ์ˆ˜๊ฐ€ ๋ฐ›๋Š” ์ธ์ˆ˜๋ฅผ ์ •์˜ํ•˜์ž" ๋ผ๋Š” ์‹์œผ๋กœ ๋งํ•  ๊ฒ๋‹ˆ๋‹ค. ์™œ๋ƒํ•˜๋ฉด ๊ฒฐ๊ตญ ํ•จ์ˆ˜์˜ ์ธ์ˆ˜๋ฅผ ์ •์˜ํ•œ๋‹ค๋Š” ๊ฒƒ์€, ํ•ด๋‹น ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•œ๋‹ค๋Š” ๋œป์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค (๊ทธ ๋ฐ˜๋Œ€์˜ ๊ฒฝ์šฐ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€์ž…๋‹ˆ๋‹ค).

const startGameBtn = document.getElementById('start-game-btn');

function startGame() {
  console.log('Game is starting...');
}

const person = {
  greet: function greet() {
    console.log('Hello there!');
  }
}

person.greet();

startGameBtn.addEventListener('click', startGame);

 

Functions are objects!

We can also store functions in objects which essentially stores the object in an object.

 

const startGameBtn = document.getElementById('start-game-btn');

const start = function startGame() {
  console.log('Game is starting...');
}

startGameBtn.addEventListener('click', startGame);

 

 

A Different Way of Defining Functions

Anonymous Functions

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression.

 

The below enlightened syntax illustrates the declaration of anonymous function using normal declaration:

function() {
    // Function Body
 }

We may also declare anonymous function using arrow function technique which is shown below:

( () => {
    // Function Body...
} )();

๋‹ค์–‘ํ•œ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ๊ตฌ๋ฌธ

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์˜ ๊ฒฝ์šฐ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ช‡ ๊ฐ€์ง€ ๋‹ค๋ฅธ ๊ตฌ๋ฌธ์ด ์žˆ์Šต๋‹ˆ๋‹ค - ๋‹ค์Œ์€ ์ด์— ๋Œ€ํ•œ ์š”์•ฝ์ž…๋‹ˆ๋‹ค.

์ค‘์š”ํ•œ ์ฐธ๊ณ  ์‚ฌํ•ญ. ์ด ๊ธ€์˜ ๋ ๋ถ€๋ถ„์— ์žˆ๋Š” "ํ•จ์ˆ˜๋Š” ๊ฐ์ฒด๋งŒ ๋ฐ˜ํ™˜"ํ•˜๋Š” ํŠน์ˆ˜ ์‚ฌ๋ก€๋ฅผ ๋†“์น˜์ง€ ๋งˆ์„ธ์š”!

1) ๊ธฐ๋ณธ ๊ตฌ๋ฌธ:

  1. const add = (a, b) => {
  2. const result = a + b;
  3. return result; // like in "normal" functions, parameters and return statement are OPTIONAL!
  4. };

์ฃผ๋ชฉํ•˜์‹ค ๋งŒํ•œ ์‚ฌํ•ญ. ๋งˆ์ง€๋ง‰์˜ ์„ธ๋ฏธ์ฝœ๋ก , ํ•จ์ˆ˜ ํ‚ค์›Œ๋“œ ์—†์Œ, ๋งค๊ฐœ๋ณ€์ˆ˜/์ธ์ˆ˜์˜ ๊ด„ํ˜ธ.

2) ์ •ํ™•ํžˆ ํ•˜๋‚˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐ›๋Š” ๊ฒฝ์šฐ ๋” ์งง์€ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ตฌ๋ฌธ.

  1. const log = message => {
  2. console.log(message); // could also return something of course - this example just doesn't
  3. };

์ฃผ๋ชฉํ•˜์‹ค ๋งŒํ•œ ์‚ฌํ•ญ. ๋งค๊ฐœ๋ณ€์ˆ˜ ๋ชฉ๋ก์˜ ๊ด„ํ˜ธ๋Š” ์ƒ๋žตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค(์ •ํ™•ํžˆ ํ•˜๋‚˜์˜ ์ธ์ˆ˜์— ๋Œ€ํ•ด).

3) ์ธ์ˆ˜๋ฅผ ๋ฐ›์ง€ ์•Š์€ ๊ฒฝ์šฐ ๋นˆ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ด„ํ˜ธ.

  1. const greet = () => {
  2. console.log('Hi there!');
  3. };

์ฃผ๋ชฉํ•˜์‹ค ๋งŒํ•œ ์‚ฌํ•ญ. ๊ด„ํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค(์ƒ๋žตํ•  ์ˆ˜ ์—†์Œ)

4) ์ •ํ™•ํžˆ ํ•˜๋‚˜์˜ ํ‘œํ˜„์‹์ด ์‚ฌ์šฉ๋˜๋Š” ๊ฒฝ์šฐ ๋” ์งง์€ ํ•จ์ˆ˜ ๋ณธ๋ฌธ.

  1. const add = (a, b) => a + b;

์ฃผ๋ชฉํ•˜์‹ค ๋งŒํ•œ ์‚ฌํ•ญ. ์ค‘๊ด„ํ˜ธ ๋ฐ return ๋ฌธ ์ƒ๋žต ๊ฐ€๋Šฅ, ํ‘œํ˜„์‹ ๊ฒฐ๊ณผ๋Š” ํ•ญ์ƒ ์ž๋™ ๋ฐ˜ํ™˜

5) ํ•จ์ˆ˜๊ฐ€ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค(4)์˜ ์˜ˆ์‹œ์™€ ๊ฐ™์ด ๊ตฌ๋ฌธ์ด ๋‹จ์ถ•๋จ).

  1. const loadPerson = pName => ({name: pName });

์ฃผ๋ชฉํ•˜์‹ค ๋งŒํ•œ ์‚ฌํ•ญ. ๊ฐ์ฒด์— ๋Œ€ํ•œ ์ถ”๊ฐ€ ๊ด„ํ˜ธ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์ค‘๊ด„ํ˜ธ๋Š” ํ•จ์ˆ˜ ๋ณธ๋ฌธ์„ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ธฐํ˜ธ๋กœ ํ•ด์„๋˜๋ฏ€๋กœ ๊ตฌ๋ฌธ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

๋งˆ์ง€๋ง‰ ์˜ˆ์‹œ๋Š” ํ—ท๊ฐˆ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ณดํ†ต JavaScript์—์„œ ์ค‘๊ด„ํ˜ธ๋Š” ํ•ญ์ƒ ์ •ํ™•ํžˆ ํ•˜๋‚˜์˜ ์˜๋ฏธ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  1. const person = { name: 'Max' }; // ์ด ์ค‘๊ด„ํ˜ธ๋Š” ๊ฐ์ฒด ์ƒ์„ฑ์— ์“ฐ์ž„
  2. if (something) { ... } // ์ค‘๊ด„ํ˜ธ๋กœ if ๋ฌธ ๋ธ”๋ก์„ ํ‘œ๊ธฐํ•จ

๊ทธ๋Ÿฌ๋‚˜ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ, ์ค‘๊ด„ํ˜ธ๋Š” ๋‘ ๊ฐ€์ง€ ์˜๋ฏธ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

1) ํ•จ์ˆ˜ ๋ณธ๋ฌธ ํ‘œ์‹œ(๊ธฐ๋ณธ ํ˜•์‹์—์„œ)

2) ๋ฐ˜ํ™˜ํ•˜๋ ค๋Š” ๊ฐ์ฒด ์ƒ์„ฑ(์งง์€ ํ•จ์ˆ˜ ๋ณธ๋ฌธ ํ˜•์‹์œผ๋กœ)

JavaScript์— ์ˆ˜ํ–‰ํ•˜๋ ค๋Š” ์ž‘์—…์„ "์•Œ๋ฆฌ๋ ค๋ฉด" ์œ„์— ํ‘œ์‹œ๋œ ๊ฒƒ์ฒ˜๋Ÿผ ํ‘œํ˜„์‹(์˜ˆ: ๊ฐ์ฒด ์ƒ์„ฑ)์„ ๊ด„ํ˜ธ๋กœ ๋ฌถ์œผ์„ธ์š”.

 

Rest Parameters

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

 

Description

A function definition's last parameter can be prefixed with ... (three U+002E FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within a standard JavaScript array. Only the last parameter in a function definition can be a rest parameter.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

 

Callback Function

"I will call back later!"

A callback is a function passed as an argument to another function

This technique allows a function to call another function

A callback function can run after another function has finished

 

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(5, 5, myDisplayer);

 

Bind()

 

Function Borrowing

With the bind() method, an object can borrow a method from another object.

The example below creates 2 objects (person and member).

The member object borrows the fullname method from the person object:

const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);

 

Preserving this

Sometimes the bind() method has to be used to prevent loosing this.

In the following example, the person object has a display method. In the display method, this refers to the person object:

const person = {
  firstName:"John",
  lastName: "Doe",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}

person.display();

 

When a function is used as a callback, this is lost.

This example will try to display the person name after 3 seconds, but it will display undefined instead:

const person = {
  firstName:"John",
  lastName: "Doe",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}

setTimeout(person.display, 3000);

The bind() method solves this problem.

In the following example, the bind() method is used to bind person.display to person.

This example will display the person name after 3 seconds:

const person = {
  firstName:"John",
  lastName: "Doe",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}

let display = person.display.bind(person);
setTimeout(display, 3000);

 

function calculate(operation) {
  const enteredNumber = getUserNumberInput();
  const initialResult = currentResult;
  let operator;
  if (operation === 'ADD') {
    currentResult += enteredNumber;
    operator = '+';
  } else if (operation === 'SUBTRACT') {
    currentResult -= enteredNumber;
    operator = '-';
  } else if (operation === 'MULTIPLY') {
    currentResult *= enteredNumber;
    operator = '*';
  } else {
    currentResult /= enteredNumber;
    operator = '/';
  }
  createAndWriteOutput(operator, initialResult, enteredNumber);
  writeToLog(operation, initialResult, enteredNumber, currentResult);
}

addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
multiplyBtn.addEventListener('click', calculate.bind(this, 'MULTIPLY'));
divideBtn.addEventListener('click', calculate.bind(this, 'DIVIDE'));

 

 

 

 

 

 

Sources

https://www.geeksforgeeks.org/javascript-anonymous-functions/#:~:text=Anonymous%20Function%20is%20a%20function,keyword%20without%20the%20function%20name.

 

JavaScript Anonymous Functions - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

 

Rest parameters - JavaScript | MDN

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

developer.mozilla.org

https://www.w3schools.com/js/js_function_bind.asp

 

JavaScript Function bind() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com