JavaScript Core Flashcards
What are the benefits of using array methods (forEach, map, etc.) over loops?
- they’re more meaningful and expressive
- the code is more declarative – it means that I define what I want to reach instead of describing the way how to do it
- using loops we need to care about the number of elements, starting point, and the iteration process
- A programming language is low level when its programs require attention to the irrelevant.” — Alan Perlis
How does .map() work?
- .map is applied to an array
- It accepts one parameter: a transformation function
- It returns a new array containing the same number of elements as the original array but with the transformation applied
- The original array is not modified
- We always receive a new array, so we need to assign the result to a variable
const strings = ['42', '23', '15', '2']; const numbers = strings.map(s =\> Number(s)); // [42, 23, 15, 2] (notice the lack of quote ')
How does .filter() work?
- The filter function is applied to an array
- It accepts one parameter: a condition function (also called a predicate or callback function)
- It returns a new array with only the elements for which the condition is true
- It always returns a new array, and the original array is not modified
- Filter can be used on arrays with elements of any type
const numbers = [4, 2, 1, 3, 5, 8]; const evens = numbers.filter(num =\> num % 2 === 0); // [4, 2, 8]
- The following example does not assign the result, so it is not used and is ignored.
numbers. filter(num => num % 2 === 0);
How does .reduce() work?
- reduce accepts two parameters: a reducer function and an initial value
- It is named ‘reduce’ because it reduces a collection of elements to a single value by applying the reducer function to each element
- The initial value is used in the first iteration, as the accumulated value
- Iterating the array, at each step, the reducer function is called
- The reducer function receives the accumulated value and the current element of the collection and combines them in some way
- Any sort of collection can be reduced
- If you don’t supply an initial value, the first element of the collection will be used
- Reduce can return any type of data - array, boolean, string, etc.
const numbers = [2,5,7]; const sum = numbers.reduce((sum, number) =\> sum + number, 0);
const animals = ['cat', 'dog']; const joined = animals.reduce((res, animal) =\> res + ', ' + animal)); // no initial value
const joined = animals.reduce((res, animal) => res + ‘, ‘ + animal, ‘’); // with initial value
How can implement filter by using reduce?
const filter = (array = [], filterFn) =\> { const result = array.reduce((acc, el, index, arr) =\> { if (filterFn(el, index, arr)) { acc.push(el); } return acc; }, []);
return result;
};
const filtered = filter([2, 6, 5, 8, 10], (el) =\> el \> 5); console.log(filtered); // [6, 8, 10]
How can implement mapby using reduce?
const map = (array = [], mapFn) =\> { const result = array.reduce((acc, el, index, arr) =\> { acc.push(mapFn(el, index, arr)); return acc; }, []);
return result;
};
console.log(map([1, 2, 3], (el) => el * 2)); // [2, 4, 6]
What is NPM?
Node Package Manager e мениджър на JS пакети, които са публикувани от различни програмисти в общността.
Пакетите може да са единични файлове, JS библиотеки, или по-сложни колекции от библиотеки, цели JS frameworks.
Те решават различни проблеми и могат да се ползват от различни програмисти.
What are the benefits of using it?
NPM пакетите се ползват, защото:
- се пести време - не е нужно да се написват отначало фунционалности, които вече са написани от друг програмист
- намаляваме вероятността от грешки, като преизползваме даден код
- осигуряваме си надеждност, като интегрираме пакет, който се използва от други разработчици, които гарантират, че кода е тестван за edge cases и ни позволява да се концентрираме върху нашата логика
Предимства на NPM:
- пакетите са open source и ние можем да разглеждаме кога и да се запознаем как работи
- повечето пакети са тествани и доказано са с работещ код
- повечето пакети се update - ват регулярно и всякакви грешки по кода се оправят и кода се подобрява
What is Node.js?
Node.js е сървърно приложение, създаващо среда за изпълнение на JS код, т.е. run time environment.
Node.js прави възможно изпълнението на JS код, директно на сървъра, когато обикновено JS се изпълнява в browser-а.
За да ползваме NPM трябва да имаме инсталиран Node.js.
Или:
Node.js is an open source server environment
Node.js is free
Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
Node.js uses JavaScript on the server
What is the package.json file?
Когато сваляме пакет с npm, този пакет се сваля в папка node_modules в нашия проект.
NPM знае версиите на всички пакети, които използваме в проекта и ги запазва в специален файл - Package.json
package-lock.json - в него подробно се описват всички пакети, както и всички пакети на които зависят тези пакети, заедно с версиите на всички
How can create a package.json file?
To create a package.json file run the following comman in the bash terminal whithin the project’s folder:
npm init -y
This will create a package.json file with a template structure and default values:
- description: кратко описание на проекта, модула
- main: стартовия файл на проекта
- scripts: обект от скриптове/предефинирани команди (например за стартиране на файлове), които се ползват в проекта
- keywords: ключови думи, които описват пакета. Те са полезни когато търсим пакета в интернет или регистрите на npm
- dependancies: описват се всички пакети, необходими за проекта да работи
- dev-dependancies: описват се пакетите, които помагат (на програмистите при писане на самия пакет
What is a NPM project?
NPM е такъв, в който имаме package.json файл, в който се описват пакетите ползвани с проекта.
How to determine the version of an installed package?
Execute the following command in bash terminal:
- node -v
- npm -v
- package name -v
How can install a npm package?
Execute the following command in the bash terminal within the npm project’s folder:
- npm install [name_of_package] -D
- D means saving the dependency in the dev0dependancies array in the package.json file.
This will install the package in the current npm project.
Do I need to have node_modules when I use npm project?
No, you need to havejust a package.json file. Той съдържа цялата информация за всички пакети, които се ползват в пакета. Затова не е необходимо да качваме/изпращаме тази папка с проекта.
Като си копираме/сваляме проекта е необходимо само да изпълним:
npm install
Така всички dependencies from pachage.json ще бъдат инсталирани в node_modules папката.
How can install a npm packege globally?
Open the cmd/bash terminal anywhere in the system.
Execute the following command:
- npm install [package_name] -g
- g comes from global
Example:
npm install lodash -g
How can setup and run a custom script in npm?
In package.json > scripts type the custom command:
“scripts” {
“start”: “node main.js”
},
Има предефинирани скриптове/команди за start and end. Ако използваме тези предефинирани команди/думи - не е необходимо да използваме думата run при пускане на скрипта.
Ако обаче ползваме различни думи, трябва да ползваме run:
“scripts” {
“log”: “node log.js”
},
npm run log
What are ES Modules? Explain what ES Modules are and what problems they solve.
Когато NPM и Node.js са били създадени JavaScript не е имала собствена модулна система. Браузърите са работели по различен начин, а Node.js е работел с CommonJS модулна система.
ES6 предоставя като обща модулна система ES Modules. Браузърите започват да предоставят поддръжка за нея, също и Node.js от версия 14.
ЕS Modules става универсална модулна система за JavaScript ecosystem.
What is a npm module?
Модул - това е JS файл, който декларира и експортва една или повече стойности - функции или променливи, използвайки ‘export’.
What is important to know about the node modules?
- Те се инициализират веднъж и след това Node.js и браузъра ги кешират
- Ако експорта е референтен тип, то реално импортваме референцията към референтната стойност/обект
- Скоупа на декларираните в даден модул променливи и функции е самия модул. Модулите ни позволяват скриване на данни, т.е скриваме данни, които не сме експортнали
- Модулите могат да импортват други модули, които да използват в кода си
How can I use the ES Modules system?
You need to type in the package.json file the following (no matter where in the file on the first level):
“types”: “modules”,
How can I create an npm module?
Можем да експортваме стойности от файла ни една по една с думата “export”:
export const defaultMsg = ‘Default message’
export function log(msg) {
console.log(msg);
}
Това ще генерира обект с имената на всички експортнати променливи и функции.
export {
defaultMsg,
log,
}
How can I import an npm module?
- За да импортна само определени функционалности/пропертита он модула, мога да ползвам module/object destructuring:
import { defaultMsg, log } from ‘logger.js’
- Ако искам да импортна цялата функционалност от модула и да го именувам:
import * as logger from ‘./logger.js’
Сега всяка функционалност от Logger.js може да бъде достъпена през logger.
- Импортването на модул само по име - ще импортне само default export:
import log from ‘path_to_module.js’
През log можем да достъпим всичко от default export.
What is a default export?
Един модул може да има 0 или 1 default export и/ или много именувани exports.
export default function (msg) {
console.log(msg);
}
export function named () {
console.log(‘named’)
}
А може направим default export на обект от фунционалности:
export default {
defaultMsg,
log,
named
}
Импортването на модул само по име - ще импортне само default export:
import log from ‘path_to_module.js’
През log можем да достъпим всичко от default export.