CoreJS Interview1 Cheat Sheet

CoreJS Interview#1 Basics - Data types - Number methods - String methods - String templates - ternary operator - switch case - examples, where it can be useful

2,974 views 852 downloads 9 Jul 2023 History

JS Basics

Falsy ⇒ '­', 0, null, undefined, NaN, fals
var - hoisting, let, const - blocks
Temporal Dead Zone начинается в начале области видимости переменной и заканч­ивается ее объявл­ением
Primitives: Undefined, Boolean, String, Symbol, BigInt, Null
Non Primot­ives:
Object, Array, Function, RegExp, Date, Map, Set,
Error, Promise, enum

Strings

text.l­ength
text.s­lic­e(s­tart, end) => new string [start, end)
text.s­ubs­tri­ng(­start, end) new string [start, end)
text.s­ubs­tr(­start, length) new string [start... length number of charac­ters.
text.r­epl­ace­(ol­dValue, newValue) text.r­epl­ace­All­(ol­dValue, newValue)
text.t­oUp­per­Case() text.t­oLo­wer­Case()
concat­(st­ring1, string2, ..., stringN)
text.t­rim() trimSt­art() trimEnd()
padSta­rt(­tar­get­Length, padString): adds padding to the beginning
padEnd­(ta­rge­tLe­ngth, padString):adds padding to the end
charAt­(index) charCo­deA­t(i­ndex)
split(­sep­arator, limit)

Timers

Методы setInt­erv­al(­func, delay, ...args) и setTim­eou­t(func, delay, ...args) позволяют выполнять func регулярно или только один раз после задержки delay, заданной в мс.
ля отмены выполнения необходимо вызвать clearI­nte­rva­l/c­lea­rTi­meout со значением, которое возвращают методы setInt­erv­al/­set­Tim­eout.
Планир­ование с нулевой задержкой setTim­eou­t(f­unc,0) или, что то же самое, setTim­eou­t(func) исполь­зуется для вызовов, которые должны быть исполнены как можно скорее, после завершения исполнения текущего кода.
Браузер ограни­чивает 4-мя мс минима­льную задержку между пятью и более вложенными вызовами setTim­eout, а также для setInt­erval, начиная с 5-го вызова.
let timerId = setTim­eou­t(...); clearT­ime­out­(ti­merId);

Objects

Creating Objects
Literal/ Contructor Function/ Class
{x: "­y"} (new) functi­on(){} new Object() same as {} class Banana {} Object.cr­eate(proto[, proper­tie­sOb­ject])
delete book.u­ser­sRe­ading
Обход объекта
for (let key in myObject) Object.en­tries() => [key, value]
Object.keys() ⇒ [key] Object.va­lues() =>­[va­lues]
Методы
someOb­j.h­asO­wnP­roperty('­key­1')
obj.__proto__ === person ⇒ Object.ge­tPr­oto­typ­eOf­(ob­ject1) Object.se­tPr­oto­typ­eOf­(ob­ject1)
The valueOf() method of [Object] instances converts the this value [to an object]

Object.cr­eate()

function MyClass() {
  SuperClass.call(this);
  OtherSuperClass.call(this);
}
MyClass.prototype = Object.create(SuperClass.prototype); 
позволяет создавать новый объект и устана­вливать прототип этого объекта в объект, переданный в качестве параметра

Events

Event Phases - это три фазы жизненного цикла события: захват (captu­ring), цель (target) и всплытие (bubbl­ing).
Разница между этими фазами заключ­ается в порядке вызова обрабо­тчиков событий. В фазе захвата обрабо­тчики вызываются сверху вниз, а в фазе всплытия - снизу вверх. В фазе цели вызывается только один обрабо­тчик, связанный с элементом цели.
Mouse Events: - click - dblclick - mousedown - mouseup - mousemove - mouseover - mouseout - contex­tmenu
Keyboard Events: - keydown - keyup - keypress
Form: formdata reset submit;
Input:­change, input, cut, copy, paste

Array NOT Mutating

`concat(array1, array2, ..., arrayN): new Array`
`array.filter(callback(el, ind, array), thisArg): new Array`
`array.map(callback(elt, ind, array), thisArg): new Array`
`array.slice(start, end): new Array`
`array.reduce(callback(acc, cur, i, array), initi): any`
`reduceRight(callback(acc, cur, i, array), init): any`

Array Mutations

push(e­lem­ent1, element2, ..., elementN)
pop()
shift()
unshif­t(e­lem­ent1, element2, ..., elementN)
splice­(start, delete­Count, item1, item2, ..., itemN)
sort(c­omp­are­Fun­ction)
reverse()
fill(v­alue, start, end)

Iterate Array

for (let i = 0; i < scores.length; i++) {}
for (i in scores) {}
for (score of scores) {}
scores.forEach((score) => {});
every(function (element, index, array) { /* … */ }, thisArg)
array.reduce( function(total, el, i, arr),initialValue )
every(function (element, index, array) { /* … */ }, thisArg)

Copy Array

const arrNew = [...arrOld];
const newArray = [...oldArray];
{ const json = JSON.stringify(oldArray);
const newArray = JSON.parse(json); }
const arrNew = arrOld.slice();
const arrNew = Array.from(arrOld);
const arrNew = [].concat(arrOld);

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.