본문으로 건너뛰기

Functions

Functions

What is a Function?

A function in JavaScript is a block of statements grouped together under a name, similar to a recipe or a set of instructions that performs a task with given 'ingredients'.

Example:

function sayHello() {
console.log('Hello!');
}

Purpose and Advantages of Functions

The main purpose of functions is to increase code reusability.

A function that has been created can be called multiple times, which reduces code duplication and eases maintenance.


Ways to Declare Functions

  • Function Declaration

This approach starts with the 'function' keyword followed by the name of the function, parameters, and a block of statements.

Example:

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

  • Function Expression

Functions can be treated as values. Declaring a function by assigning it to a variable is known as a function expression.

Example:

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

Difference Between Parameters and Arguments

Parameters are the variables used when defining a function, while arguments are the actual values passed to the function when it is called.

For example, in cooking, if 'salt' listed in a recipe is a parameter, then the actual amount of salt you put in, say '1 spoon', is the argument.


  • Return Value (return)

The return keyword is used when you want to return a specific value from a function.

Example:

function multiply(a, b) {
return a * b;
}

const result = multiply(2, 3); // 6

Function Invocation and Examples

Once a function is defined, it can be 'invoked' or 'called' using its name.

Function invocation means executing a function by appending parentheses () after its name.

Example:

function greet(name) {
console.log('Hello, ' + name + '!');
}

greet('Minsoo'); // "Hello, Minsoo!" is printed

다음 내용이 궁금하다면?

월 12,500원 PLUS 멤버십 가입 or 강의를 등록해 주세요!