JavaScript 시작하기 - 3장 🚀

목차
* 🤓 INTRODUCTION
* 👩🏻‍🔬 FUNCTIONS
* 👔 BINDINGS AND SCOPES
* 🦅 NESTED SCOPES
* 🏹 ARROW FUNCTIONS
* 📚 CALL STACK
* ❔ OPTIONAL ARGUMENTS
* ➰ RECURSION
* 📝 SUMMARY
* 🙏 THANK YOU

🤓 소개

**Welcome, my dear coders! I hope you are all having a codelicious weekend! Here we are, at our third chapter of the Getting started with javascript series. Today, we will tackle the functions, scopes, bindings, different types of function, the call stack and more. Stay with me, let's learn JavaScript and get you a first programming job! 🚀

I am hyped!

👩🏻‍🔬 기능

The day before yesterday, I discussed a function, where we explained that the functions represent the concept of wrapping a piece of a program. It gives us a way to structure larger programs, assign subprograms a name, reduce repetition, and isolate these subprograms from each other.

기능 정의



함수 정의는 바인딩 값이 함수인 일반 바인딩입니다. 주어진 숫자의 제곱을 생성하는 함수를 정의해 봅시다.

const square = function(x){
   return x*x;
};
console.log(square(8)); //output: 64


기능을 만드는 재료


  • 키워드 function으로 시작하는 표현식입니다.

  • 매개변수 세트(이 경우 x)

  • 함수 본문 - 함수가 호출될 때 실행될 명령문을 포함합니다.

  • 👔 바인딩 및 범위

    Each binding has a scope, which is the part of the program in which the binding is visible. For binding defined outside of any function or block, the scope is the whole program - also known as global scope.

    Bindings that are created for function parameters or declared inside a function can be referenced only in that function - also known as local scope.

    Example:

    let x = 3;
    if (true){
      let y = 25;
      var z = 3;
      console.log(x + y + z); // output: 31
    }
    //y is not visible here 
    //but z is visible, because it is declared as var not let
    //if we declare a variable in local scope with the var keyword
    //a variable will be visible outside the local scope
    //does not apply to variables declared with let keyword
    console.log(x + z); //output: 6
    

    If we were to access y outside local scope we would get something like this:

    Uncaught ReferenceError: y is not defined

    🦅 중첩 범위

    JavaScript distinguishes not just global and local bindings. Blocks and functions can be created inside other blocks and functions, producing multiple degrees of the locality.

    const pizza_dough = (factor) =>{
      const ingredient = function(amount, unit, name){
        let ingredientAmount = amount*factor;
        if (ingredientAmount > 1){  
          unit += "s";
        }
        console.log(`${ingredientAmount} ${unit} ${name}`);
      };
      ingredient(0.5, "cup", "warm water");
      ingredient(1, "package", "active dry yeast");
      ingredient(3, "cup", "bread flour");
      ingredient(2, "tablespoon", "extra virgin oil");
      ingredient(2, "teaspoon", "salt");
      ingredient(1, "teaspoon", "sugar");
    }
    pizza_dough(1);
    

    The code inside the ingredient function can see the factor binding from the outer function. But its local bindings, such as unit or ingredientAmount are not visible in the outer function;

    🏹 화살표 기능

    In the previous code section, I used what is called an arrow function. So, instead of the function keyword, it uses an arrow made up of an equal sign and a greater-than character (=>)

    The arrow comes after the list of parameters and is followed by the function's body. It expresses something like this specific input, with specific parameters, will produce the following result;

    Let's convert our square function into an arrow function:

    const square = (x) => { return x*x; }; //an arrow function
    const square = x => x*x; //remove paranthesees when only parameter
    

    These are the same arrow functions and will produce the same result as a regular function notation.

    📚 호출 스택

    A call stack is a stack data structure (that we will talk about very soon) that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or machine stack.

    콜 스택은 무엇을 합니까?



    호출 스택의 주요 목적은 반환 주소를 저장하는 것입니다. 서브루틴이 호출되면 호출 루틴이 나중에 재개될 수 있는 명령의 위치(주소)를 어딘가에 저장해야 합니다.

    호출 스택에서 각 작업은 자체 스택을 가질 수 있으므로 서브루틴은 thread-safe 일 수 있습니다. 즉, 다른 작업을 수행하는 여러 작업에 대해 동시에 활성화될 수 있습니다.

    언어, 운영 체제 및 시스템 환경에 따라 호출 스택은 다음과 같은 추가 용도를 제공할 수 있습니다.
  • 로컬 데이터 저장소
  • 매개변수 전달
  • 평가 스택
  • 현재 인스턴스에 대한 포인터
  • 엔클로징 서브루틴 컨텍스트
  • 다른 반환 상태

  • 호출 스택 구조



    호출 스택은 스택 프레임(활성화 레코드 또는 활성화 프레임)으로 구성됩니다. 스택의 시각적 표현은 바로 스택입니다.



    스택 맨 위에 있는 스택 프레임은 현재 실행 중인 루틴을 위한 것입니다. 스택 프레임에는 일반적으로 적어도 다음 항목이 포함됩니다(푸시 순서로).
  • 루틴에 전달된 인수(매개 변수 값)
  • 루틴의 호출자에게 돌아가는 반환 주소
  • 루틴의 로컬 변수를 위한 공간

  • 스택 작업의 예:


  • 푸시 - 스택 맨 위에 요소를 추가합니다(OverflowException)
  • .

  • pop - 스택 맨 위에서 요소를 읽고 제거합니다(UnderflowException)
  • .

  • getTop - 스택 맨 위에서 요소를 읽지만 제거하지는 않습니다
  • .

  • isEmpty - 스택이 비어 있는지 확인합니다
  • .

  • numberOfElements - 스택의 요소 수를 가져옵니다
  • .

    ❔ 선택적 인수

    JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass to few, the missing parameters get assigned the value of undefined.
    DOWNSIDE - it is possible - likely, even - that you'll accidentally pass the wrong number of arguments to
    UPSIDE - Behaviour can be used to allow a function to be called with different numbers of arguments.

    Example:

    function minus(a, b){
      if (b === undefined) return -a;
      else return a-b;
    };
    console.log(minus(10)); //output: -10
    console.log(minus(10, 5)); //output: 5
    
    

    ➰ 재귀

    It is perfectly okay for a function to call itself, as long as it doesn't do it so often that it overflows the stack. A function that calls itself is called a recursive function.

    function power(base, exponent){
      if (exponent === 0){
        return 1;
      } else{
        return base * power(base, exponent - 1);
      }
    }
    console.log(power(3, 2)); //output: 9
    

    This is very close to the way mathematicians define exponentiation and arguably describes the concept more clearly than the looping variant.

    The problem with this implementation is that in typical JavaScript implementation it's about three times slower than the looping version.

    📝 요약

    • The functions represent the concept of wrapping a piece of a program. It gives us a way to structure larger programs, assign subprograms a name, reduce repetition, and isolate these subprograms from each other.
    • Binding defined outside of any function or block, the scope is the whole program - also known as global scope.
    • Bindings that are created for function parameters or declared inside a function can be referenced only in that function - also known as local scope.
    • Blocks and functions can be created inside other blocks and functions
    • The arrow comes after the list of parameters and is followed by the function's body. It expresses something like this specific input, with specific parameters, will produce the following result
    • A call stack is a stack data structure (that we will talk about very soon) that stores information about the active subroutines of a computer program.
    • The primary purpose of the call stack is to store the return addresses.
    • The call stack is composed of Stack frames (activation records or activation frames).
    • JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass to few, the missing parameters get assigned the value of undefined.
    • A function that calls itself is called a recursive function.

    🙏 읽어주셔서 감사합니다!

    References:
    School notes...
    School books...

    Please leave the comment, tell me about you, about your work, comment your thoughts, connect with me!

    ☕ SUPPORT ME AND KEEP ME FOCUSED!


    즐거운 해킹 시간 되세요! 😊

    좋은 웹페이지 즐겨찾기