Skip to content

Instantly share code, notes, and snippets.

@paulwongx
Created December 1, 2023 19:38
Show Gist options
  • Save paulwongx/5473e75085dab2f87c8dcd479938849d to your computer and use it in GitHub Desktop.
Save paulwongx/5473e75085dab2f87c8dcd479938849d to your computer and use it in GitHub Desktop.
Javascript Cheatsheet

Javascript Cheatsheet

  1. This document focuses on more nuanced topics. It is not comprehensive.
  2. Examples are taken from MDN mostly

Strings

// [@@iterator]() - iterating a string
const str = 'A\uD835\uDC68';
const strIter = str[Symbol.iterator]();
console.log(strIter.next().value); // "A"
console.log(strIter.next().value); // "\uD835\uDC68"

// character codes
const sentence = 'The quick brown fox jumps over the lazy dog.';
sentence.charAt(4); // q
sentence.charCodeAt(4); // 113
'ABC'.codePointAt(0) // 65
'ABC'.codePointAt(0).toString(16) // 41
'😍'.codePointAt(0) // 128525
'\ud83d\ude0d'.codePointAt(0) // 128525
'\ud83d\ude0d'.codePointAt(0).toString(16) // 1f60d
"hello".concat(" ", "world"); // "hello world"
String.fromCharCode(189, 43, 190, 61); // "½+¾="
String.fromCodePoint(9731, 9733, 9842, 0x2F804); // "☃★♲你"


// Misc functions
"Cats are the best!".endsWith("best!"); // true     
sentence.includes("fox"); // true
sentence.indexOf("dog"); // 40
sentence.lastIndexOf("the") // 31

// comparing words
'a'.localeCompare('c'); // -1
'check'.localeCompare('against'); //  1
'a'.localeCompare('a'); // 0
let items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu'];
items.sort( (a, b) => a.localeCompare(b, 'fr', { ignorePunctuation: true }));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']

// .match()
sentence.match(/[A-Z]/g); // ["T"];

// .matchall() - must be in new array
[..."test1test2".matchAll(/t(e)(st(\d?))/g)]; // [["test1", "e", "st1", "1"], ["test2", "e", "st2", "2"]] 

// .normalize()
const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065';
name1.normalize('NFC'); // "Amélie, Amélie"

// .padEnd(targetLength, char)
"Breaded Mushrooms".padEnd(25, '.'); // "Breaded Mushrooms........"

// .padStart(targetLength, char)
const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*'); // "************5581"

// .raw()
// ignore escaped values. Keep template literals
String.raw`C:\Development\profile\aboutme.html` // "C:\Development\profile\aboutme.html"

// .repeat(count)
"hello".repeat(2); // "hello hello"

// .replace(regexp, newSubStr)
// .replace(regexp, replacerFunction)
// .replace(substr, newSubStr)
// .replace(substr, replacerFunction)
// if string, only first occurence is replaced
"have a good day".replace("good", "great"); // "have a great day"

// replaceAll(regexp, newSubstr)
// replaceAll(regexp, replacerFunction)
// replaceAll(substr, newSubstr)
// replaceAll(substr, replacerFunction)
"have a good good day".replaceAll(/good/ig, "great"); // "have a great great day"

// .search(regexp)
sentence.search(/[^\w\s]/g); // 43

// .slice(beginIndex)
// .slice(beginIndex, endIndex)
// does not include the endIndex
sentence.slice(31); // "the lazy dog."
sentence.slice(-4); // "dog."

// .split()

// .startsWith(searchString)
// .startsWith(searchString, position)
"Saturday night plans".startsWith("Sat"); // true 

// substring(indexStart)
// substring(indexStart, indexEnd)
// Stick with slice()
"Mozilla".substring(1, 3); // "oz"
"Mozilla".substring(2); // "zilla"

// toLocaleLowerCase()
"İstanbul".toLocaleLowerCase("en-US"); // i̇stanbul
"İstanbul".toLocaleLowerCase("tr"); // istanbul

// toLocaleUpperCase()
// toLowerCase()
// toString()
// toUpperCase()
// trim()
// trimEnd()
"   Hello world!   ".trimEnd(); // "   Hello world!"
// trimStart()
// valueOf()
const stringObj = new String("foo");
stringObj; // String { "foo" }
stringObj.valueOf() // "foo" 

Object

// .constructor()
let o = {}
o.constructor === Object // true

// .assign()
// does not deep clone
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
target; // Object { a: 1, b: 4, c: 5 }
returnedTarget; // Object { a: 1, b: 4, c: 5 }

// to deep clone
obj2 = Object.assign({}, obj1);
obj2 = {...obj1};

// .create()
const ability = {
  fly: true,
  walk: true,
};
const me = Object.create(ability);
me.fly; // true

// .defineProperties()
const object1 = {};
Object.defineProperties(object1, {
  property1: {
    value: 42,
    writable: true
  },
  property2: {}
});
object1.property1; // 42

// .defineProperty()
const object1 = {};
Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});
object1.property1 = 77; 
object1.property1; // 42

// .entries()
const object1 = {
  a: 'somestring',
  b: 42
};
for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
// "a: somestring"
// "b: 42"

// .freeze()
// .fromEntries()
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
const obj = Object.fromEntries(entries);
obj; // Object { foo: "bar", baz: 42 }


// .getOwnPropertyDescriptor()
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, 'bar');
// d is {
//   configurable: true,
//   enumerable: true,
//   value: 42,
//   writable: true
// }


// .getOwnPropertyDescriptors()
// .getOwnPropertyNames()
const object1 = {
  a: 1,
  b: 2,
  c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]


// .getOwnPropertySymbols()
const object1 = {};
const a = Symbol('a');
const b = Symbol.for('b');
object1[a] = 'localSymbol';
object1[b] = 'globalSymbol';
const objectSymbols = Object.getOwnPropertySymbols(object1);
console.log(objectSymbols.length);
// expected output: 2


// .getPrototypeOf()
const prototype1 = {};
const object1 = Object.create(prototype1);
console.log(Object.getPrototypeOf(object1) === prototype1);
// expected output: true


// .hasOwnProperty()
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true


// is()
// Case 1: Evaluation result is the same as using ===
Object.is(25, 25);                // true
Object.is('foo', 'foo');          // true
Object.is('foo', 'bar');          // false
Object.is(null, null);            // true
Object.is(undefined, undefined);  // true
Object.is(window, window);        // true
Object.is([], []);                // false
const foo = { a: 1 };
const bar = { a: 1 };
Object.is(foo, foo);              // true
Object.is(foo, bar);              // false

// Case 2: Signed zero
Object.is(0, -0);                 // false
Object.is(+0, -0);                // false
Object.is(-0, -0);                // true
Object.is(0n, -0n);               // true

// Case 3: NaN
Object.is(NaN, 0/0);              // true
Object.is(NaN, Number.NaN)        // true


// isExtensible()
const object1 = {};

console.log(Object.isExtensible(object1));
// expected output: true

Object.preventExtensions(object1);

console.log(Object.isExtensible(object1));
// expected output: false


// isFrozen()
// isPrototypeOf()
// isSealed()
const sealed = {};
Object.seal(sealed);
Object.isSealed(sealed); // === true


// keys()
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]


// preventExtensions()
// Cannot add new properties to the object
const object1 = {};
Object.preventExtensions(object1);
try {
  Object.defineProperty(object1, 'property1', {
    value: 42
  });
} catch (e) {
  console.log(e);
  // expected output: TypeError: Cannot define property property1, object is not extensible
}


// propertyIsEnumerable()
// seal()
// Prevents new properties to be writtent to the object


// setPrototypeOf()
// toLocaleString()
const date1 = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
console.log(date1.toLocaleString('ar-EG'));
// expected output: "٢٠‏/١٢‏/٢٠١٢ ٤:٠٠:٠٠ ص"

const number1 = 123456.789;
console.log(number1.toLocaleString('de-DE'));
// expected output: "123.456,789"


// toString()
// valueOf()
+"5" // 5 (string to number)
+"" // 0 (string to number)
+"1 + 2" // NaN (doesn't evaluate)
+new Date() // same as (new Date()).getTime()
+"foo" // NaN (string to number)
+{} // NaN
+[] // 0 (toString() returns an empty string list)
+[1] // 1
+[1,2] // NaN
+new Set([1]) // NaN
+BigInt(1) // Uncaught TypeError: Cannot convert a BigInt value to a number
+undefined // NaN
+null // 0
+true // 1
+false // 0


// values()
const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};
console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment