Skip to content

Instantly share code, notes, and snippets.

@dgca
Created July 7, 2021 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgca/04c6bbae8c069718a322d86d9ea93752 to your computer and use it in GitHub Desktop.
Save dgca/04c6bbae8c069718a322d86d9ea93752 to your computer and use it in GitHub Desktop.
Different ways of assigning the same value to different variable declarations

Different ways of assigning the same value to different variable declarations

Assignment waterfall

const x = y = z = Symbol('hi');

console.log(x === y && y === z);

Object destructuring assignment with renamed variable names

const { value: x, value: y, value: z } = { value: Symbol('hi') };

console.log(x === y && y === z);

Array destructuring assignment with handrolled array

const [x, y, z] = (function() {
  const value = Symbol('hi');
  return [value, value, value];
})();

console.log(x === y && y === z);

Array destructuring assignment with generator function

const [x, y, z] = (function*() {
  const value = Symbol('hi');
  while(true) {
    return value;
  }
})();

console.log(x === y && y === z);

Object destructuring assignment with handrolled object

const { x, y, z } = (function() {
  const value = Symbol('hi');
  return {
    x: value,
    y: value,
    z: value,
  };
})();

console.log(x === y && y === z);

Object destructuring assignment with proxied object

const { x, y, z } = new Proxy({ value: Symbol('hi') }, {
  get(target) {
    return target.value;
  }
});

console.log(x === y && y === z);

Array destructuring assignment with proxy acting as generator

const [x, y, z] = new Proxy({ value: Symbol('hi') }, {
  get(target, prop, receiver) {
    if (prop === Symbol.iterator) {
      return () => receiver;
    }
    if (prop === 'next') {
      return () => ({
        done: false,
        value: target.value
      })
    }
  }
});

console.log(x === y && y === z);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment