[JavaScript] functions

Cadet_42ยท2021๋…„ 8์›” 9์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
8/8
post-thumbnail

๐Ÿ”ฎ What is a functions?

Functions are one of the fundamental building blocks in JavaScript. A function is a set of statements that performs a particular task of the program. This task could be just a little part of a program or even the whole program.

๐Ÿ’กDeclaring a function in JS

  • The function declaration is the process of creating function, but not executing it.
function sayHi()
{
  console.log('Hello!');
}
  • The process of executing(calling) the function is known as function invocation

==> as many as times as you invoke the function, that many times it will execute the code between the curly braces.
( in our case: 'Hello!');

sayHi();

๐Ÿ’ก Function Syntax

// keyword  function   parameters (if any)
// ^         name  ________|
// |          |   |
function sayHello() {
  // the code or so called the body of the function
  // return an expression (if needed)
}

๐Ÿ’ก Arguments and Parameters

// function declaration with a parameter
function sayHello(language) {
  switch (language) {
    case 'fr':
      console.log('Bonjour!');
      break;
    case 'ger':
      console.log('Hallo!');
      break;
    case 'esp':
      console.log('Hola!');
      break;
    default:
      console.log('Hello!');
  }
}

// function invocation with or without an argument
sayHello('ger'); // => Hallo!
sayHello('fr'); // => Bonjour!
sayHello('esp'); // => Hola!
sayHello(); // => Hello!
  • Parameter is the variable between the parentheses which is part of the function declaration. In the case above: The language variable. Note that this word is a placeholder and can be any word possible.
  • Argument is the value passed to the function at the moment of its invocation. In the case above: The different strings ger, fr, or esp that are passed and stored in the parameter.
// we passed argument "ger"
//                      |
//           -----------
//          |
sayHello('ger'); // => Hallo!

// we passed argument "fr"
sayHello('fr'); // => Bonjour!

// we passed argument "esp"
sayHello('esp'); // => Hola!

// we didn't pass any arguments, so the default part was executed
sayHello(); // => Hello!
profile
์•ˆ๋…•ํ•˜์„ธ์š”! ๊ฐœ๋ฐœ๊ณต๋ถ€๋ฅผ ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํžˆ ๋ฐฐ์šฐ๊ฒ ์Šต๋‹ˆ๋‹ค. ;)

0๊ฐœ์˜ ๋Œ“๊ธ€