JS Puzzlers

Are you sure you know JavaScript ? (remake)

JS features usage overview

State of JS 2019

Syntax

Spread operator

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
  return 4;
}

console.log([...gen()]);

What will be the output ?

What is "Spread Operator" exactly does ?

The spread operator is used to expand elements of an iterable (like an array) into places where multiple elements can fit.

What is an iterator ?

Object that knows how to access items from a collection one at a time, while keeping track of its current position within that sequence.

The iterable protocol

In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator:

Iterator object have a next() method which returns the next item in the sequence.

This method returns an object with two properties: done and value.

{value: ‘Current value of iteration’, done: ‘true/false’}

const genInstance = gen();

genInstance.next();
//{value: 1, done: false}

genInstance.next();
//{value: 2, done: false}

genInstance.next();
//{value: 3, done: false}

genInstance.next();
//{value: 4, done: true}

Spread operator doesn't count objects with "done: true"

function* gen() { 
  yield 1;
  yield 2;
  yield 3;
  return 4;
}

console.log([...gen()]);

// [1, 2, 3]

Destructuring

const data = {
   a: 1,
   b: undefined,
   c: null,
}

const { a = 2, b = 3, c = 4, d = 5 } = data;

console.log(a,b,c,d);

What is the output ?

Destructuring supprts default values

Null !== undefined

Arrow functions

How to distingwish between plain old function with an arrow function ?

function isArrowFunction(fn) {
  return /* ? */
}

isArrowFunction(() => console.log(1)) // true
isArrowFunction(function(){console.log(2)}) // false

prototype does not exist for an arrow function.

More puzzles ?

Is this valid ?

const x = {[{}]:[{}]}

What is the actual value of x ?

What is the actual value of y ?

const y = {[{}](){[]}}

What about this one ?

Data structures

Maps

Why we need Map() if we can use just objects ?

const map = new Map();
map.set("hello world", "💩");
map.get("hello word"); // 💩

const map2 = {};
map2["hello word"] = "💩";
map2["hello word"]; // 💩
  • The key difference is that Objects only support string keys where as Maps support more or less any key type.
  • A Map object can iterate its elements in insertion order

Map vs objects

Sets

NaN === NaN ?

NaN == NaN ?

false

new Set().add(NaN).add(NaN)
// ???

So will we have Two NaN's or only One ?

APIs

Fetch

Everyone knows about it, right ?

const promise = fetch(url) 
  .then((response) => {
    return response;
  })
  .catch((err) => {
    console.log(err);
  });

Fetching some data...

And response doesn't come for a while...

Abort a fetch ?

Axios has build-in cancel() method which gives you an opportunity to abort requests which aren’t yet resolved or rejected.

Native fetch API ?

AbortController !

Represents a controller object that allows you to abort one or more Web requests as and when desired

const url = "https://api.github.com/users";

const controller = new AbortController();
const signal = controller.signal;

const promise = fetch(url, {signal}) 
// you can see we pass signal to fetch params
  .then((response) => {
    return response;
  })
  .catch((err) => {
    console.log(err);
  });

controller.abort();

Example

Browser compatibility

Local Storage

const parent = { child: { hi: "all" } };
localStorage.setItem("parent", parent);

console.log(
  localStorage.getItem("parent").child  // ?
);

What will be the output ?

Local storage can only store string pairs!

To store objects in LocalStorage you have to stringify them

JSON.stringify(category1); ???

We can't stringify circular references!

How to store two-way linked lists/trees then ?

Made with Slides.com