Skip to content

Latest commit

 

History

History
341 lines (280 loc) · 9.29 KB

File metadata and controls

341 lines (280 loc) · 9.29 KB

Author: Confy-Code Date: 2026-May-29


ES6 - UDACITY NOTES

  1. let, const and var keywords
  • let and const: block-scoped variable declaration, no hoisting, no redeclaration
  • var: function-scoped variable declaration, hoisting, redeclaration allowed

  1. Template literals --> (${}) Example:
const name = "Alice";
const greeting = `Hello, ${name}!`;

  1. Object literal shorthand (elimination of keyword 'function') Example:
const obj = {
  method() {
    console.log("This is a method.");
  }
};

instead of:
const obj = {
  method: function() {
    console.log("This is a method.");
  }
};  

  1. Array properties ==> Array.prototype.decimalfy [TO SEE]

  2. Pythonic capitalize() equivalence in JS:

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

  1. Rest parameter (2 uses: destructuring an array , variadic functions)
// Destructuring an array   
const [first, ...rest] = [1, 2, 3, 4];
// Variadic function
function sum(...numbers) {
  return numbers.reduce((acc, num) => acc + num, 0);
}

  1. Arrow functions are always expressions (Arrow function expressions)
  2. Arrow functions syntax(concise and block body syntaces)
// Concise body syntax
const add = (a, b) => a + b;
// Block body syntax
const add = (a, b) => {
    return a + b;
    };

  1. JS classes - use static functions for comparing the obj of the same class
class Person {
  constructor(name) {
    this.name = name;
  }

  static compare(person1, person2) {
    return person1.name === person2.name;
  }
}

  1. "Super" is used to pass variables child --> Parent class

  2. Symbol(description): Handle duplicate properties in an object.

const obj1 = {
  name: "Confy",
  [Symbol("id")]: 123
  [Symbol("id")]: 456
};

  1. Symbol.iterator: to simulate linked-lists
const arr = [1, 2, 3];
arr_values = arr[Symbol.iterator]();
console.log(arr_values.next()); // { value: 1, done: false }

while(!arr_values.next().done) {
  console.log(arr_values.next().value);
}

  1. Sets operations: .add, .delete, .clear
  2. Iterate through sets: setIterator & for...of
const mySet = new Set([1, 2, 3]);
const setIterator = mySet.values();

//using for...of loop
for (const value of mySet) {
  console.log(value);
}

//using setIterator
let result = setIterator.next();

  1. Weak sets: only objects (use it for double-deletion of objects)
const weakSet = new WeakSet();
let obj1 = { name: "Confy" };
weakSet.add(obj1);
console.log(weakSet.has(obj1)); // true
obj1 = null; // Remove reference to the object
// After garbage collection, the object will be removed from the weak set
  1. Garbage collection: automatic memory management, removes unused objects from memory

  2. Map ops: .set(), .delete(key), .clear, .has, .get

const myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
console.log(myMap.get("key1")); // value1
console.log(myMap.has("key2")); // true
myMap.delete("key1");
myMap.clear();

  1. Map iterations: MapIterator, for...of, .forEach()
const myMap = new Map([["key1", "value1"], ["key2", "value2"]]);
// Using MapIterator
const mapIterator = myMap.entries();

// Using for...of loop
for (const [key, value] of myMap) {
  console.log(`${key}: ${value}`);
}
// Using .forEach() method
myMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

  1. destructuring needs brackets!
  2. weakMap(): only object-keys
const weakMap = new WeakMap();
let objKey = { name: "Confy" };
weakMap.set(objKey, "This is a value");
console.log(weakMap.get(objKey)); // This is a value
objKey = null; // Remove reference to the object
// After garbage collection, the object and its associated value will be removed from the weak map

  1. Promises: Full structure of a Promises
const myPromise = new Promise(function (resolve, reject) {
  const success = true;

  setTimeout(function () {
    if (success) {
      resolve('Ice cream is ready!');
    } else {
      reject('Sorry, no ice cream today.');
    }
  }, 1000);
});

console.log(myPromise);

myPromise.then(
  function (message) {
    console.log('Success:', message);
  },
  function (error) {
    console.log('Failed:', error);
  }
);

  1. PROXY: An object that stands in front of another object and intercepts operations on it
const richard = {status: "looking for a job"};
const handler = {
  get(target, property) {
    if (property === "status") {
      return "hired";
    }
    return target[property];
  }
};
const richardProxy = new Proxy(richard, handler);
console.log(richardProxy.status); // Output: "hired"

// using set trap to intercept property assignment
const handler = {
  set(target, property, value) {
    if (property === "status") {
      console.log("Status cannot be changed.");
      return false; // Prevent the assignment
    }
    target[property] = value; // Allow other properties to be set
    return true;
  }
};
const richardProxy = new Proxy(richard, handler);
richardProxy.status = "hired"; // Output: "Status cannot be changed."

richardProxy.name = "Richard"; // This will work, as it's not the "status" property
console.log(richardProxy.name); // Output: "Richard"

--

OTHER TRAPS:

  1. The get trap: Intercepts property access.
  2. The set trap: Intercepts property assignment.
  3. The has trap: Intercepts the in operator.
    const handler = {
      has(target, property) {
        if (property === "status") {
          return false; // Pretend that the "status" property does not exist
        }
        return property in target; // Default behavior for other properties
      }
    };
     const richardProxy = new Proxy(richard, handler);
     console.log("status" in richardProxy); // Output: false
     console.log("name" in richardProxy); // Output: true (assuming "name" is a property of the target object)
  4. The deleteProperty trap: Intercepts the delete operator.
  5. The apply trap: Intercepts function calls.
  6. The construct trap: Intercepts object instantiation with the new operator.
  7. The getOwnPropertyDescriptor trap: Intercepts Object.getOwnPropertyDescriptor() calls.
  8. The ownKeys trap: Intercepts Object.keys(), Object.getOwnPropertyNames(), ...

  1. DIFFERENCE BETWEEN PROXY & GETTER/SETTER ==> ES5 getter/setter: beforehand defined properties, only intercepts property access and assignment, cannot intercept other operations like function calls or object instantiation.

==> ES6 Proxy: can intercept a wide range of operations (property access, assignment, function calls, object instantiation, etc.), allows for dynamic behavior and more flexible object manipulation.


  1. GENERATORS AND ITERATORS
  • Generators: special functions that can be paused and resumed, defined with function* syntax, use yield to produce a sequence of values.
function* generatorFunction() {
  yield 1;
  yield 2;
  yield 3;
}
const generator = generatorFunction();
console.log(generator.next()); // { value: 1, done: false }

  • YIELD IN and OUT functions: yield can be used to receive input from the caller and also to produce output.
function* generatorFunction() {
  const input = yield "Please provide input";
  console.log("Received input:", input);
  yield "Thank you for the input!";
}
const generator = generatorFunction();
console.log(generator.next()); // { value: "Please provide input", done: false }
console.log(generator.next("Hello, Generator!")); // Logs: "Received input: Hello, Generator!" and returns { value: "Thank you for the input!", done: false }

  1. Ecma international: organization that standardizes JavaScript (ECMAScript) and JSON specifications, ensuring consistency and compatibility across different implementations of JavaScript.

  1. specs (specifications) : detailed documents that define the behavior and features of JavaScript, including syntax, semantics, and APIs. They serve as a reference for developers and implementers of JavaScript engines.

  1. Each browser maker (except for Safari) has a website that tracks its development status.

  1. POLYFILL: a piece of code (usually JavaScript) that implements a feature on web browsers that do not natively support it, allowing developers to use modern features while maintaining compatibility with older browsers.
if (!String.prototype.startsWith) {
  String.prototype.startsWith = function (searchString, position) {
    position = position || 0;
    return this.substr(position, searchString.length) === searchString;
  };
}

==> Other Polyfills include: SVG, HTML5, Video, WebSockets, etc.

  1. TRANSPILER: Converts the code from one language version to another, e.g, from ES6 to ES5, allowing developers to use modern JavaScript features while ensuring compatibility with older browsers that may not support those features.
  • Example: Babel -- a popular JavaScript transpiler that converts ES6+ code into ES5 code, JSX and Flow to JavaScript by using their website.

    To do this, Babel uses plugins and presets that define how specific features like arrow functions should be transformed.

    Plugins and presents can be configured in .babelrc file.