JavaScript 11

JavaScript 11

Closures

Closures 允許 inner function 可以保留並存取 outer function scope 所在的 variables,即便 outer function 已經執行完畢。

function outerFunction() {
  const outerVariable = 'I am outside!';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const closure = outerFunction();

closure(); // Output: I am outside!

Array.prototype.filter()

基本語法:filter(callbackFn, thisArg)

  • callbackFn 裡面依序有三個參數可以傳入:element, index, array

  • thisArg 是 optional,可以綁定 callbackFn 中的 this

Array.prototype.sort()

If you want to sort numbers or sort based on a specific condition, you can pass a compare function to array.sort(compareFn).

This function should return a negative, zero, or positive value, depending on the arguments, like:

  • a negative value if a should be sorted before b .

  • a positive value if a should be sorted after b .

  • zero if a and b are equal and their order doesn't matter.

const array = [5,4,3,2,1]
array.sort(function(a, b) {
  return a - b;
});
console.log(array) // [1, 2, 3, 4, 5]

Callback hell

  • 一層ㄧ層的 callback function 被嵌套著。

  • 特色是難以維護及閱讀。

function asyncOperation1(callback) {
  setTimeout(() => {
    console.log('Async Operation 1');
    if (Math.random() < 0.5) {
      callback(null, 'Data from async operation 1');
    } else {
      callback('Error in async operation 1');
    }
  }, 1000);
}

function asyncOperation2(data, callback) {
  setTimeout(() => {
    console.log('Async Operation 2');
    if (Math.random() < 0.5) {
      callback(null, 'Data from async operation 2');
    } else {
      callback('Error in async operation 2');
    }
  }, 1000);
}

function asyncOperation3(data, callback) {
  setTimeout(() => {
    console.log('Async Operation 3');
    if (Math.random() < 0.5) {
      callback(null, 'Data from async operation 3');
    } else {
      callback('Error in async operation 3');
    }
  }, 1000);
}

asyncOperation1((error1, data1) => {
  if (error1) {
    console.error(error1);
    return;
  }

  asyncOperation2(data1, (error2, data2) => {
    if (error2) {
      console.error(error2);
      return;
    }

    asyncOperation3(data2, (error3, data3) => {
      if (error3) {
        console.error(error3);
        return;
      }

      console.log('Final result:', data3);
    });
  });
});

Hoisting

  • 使用 var 宣告的變數會被提升到其作用域的頂部並初始化為 undefined

  • 使用 function 宣告的函式也會被提升到其作用域的頂部,包括其函式本身。

  • 使用 letconst 宣告的變數也會被提升到其區作用域的頂部,但不會被初始化。在宣告之前嘗試存取的話會導致 ReferenceError

currying function

  • 是一種將具有 n 個參數的函式轉換成一系列具有 n 個參數的函式的技巧。

  • 好處是可以拆分參數的處理,提高程式碼的彈性,利於重複使用。

      //before 
      function add(x, y) {
        return x + y;
      }
    
      console.log(add(5, 3));  // Outputs: 8
    
      //after
      function add(x) {
        return function(y) {
          return x + y;
        };
      }
    
      let addFive = add(5);
      console.log(addFive(3));  // Outputs: 8
      console.log(addFive(10));  // Outputs: 15