Function in js

Yoseob Shin·2022년 3월 28일
0

javascript

목록 보기
7/24
post-thumbnail
post-custom-banner

In programming, we often use code to perform a specific task multiple times. Instead of rewriting the same code, we can group a block of code together and associate it with one task, then we can reuse that block of code whenever we need to perform the task again. We achieve this by creating a function. A function is a reusable block of code that groups together a sequence of statements to perform a specific task.


Funciton Declaration (선언형 함수)

a function declaration binds a function to a name, or an identifier.

function greetWorld() {
	console.log('greeting');
 }
  • The function keyword.
  • The name of the function, or its identifier, followed by parentheses.(In this case === greetWorld is identifier 식별자)
  • A function body, or the block of statements required to perform a specific task, enclosed in the function’s curly brackets, { }.
  • To call function you do identifierName() use parenthesis.

Hoisting

  • variable let, var, and function declaration.
  • Allows access to function declarations before they’re defined.
greetWorld(); // Output: Hello, World!
 
function greetWorld() {
  console.log('Hello, World!');
}
  • Not so good practice in actual working environment.
    자세한 내용은 다른 아티클로 서술 해야겠다...

Parameters(매개변수)

functions can take inputs and use the inputs to perform a task. When declaring a function, we can specify its parameters. Parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.

  • They act just like regular variables.

Arguments

The values that are passed to the function when it is called are called arguments. Arguments can be passed to the function as values or variables.

  • The order in which arguments are passed and assigned follows the order that the parameters are declared.
  • Can be data value, and variables.

By using parameters and arguments, functions can be reused to compute.

Default Parameters

  • Default parameters allow parameters to have a predetermined value in case there is no argument passed into the function or if the argument is undefined when called.
  • Useful to have in case we ever want to include a default value when a function is called without an argument.
function greeting (name = 'stranger') {
  console.log(`Hello, ${name}!`)
}
 
greeting('Nick') // Output: Hello, Nick!
greeting() // Output: Hello, stranger!
  • When the code calls greeting('Nick') the value of the argument is passed in and, 'Nick', will override the default parameter of 'stranger' to log 'Hello, Nick!' to the console. -> name being 'Nick' instead of 'stranger'

  • When there isn’t an argument passed into greeting(), the default value of 'stranger' is used, and 'Hello, stranger!' is logged to the console.

  • default parameters 없인 function 은 undefined을 리턴 합니다.

  • By using a default parameter, we account for situations when an argument isn’t passed into a function that is expecting an argument.

return keyword

  • When a function is called, the computer will run through the function’s code and evaluate the result of calling the function. By default that resulting value is undefined.
  • To pass back information from the function call, we use a return statement.
  • When a return statement is used in a function body, the execution of the function is stopped and the code that follows it will not be executed. Look at the example below:
function rectangleArea(width, height) {
  if (width < 0 || height < 0) {
    return 'You need positive integers to calculate area!';
  }
  return width * height;
}

If an argument for width or height is less than 0, then rectangleArea() will return 'You need positive integers to calculate area!'. The second return statement width * height will not run.

Helper Functions

  • We can also use the return value of a function inside another function. These functions being called within another function are often referred to as helper functions.

  • Since each function is carrying out a specific task, it makes our code easier to read and debug if necessary. === moduluar way of coding.

  • We can use functions to section off small bits of logic or tasks, then use them when we need to. Writing helper functions can help take large and difficult tasks and break them into smaller and more manageable tasks.

Function Expressions

  • In a function expression, the function name is usually omitted.
  • A function with no name is called an anonymous function.
  • A function expression is often stored in a variable in order to refer to it.
  • Since the release of ES6, it is common practice to use const as the keyword to declare the variable name (identifier)for function expression.
  • To invoke a function expression, write the name of the variable in which the function is stored followed by parentheses enclosing any arguments being passed into the function.

Function expressions aren’t hoisted. This allows them to retain a copy of the local variables from the scope where they were defined.

Arrow function

  • ES6 feature a shorter way to write functions.

Concise Body Arrow Functions

The most condensed form of the function is known as concise body.

  1. Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, if a function takes zero or multiple parameters, parentheses are required.
const functionName = () => {**do something**};
const functionName2 = param => {**do something with param**};
const functionName3 = (param, param2) => {**do something with given params**};
  1. A function body composed of a single-line block does not need curly braces. Without the curly braces, whatever that line evaluates will be automatically returned. The contents of the block should immediately follow the arrow => and the return keyword can be removed. This is referred to as implicit return.
const functionName4 = param => param * 2;

Review

  • A function is a reusable block of code that groups together a sequence of statements to perform a specific task.

  • A function declaration : hoisting available

  • A parameter is a named variable inside a function’s block which will be assigned the value of the argument passed in when the function is invoked.

  • ES6 introduces new ways of handling arbitrary(임의적) parameters through default parameters which allow us to assign a default value to a parameter in case no argument is passed into the function.

  • To return a value from a function, we use a return statement.

  • To define a function using function expressions: no hoisting but more readable.

  • To define a function using arrow function notation: better readability and concise form.

  • When to use either function declaration or function expression? --> expression when no need of hoisting.

profile
coder for web development + noodler at programming synthesizers for sound design as hobbyist.
post-custom-banner

0개의 댓글