Babelと最もよく使われるes 6、es 11の文法を整理します


夢のコードby Ellyの原始のビデオのショートカット
関連概念整理はDREAMCODE BY ELLYのビデオで整理されています

es6(2015)


es 6以降、internelt explorerではこの機能はサポートされていません.だからbabelを使う

babelとは何ですか。


babelはコンパイラですしかし、以下、これについてさらに説明する.

Interpreter


JavaScriptはインタラクティブな言語です.C,Javaなどの高度な言語を機械が聞き取れる言語に翻訳して実行する言語をコンパイル言語,ソースコード自体が実行する方式を割り込みと呼ぶ.この両者の最大の違いは,前処理とコンパイルの有無に帰結できる.

V 8エンジン始動


では、なぜコンパイラが必要なのでしょうか.の始点はV 8エンジンの始点にあります.JavaScriptの目標は、HTMLを動的に作成することですが、その後、多くのユーザーが対話し、より良いエンジンが必要になります.

JavaScriptエンジンは、エンジン内部でコンパイルされ、Interpreterによってコードが読み込まれて実行されます.コードの実行中に、Profilerはコンパイラに観察および最適化可能なコードを渡します.主に繰り返し実行されるコードブロック(Optimizer)をコンパイルします.
コードはまず解釈器で実行され、必要に応じてコンパイルされ、JITコンパイラと呼ばれます.
結論として、JavaScriptは実行プラットフォームに基づいて、使用中断とコンパイルを混合する.これにより、JavaScriptのパフォーマンスが大幅に向上します.

TranspillとCompile


Babel is a JavaScript compiler
ではBabyは何ですか?前述したようにbabelはコンパイラです.
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
要するに,es 6+構文は古いブラウザ(Internet expoler)では機能しない.だから私はbabelを通じて最新の文法を旧式に変換する友达が必要です.でもTranspillって何ですか?
Compile
コンパイルの場合、1つの言語で記述されたソースコードを別の言語に変換することを意味します.
典型的な例としては、Java→バイトコード、C→Assemblyが挙げられる.
Transpile
変換ファイルとは、ある言語で記述されたソースコードを、類似レベルで抽象化された別の言語に変換することです.たとえば、変換ファイルは次のようになります.
  • es 6コード→es 5コードに変換した場合:
  • c++ → c
  • typescript → javascript
  • 要するにTranspilerはsource to sourceコンパイラと言える.つまり、コンパイラは最大のカテゴリにあり、次はコンパイラです.

    ES 6構文クリーンアップ


    Shorthand poperty names


    With Shorthand Properties, whenever you have a variable which is the same name as a property on an object, when constructing the object, you can omit the property name.
    次のパラメータとプロパティは、例では同じです.したがって、propertyのkeynameは省略できます.これは関数にも適用されます.
    function formatMessage (name, id, avatar) {
      return {
        name: name,
        id: id,
        avatar: avatar,
        timestamp: Date.now()
    		save: function () {
          // save message
        }
      }
    }
    
    function formatMessage (name, id, avatar) {
      return {
        **name,
        id,
        avatar,**
        timestamp: Date.now()
    		save () {
          //save message
        }
      }
    }
    
    /**
     * Shorthand property names
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Object_initializer
     *
     */
    
    {
      const ellie1 = {
        name: 'Ellie',
        age: '18',
      };
    
    	//상단에 Object 안에 property와 동일한 key name의 property가 있다면 
    	//property 의 값은 상단에 선언된 내용을 따릅니다. 
    	
      const name = 'Ellie';
      const age = '15';
    
      // 💩
      const ellie2 = {
        name: name,
        age: age,
      };
    
      // ✨
      const ellie3 = {
        name,
        age,
      };
    
      console.log(ellie1, ellie2, ellie3);
      console.clear();
    }
    {name: 'Ellie', age: '18'} {name: 'Ellie', age: '15'} {name: 'Ellie', age: '15'}

    ぶんぱいせっけいこうぞう


    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
    /**
     * Destructuring Assignment
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
     *
     */
    {
      // object
      const student = {
        name: 'Anna',
        level: 1,
      };
    
      // 💩
      {
        const name = student.name;
        const level = student.level;
        console.log(name, level);
      }
    
      // ✨
      {
        const { name, level } = student;
        console.log(name, level); // Anna, 1
    
        const { name: studentName, level: studentLevel } = student;
        console.log(studentName, studentLevel); //변수 명을 다르게 해줬으니 console도 다르게 찍어줘야 합니다.
      }
    
      // array
      const animals = ['🐶', '😽'];
    
      // 💩
      {
        const first = animals[0];
        const second = animals[1];
        console.log(first, second);
      }
    
      // ✨
      {
        const [first, second] = animals; //array도 동일하게 적용할 수 있습니다. 
        console.log(first, second);
      }
      console.clear();
    }
    配列が宣言されているためundefinedが表示されますが、greenとblueには参照可能な値がありません.Default valueを使用できます.
    const foo = ['one', 'two'];
    
    const [red, yellow, green, blue] = foo;
    console.log(red); // "one"
    console.log(yellow); // "two"
    console.log(green); // undefined
    console.log(blue);  //undefined
    
    const foo = ['one', 'two'];
    
    const [red, yellow, green="three", blue="four"] = foo;
    console.log(red); // "one"
    console.log(yellow); // "two"
    console.log(green); // "three"
    console.log(blue);  // "four"

    Spread syntax


    Spread syntax ( ... ) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
    Spread syntax can be used when all elements from an object or array need to be included in a list of some kind
    /**
     * Spread Syntax
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
     *
     */
    {
      const obj1 = { key: 'key1' };
      const obj2 = { key: 'key2' };
      const array = [obj1, obj2];
    
      // array copy
    	// 복사된 arrayCopy와 array는 동일한 객체를 참조하고 있기 때문에 같은 값이 출력됩니다.
      const arrayCopy = [...array];
      console.log(array, arrayCopy);
    
      const arrayCopy2 = [...array, { key: 'key3' }];
      obj1.key = 'newKey';
      console.log(array, arrayCopy, arrayCopy2);
    
      // object copy
      const obj3 = { ...obj1 };
      console.log(obj3);
    
      // array concatenation
      const fruits1 = ['🍑', '🍓'];
      const fruits2 = ['🍌', '🥝'];
      const fruits = [...fruits1, ...fruits2];
      console.log(fruits); //['🍑', '🍓', '🍌', '🥝']
    
      // object merge
      const dog1 = { dog: '🐕' };
      const dog2 = { dog: '🐶' };
      const dog = { ...dog1, ...dog2 }; // 동일한 key 값이 존재한다면 뒤에 있는 value가 앞에 덮어 씌워 집니다.
      console.log(dog); // 🐶
      console.clear();
    }

    Default parameters

    /**
     * Default parameters
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Default_parameters
     */
    {
      // 💩
      {
        function printMessage(message) {
          if (message == null) {
            message = 'default message';
          }
          console.log(message);
        }
    
        printMessage('hello');
        printMessage();
      }
    
      // ✨
      {
        function printMessage(message = 'default message') { //파라메터의 기본 값을 지정하여 null값을 체크하지 않아도 됩니다.
          console.log(message);
        }
    
        printMessage('hello');
        printMessage(); //default message
      }
      console.clear();
    }

    Conditional(Ternary) Operator


    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is  truthy  followed by a colon ( : ), and finally the expression to execute if the condition is  falsy . This operator is frequently used as an alternative to an  [if...else](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)  statement.
    これですか.うん:考えてみれば気持ちがいいじゃないか.
    /**
     * Ternary Operator
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
     */
    {
      const isCat = true;
      // 💩
      {
        let component;
        if (isCat) {
          component = '😸';
        } else {
          component = '🐶';
        }
        console.log(component);
      }
    
      // ✨
      {
        const component = isCat ? '😸' : '🐶';
        console.log(component);
        console.log(isCat ? '😸' : '🐶');
      }
      console.clear();
    }
    Handling null値に使用できます.
    let greeting = person => {
        let name = person ? person.name : `stranger`return `Howdy, ${name}`}
    
    console.log(greeting({name: `Alice`}));  // "Howdy, Alice"
    console.log(greeting(null));

    Template Literals


    +で文字列を表す必要はありません.変数を`(ベクトル)に${}で表すことができます.
    /**
     * Template Literals
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals
     */
    {
      const weather = '🌤';
      const temparature = '16°C';
    
      // 💩
      console.log(
        'Today weather is ' + weather + ' and temparature is ' + temparature + '.'
      );
    
      // ✨
      
      console.log(`Today weather is ${weather} and temparature is ${temparature}.`);
    es11(2020)

    Optional chaining


    The optional chaining operator ( ?. ) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
    The  ?.  operator is like the  .  chaining operator, except that instead of causing an error if a reference is  nullish  ( null  or  undefined ), the expression short-circuits with a return value of  undefined . When used with function calls, it returns  undefined  if the given function does not exist.
    This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.
    Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.
    The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be  undefined  or  null .let nestedProp = obj.first?.second;の解釈は以下の通りである.
    let temp = obj.first;
    let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
    /**
     * 관련 강의 영상: https://youtu.be/36HrZHzPeuY
     */
    /**
     * Optional Chaining (ES11)
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining
     */
    {
      const person1 = {
        name: 'Ellie',
        job: {
          title: 'S/W Engineer',
          manager: {
            name: 'Bob',
          },
        },
      };
      const person2 = {
        name: 'Bob',
      };
    
      // 💩💩💩💩💩💩
      {
        function printManager(person) {
          console.log(person.job.manager.name);
        }
        printManager(person1);
        // printManager(person2); 매니저가 존재하지 않아 문제가 발생
      }
    
      // 💩💩💩
    	//Ternary Operation 을 이용
    	//코드의 반복이 존재하기 때문에 불편함.
      {
        function printManager(person) {
          console.log(
            person.job
              ? person.job.manager
                ? person.job.manager.name
                : undefined
              : undefined
          );
        }
        printManager(person1);
        printManager(person2);
      }
    
      // 💩
    	// 이또한 코드의 반복이 계속적으로 반복되어서 보기 안좋다.
      {
        function printManager(person) {
          console.log(person.job && person.job.manager && person.job.manager.name);
        }
        printManager(person1);
        printManager(person2);
      }
    
      // ✨
    	//optional Chaining
      {
        function printManager(person) {
          console.log(person.job?.manager?.name);
        }
        printManager(person1);
        printManager(person2);
      }
      console.clear();
    }
    Nullish coalescing operator(??)
    The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is  null  or  undefined , and otherwise returns its left-hand side operand.
    論理OR演算子でfalseには次の内容が含まれます.
  • null ;
  • NaN ;
  • 0 ;
  • empty string ( ""  or  ''  or ````);
  • undefined .
  • const foo = null ?? 'default string';
    console.log(foo);
    // expected output: "default string"
    
    const baz = 0 ?? 42;
    console.log(baz);
    // expected output: 0
    /**
     * Nullish Coalescing Operator (ES11)
     * https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
     */
    {
      // Logical OR operator
      // false: false, '', 0, null, undefined
      {
        const name = 'Ellie';
        const userName = name || 'Guest';
        console.log(userName);
      }
    
      {
        const name = null;
        const userName = name || 'Guest';
        console.log(userName);
      }
    
      // 💩
      {
        const name = ''; //false
        const userName = name || 'Guest';
        console.log(userName); //Guest
    
        const num = 0; //false로 간주
        const message = num || 'undefined';
        console.log(message); //undefined
      }
    
      // ✨
      {
        const name = '';
        const userName = name ?? 'Guest'; //이름에 이름이 있다면 이름을 쓰고 없다면 Guest를 쓰자.
        console.log(userName);
    
        const num = 0;
        const message = num ?? 'undefined';
        console.log(message);
      }
    }