Skip to content

Latest commit

 

History

History
115 lines (87 loc) · 1.73 KB

File metadata and controls

115 lines (87 loc) · 1.73 KB

Objects & Advanced Concepts

JavaScript Object

Objects are key-value collections.

const user = {
  name: "Sam",
  age: 20,
};

console.log(user.name);
console.log(user["age"]);

What is a Method?

A method is a function stored on an object.

const counter = {
  value: 0,
  inc() {
    this.value += 1;
  },
};

counter.inc();
console.log(counter.value); // 1

this Keyword

this depends on how a function is called.

const obj = {
  x: 1,
  show() {
    return this.x;
  },
};

const f = obj.show;
console.log(obj.show()); // 1
console.log(f()); // undefined in strict mode (or global object in sloppy mode)

Arrow functions capture this from the surrounding scope.

Array Destructuring & Object Destructuring

const [a, b] = [1, 2];
const { name, age: years } = { name: "A", age: 10 };

console.log(a, b, name, years);

Defaults:

const [x = 0] = [];
const { ok = false } = {};

Hoisting

  • Function declarations are hoisted (callable before definition).
  • var declarations are hoisted (initialized to undefined).
  • let/const are hoisted but in the Temporal Dead Zone until initialized.
hoisted();
function hoisted() {
  console.log("works");
}

Closure

A closure is when a function retains access to variables from its outer scope.

function makeCounter() {
  let n = 0;
  return () => {
    n += 1;
    return n;
  };
}

const c = makeCounter();
console.log(c()); // 1
console.log(c()); // 2

Higher Order Function

HOFs take functions as arguments or return functions.

const once = (fn) => {
  let used = false;
  let value;
  return (...args) => {
    if (!used) {
      used = true;
      value = fn(...args);
    }
    return value;
  };
};