JavaScript Core Flashcards

1
Q

What are the benefits of using array methods (forEach, map, etc.) over loops?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does .map() work?

A
  1. .map is applied to an array
  2. It accepts one parameter: a transformation function
  3. It returns a new array containing the same number of elements as the original array but with the transformation applied
  4. The original array is not modified
  5. 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does .filter() work?

A
  1. The filter function is applied to an array
  2. It accepts one parameter: a condition function (also called a predicate or callback function)
  3. It returns a new array with only the elements for which the condition is true
  4. It always returns a new array, and the original array is not modified
  5. 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]
  1. The following example does not assign the result, so it is not used and is ignored.
    numbers. filter(num => num % 2 === 0);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How does .reduce() work?

A
  1. reduce accepts two parameters: a reducer function and an initial value
  2. It is named ‘reduce’ because it reduces a collection of elements to a single value by applying the reducer function to each element
  3. The initial value is used in the first iteration, as the accumulated value
  4. Iterating the array, at each step, the reducer function is called
  5. The reducer function receives the accumulated value and the current element of the collection and combines them in some way
  6. Any sort of collection can be reduced
  7. If you don’t supply an initial value, the first element of the collection will be used
  8. 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can implement filter by using reduce?

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can implement mapby using reduce?

A
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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is NPM?

A

Node Package Manager e мениджър на JS пакети, които са публикувани от различни програмисти в общността.
Пакетите може да са единични файлове, JS библиотеки, или по-сложни колекции от библиотеки, цели JS frameworks.
Те решават различни проблеми и могат да се ползват от различни програмисти.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the benefits of using it?

A

NPM пакетите се ползват, защото:

  1. се пести време - не е нужно да се написват отначало фунционалности, които вече са написани от друг програмист
  2. намаляваме вероятността от грешки, като преизползваме даден код
  3. осигуряваме си надеждност, като интегрираме пакет, който се използва от други разработчици, които гарантират, че кода е тестван за edge cases и ни позволява да се концентрираме върху нашата логика

Предимства на NPM:

  1. пакетите са open source и ние можем да разглеждаме кога и да се запознаем как работи
  2. повечето пакети са тествани и доказано са с работещ код
  3. повечето пакети се update - ват регулярно и всякакви грешки по кода се оправят и кода се подобрява
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Node.js?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the package.json file?

A

Когато сваляме пакет с npm, този пакет се сваля в папка node_modules в нашия проект.
NPM знае версиите на всички пакети, които използваме в проекта и ги запазва в специален файл - Package.json

package-lock.json - в него подробно се описват всички пакети, както и всички пакети на които зависят тези пакети, заедно с версиите на всички

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can create a package.json file?

A

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: описват се пакетите, които помагат (на програмистите при писане на самия пакет
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a NPM project?

A

NPM е такъв, в който имаме package.json файл, в който се описват пакетите ползвани с проекта.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to determine the version of an installed package?

A

Execute the following command in bash terminal:

  • node -v
  • npm -v
  • package name -v
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can install a npm package?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Do I need to have node_modules when I use npm project?

A

No, you need to havejust a package.json file. Той съдържа цялата информация за всички пакети, които се ползват в пакета. Затова не е необходимо да качваме/изпращаме тази папка с проекта.

Като си копираме/сваляме проекта е необходимо само да изпълним:

npm install

Така всички dependencies from pachage.json ще бъдат инсталирани в node_modules папката.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can install a npm packege globally?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How can setup and run a custom script in npm?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are ES Modules? Explain what ES Modules are and what problems they solve.

A

Когато NPM и Node.js са били създадени JavaScript не е имала собствена модулна система. Браузърите са работели по различен начин, а Node.js е работел с CommonJS модулна система.

ES6 предоставя като обща модулна система ES Modules. Браузърите започват да предоставят поддръжка за нея, също и Node.js от версия 14.

ЕS Modules става универсална модулна система за JavaScript ecosystem.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a npm module?

A

Модул - това е JS файл, който декларира и експортва една или повече стойности - функции или променливи, използвайки ‘export’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is important to know about the node modules?

A
  1. Те се инициализират веднъж и след това Node.js и браузъра ги кешират
  2. Ако експорта е референтен тип, то реално импортваме референцията към референтната стойност/обект
  3. Скоупа на декларираните в даден модул променливи и функции е самия модул. Модулите ни позволяват скриване на данни, т.е скриваме данни, които не сме експортнали
  4. Модулите могат да импортват други модули, които да използват в кода си
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How can I use the ES Modules system?

A

You need to type in the package.json file the following (no matter where in the file on the first level):

“types”: “modules”,

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How can I create an npm module?

A

Можем да експортваме стойности от файла ни една по една с думата “export”:

export const defaultMsg = ‘Default message’

export function log(msg) {
console.log(msg);
}

Това ще генерира обект с имената на всички експортнати променливи и функции.

export {
defaultMsg,
log,
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can I import an npm module?

A
  • За да импортна само определени функционалности/пропертита он модула, мога да ползвам 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is a default export?

A

Един модул може да има 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a “tree shaking”?

A

Tree shaking - това означава да използваме само тези функционалности от модула, които ни трябват.
Да импортнем и кешираме само кода, необходим за нас. Това е и основното предимство на ES Modules пред CommonJS.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are objects? Provide an example.
- Explain what objects are and how do they compare to primitive types.

A

In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a property.

The key of a property can be a string. And the value of a property can be any value, e.g., a string, a number, an array, and even a function.
A property’s value can be a function, in which case the property is known as a method.

const person = {
 name: ['Bob', 'Smith'],
 age: 32,
 bio: function() {
 console.log(`${this.name[0]} ${this.name[1]} is ${this.age} years old.`);
 },
 introduceSelf: function() {
 console.log(`Hi! I'm ${this.name[0]}.`);
 }
};

Summary

  • An object is a collection of key-value pairs.
  • Use the dot notation ( .) or array-like notation ([]) to access a property of an object.
  • The delete operator removes a property from an object.
  • The in operator check if a property exists in an object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What do we use objects for?

  • Demonstrate how we can use objects.
  • Explain how objects help build more complex applications.
A

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. The concept of objects in JavaScript can be understood with real life, tangible objects.

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

Objects in JavaScript are ubiquitous and versatile. An object can be used as a bag of parameters with several handler functions attached. An object can group associated values but also structure a program. For example, you can put several similar functions on one object and let them operate on the same data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are the differences between primitive and reference types? Give code examples.

  • Explain the difference between primitive and reference types.
  • Demonstrate the difference between primitive and reference types.
A
  • Javascript has two types of values: primitive values and reference values.
  • You can add, change, or delete properties to a reference value, whereas you cannot do it with a primitive value.
  • Copying a primitive value from one variable to another creates a separate value copy. It means that changing the value in one variable does not affect the other.
  • Copying a reference from one variable to another creates a reference so that two variables refer to the same object. This means that changing the object via one variable reflects in another variable.
Primitive values:
var a = 3.14; // Declare and initialize a variable
var b = a; // Copy the variable's value to a new variable
a = 4; // Modify the value of the original variable
alert(b) // Displays 3.14; the copy has not changed
Reference values:
var a = [1,2,3]; // Initialize a variable to refer to an array
var b = a; // Copy that reference into a new variable
a[0] = 99; // Modify the array using the original reference
alert(b); // Display the changed array [99,2,3] using the new reference
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is destructuring, object destructuring?

A

Object destructuring assigns the properties of an object to variables with the same names by default.

let person = {
 firstName: 'John', let { firstName: fname, lastName: lname } = person;
 lastName: 'Doe'
};

let { property1: variable1, property2: variable2 } = object;

The identifier before the colon (:) is the property of the object and the identifier after the colon is the variable.

If the variables have the same names as the properties of the object, you can make the code more concise as follows:
let { firstName, lastName } = person;

When you assign a property that does not exist to a variable using the object destructuring, the variable is set to undefined.

In this example we assign the currentAge property to the age variable with the default value of 18:

let { firstName, lastName, middleName = ‘’, currentAge: age = 18 } = person;

A function may return an object or null in some situations. The code will throw a TypeError. To avoid this, you can use the OR operator (||) to fallback the null object to an empty object:

let { firstName, lastName } = getPerson() || {};

Nested object destructuring: Assuming that you have an employee object which has a name object as the property:
let employee = {
 id: 1001,
 name: {
 firstName: 'John',
 lastName: 'Doe'
 }
};

The following statement destructures the properties of the nested name object into individual variables:

let {
name: {
firstName,
lastName
}
} = employee;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Array destructuring

A

ES6 provides a new feature called destructing assignment that allows you to destructure elements of an array into individual variables.
Assuming that you have a function that returns an array of numbers as follows:

function getScores() {
 return [70, 80, 90];
}

Destructing assignment: let [x, y, z] = getScores(); // x = 70, y = 80, z = 90

It’s possible to take all remaining elements of an array and put them in a new array by using the rest syntax (…):

let [x, y ,…args] = getScores(); // [70, 80, 90, 100]; -> x = 70, y = 80, args = [90, 100]

You can skip elements and sent a default values: let [, , thirdItem = 0] = getItems(); // thirdItem = 0

If the getItems() function doesn’t return an array and you expect an array the destructing assignment will result in an error (TypeError):

To avoid the error use this: let [a = 10, b = 20] = getItems() || [];

Nested array destructuring:

function getProfile() {
return [
‘John’,
‘Doe’,
[‘Red’, ‘Green’, ‘Blue’]
];
}

Nested array destructuring: let [firstName, lastName, [ color1, color2, color3] ] = getProfile();

Swapping variables: let a = 10, b = 20; -> [a, b] = [b, a]; // a = 20, b = 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Spread Operator

A
  • The spread operator is denoted by three dots (…).
  • The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list.
  • The rest paramter is also denoted by three dots (…). However, it packs the remaining arguments of a function into an array.
  • The spread operator can be used to clone an iterable object or merge iterable objects into one.
const odd = [1,3,5];
const combined = [2,4,6, ...odd]; // [2, 4, 6, 1, 3, 5] The spread operator (...) unpacks the elements of the odd array.

Here are the main differences bertween rest and spread operators:

  • The spread operator (…) unpacks the elements of an iterable object.
  • The rest parameter (…) packs the elements into an array.
  • The rest parameters must be the last arguments of a function. However, the spread operator can be anywhere:
const odd = [1,3,5];
const combined = [2,...odd, 4,6]; // [2, 1, 3, 5, 4, 6]

JavaScript spread operator and array manipulation

1) Constructing array literal - the spread operator allows you to insert another array into the initialized array when you construct an array using the literal form:

let initialChars = ['A', 'B'];
let chars = [...initialChars, 'C', 'D']; // ["A", "B", "C", "D"]

2) Concatenating arrays: you can use the spread operator to concatenate two or more arrays:

let numbers = [1, 2];
let moreNumbers = [3, 4];
let allNumbers = […numbers, …moreNumbers]; // [1, 2, 3, 4]

3) Copying an array: you can copy an array instance by using the spread operator

let scores = [80, 70, 90];
let copiedScores = […scores];
console.log(copiedScores); // [80, 70, 90]

JavaScript spread operator and strings:

let chars = ['A', ...'BC', 'D'];
console.log(chars); // ["A", "B", "C", "D"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Rest Parameters

A

(…). A rest parameter allows you to represent an indefinite number of arguments as an array.

function fn (a, b, ...args) {
 //...
}

All the arguments you pass to the function will map to the parameter list. In the syntax above, the first argument maps to a, the second one maps to b, and the third, the fourth, etc., will be stored in the rest parameter args as an array.

fn(1, 2, 3, “A”, “B”, “C”); // [3, ‘A’, ‘B’, ‘C’]

The rest parameters must appear at the end of the argument list. The following code will result in an error:

function fn(a, ...rest, b) {
 // error // SyntaxError: Rest parameter must be last formal parameter
}

Assuming that the caller of the sum() function may pass arguments with various kinds of data types such as number, string, and boolean, and you want to calculate the total of numbers only:

function sum(...args) {
 return args
 .filter(function (e) {
 return typeof e === 'number'; let result = sum(10, 'Hi', null, undefined, 20); // 30
 })
 .reduce(function (prev, curr) {
 return prev + curr;
 });
}

Filter the arguments based on a specific type such as numbers, strings, boolean, and null:

function filterBy(type, ...args) {
 return args.filter(function (e) {
 return typeof e === type;
 });
}

Rest parameters and arrow function:

const combine = (...args) =\> {
 return args.reduce( (prev, curr) =\> prev + ' ' + curr);
};

let message = combine(‘JavaScript’, ‘Rest’, ‘Parameters’); // JavaScript Rest Parameters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How can I access the object’s properties?

A

To access a property of an object, you use one of two notations:

  • the dot notation
  • array-like notation

dot notation:
objectName.propertyName

array-like notation:
objectName[‘propertyName’]

We use dot notation when we know the name of the property.

We use array-like notation when we DO NOT know the name of the property and we need to ‘construct’ it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How can I check if an object has a property?

A
  1. hasOwnProperty() method
const hero = {
 name: 'Batman'
};
hero.hasOwnProperty('name'); // =\> true
hero.hasOwnProperty('realName'); // =\> false
  1. “in” operator
const hero = {
 name: 'Batman'
};
'name' in hero; // =\> true
'realName' in hero; // =\> false
  1. Comparing with undefined
const hero = {
 name: 'Batman'
};
hero.name; // =\> 'Batman'
hero.realName; // =\> undefined

But be aware of false negatives. If the property exists but has an undefined value:

const hero = {
 name: undefined
};
hero.name !== undefined; // =\> false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is primitive value in JS?

A

Primitive values are: null, undefined, boolean, number, string, symbol, and BigInt
Static data is the data whose size is fixed at compile time. Static data includes: primitive and reference values.

JavaScript engine stores primitive values and variables on the stack.

let age = 25;
let newAge = age;
newAge = newAge + 1;
console.log(age, newAge); // newAge = 26
 // age =25
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is a reference type value in JS?

A

When you declare variables, the JavaScript engine allocates the memory for them on two memory locations: stack and heap.

Reference values that refer to objects.

Unlike the stack, JavaScript stores objects (and functions) on the heap. The JavaScript engine doesn’t allocate a fixed amount of memory for these objects. Instead, it’ll allocate more space as needed.

let person = {
 name: 'John',
 age: 25,
};

let member = person;

member.age = 26;

console. log(person);
console. log(member);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is the main difference between reference copy and shallow copy?

A
var obj1 = new object()
var obj2 = obj1

Reference copy refers to the fact that both objects refer to the same object without creating a new object. When one object changes, the other object will also change.

Shallow copy will create a new object, this object has an exact copy of the original object property values
- If the attribute is a basic type, the value of the basic type is copied
- If the attribute is a reference type, the memory address is copied (that is, the referenced
object is copied but not the referenced object), so if one of the objects changes this
address, it will affect the other object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is shallow copy of an object?

A

A shallow copy will create a new object, this object has an exact copy of the original object’s property values
- If the attribute is a basic type, the value of the basic type is copied
- If the attribute is a reference type, the memory address is copied (that is, the referenced
an object is copied but not the referenced object). So if one of the objects changes this
address, it will affect the other object

39
Q

What is a deep copy of an object?

A

A deep copy will create a new heap memory to store an identical object. The old and new objects will not interfere.

A deep copy occurs when an object and the object it refers to are copied together. Deep copy is slower and more expensive than the shallow copy.
The two objects before and after the copy do not affect each other.

40
Q

How can I make shallow copy of an object?

A
1. Object.assign( {}, object);
 const personCopy = Object.assign({}, person);
2. Spread operator 
const personCopySpread = { ...person };
3. Object with JSON parse and stringify 
const personCopyJSON = JSON.parse(JSON.stringify(person)); 

Deep copy, but does not copy functions!

const person = {
name: ‘Maria’,
age: 20,
courses: [‘Math’, ‘Literature’],
sayHello: function () {
console.log(‘Hello’);
},
};

41
Q

How can i make a deep copy of an object?

A

In plain JavaScript, you cannot deep copy an entire object without making your own function.
We could use an external library to be able to deep copy an entire object.

lodash - maybe one of the most famous:

import _ from ‘lodash’

const person2 = _.cloneDeep(person1);

42
Q

What is “this” in objects?

A

When you deal with objects you could refer to the object itself by using the keyword this

  • this is only available in function calls
  • The functions must not be arrow functions
const person = {
 firstName: 'Maria',
 lastName: 'Ivanova',
 fullName: function() { return `${this.firstName} ${this.lastName}`,
};
43
Q

What is a Complex Structure?

A

Describes an object where some nesting is present.
In JavaScript, property keys must be strings, but property values can be anything.

const obj = {
simpleProperty: I'm just a string,
nestedObj: {
title: I'm a nested object property
},
someArray: [‘I’, ‘am’, ‘an’, ‘array’],
someMethod: function () {
return I'm a function;
}
}

const log = console.log;

// array like any other
log(obj.someArray.join(‘ ‘));
// functions on objects are
// called ‘methods’
log(obj.someMethod());

44
Q

Why complex structure is useful?

A

Data is key in every software application
Every program is just some data with algorithms that use it,
The more complex the problem, the more complex the data structure is

Objects in JavaScript help us shape the application data
We must design the structure to be easy to use,
…but also, to capture all the required information,
This process is known as data modeling

45
Q

What are linked lists?

A

Basic data structure – like a “chain” of objects
Each object holds some value
… and references the next object in the chain
The last object references null

Node is the building block of a Linked List:

const node = {
value: 1,
next:
}

next can be:
Reference to the next node
Or, if last, null

46
Q

Creating a Linked List

A

One option:

const headNode = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: null
}
}
}

Another option:

const headNode = { value: 1 };
headNode.next = { value: 2 };
headNode.next.next = { value: 3 };
headNode.next.next.next = {
value: 4,
next: null
}

47
Q

Traversing a Linked List

A

The process of iterating through all the nodes:
The algorithm can be expressed like this:

const traverse = (headNode) =\> {
 let current = headNode;

while (current !== null) {
console.log(current.value);
current = current.next;
}
}

48
Q

What is functional programming?

A

Това е стил на писане на код, който ни дава допълнителни patterns/структура с помощта на тези подходи решаваме често срещани проблеми в света на програмирането и прави нашия код по-лесен за разбиране и променяне.
Основната идея на функционалното програмиране е , че третира софтуера като една последователност от действия, които се изпълняват, като се продуцира резултат.
Като следваме този подход се стремим да не променяме състоянието на нашия софтуер, стойностите на променливи, обекти. Така намаляваме шанса някой да промени състоянието на програмата.
Imperative Pattern – описваме стъпка по стъпка какво искаме нашия софтуер на действа. Проблема е, че ние трябва да инвестираме много време за четене на този код.

Declarative Pattern – ние пишем какво искаме да се случи в кода ни, без да се влизаме в детайли как точно да се случи това (методи на масиви, а не for цикли).

// triple the value of every element in a given array
const triple = (arr) =\> {
 let results = []
 for (let i = 0; i \< arr.length; i++){
 results.push(arr[i] \* 3)
 }
 return results
}
// sum all the elements in a given array
const sum = (arr) =\> {
 let result = 0
 for (let i = 0; i \< arr.length; i++){
 result += arr[i]
 }
 return result
}
// triple the value of every item in a given array
const triple = (arr) =\> arr.map((currentItem) =\> currentItem \* 3)
// sum all the elements in a given array
const sum = (arr) =\> arr.reduce((prev, current) =\> prev + current, 0)
Functions are first class citizens – това означава, че можем да запазваме функциите в променливи също както в обикновена променлива. Също можем да ги подаваме като аргументи на други функции и също да ги връщаме каро резултат от други функции.
Higher order functions – това са функции които или приемат други функции като аргумент, или връщат функция като резултат.
Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. Functional programming is declarative rather than imperative, and application state flows through pure functions. Contrast with object oriented programming, where application state is usually shared and colocated with methods in objects.
Functional programming is a programming paradigm, meaning that it is a way of thinking about software construction based on some fundamental, defining principles (listed above). Other examples of programming paradigms include object oriented programming and procedural programming.
49
Q

What is a pure function?

A

Pure functions – това е функция, която:
• Не променя своите параметри – ако получи обект или масив, то тя не го променя когато се изпълнява
• Стойността, която те връщат не трябва да зависи на нещо друго освен параметрите, които получава
• По време на изпълнението на тази функция, тя не трябва да променя нищо извън нея, т.е. не би следвало да има side effect. По време на изпълнение на дадена функция трябва да избягваме това да боравим с данни, които не сме получили като параметър – да четем от конзолата, база данни, web
• Една функция е pure, когато при едни и същи входни данни, връща еднакъв резултат

A pure function is a function that:

  • Given the same input, will always return the same output.
  • Produces no side effects.

So, console.log( double(5) ); is the same as console.log(10);
This is true because double() is a pure function, but if double() had side effects, such as saving the value to the disk or logging to the console, you couldn’t simply replace double(5) with 10 without changing the meaning.

50
Q

What are side effects?

A

Side Effects

A side effect is any application state change that is observable outside the called function other than its return value. Side effects include:

  • Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain)
  • Logging to the console
  • Writing to the screen
  • Writing to a file
  • Writing to the network
  • Triggering any external process
  • Calling any other functions with side-effects

Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test.

51
Q

What is a module and why would you use it?

A

It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope.

  • It is used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function.
  • We expose certain properties and function as public and can also restrict the scope of properties and functions within the object itself, making them private.
  • This means that those variables cannot be accessed outside the scope of the function.
  • We can achieve data hiding an abstraction using this pattern
Immediately invoked function expression (IIFE) a standard IIFE looks like this:
(function () {
 // Code goes here
})();
The advantage of the IIFE is that any vars declared inside it are inaccessible to the outside world. So how does that help us? The key is that an IIFE can have a return value just like any other function.
var batman = (function () {
 var identity = "Bruce Wayne";

return {
fightCrime: function () {
console.log(“Cleaning up Gotham.”);
},

goCivilian: function () {
console.log(“Attend social events as “ + identity);
}
};
})();

// Outputs: undefined
console.log(batman.identity);
// Outputs: "Attend social events as Bruce Wayne"
batman.goCivilian();

If you need to both enforce privacy for some of your data and provide a public interface, then the module pattern is probably a good fit.

52
Q

What is the revealing module pattern?

A

This is an updated pattern in which we could simply define all functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wish to reveal as public.
An example of how to use the Revealing Module pattern is as follows:

var myRevealingModule = function () {

 var privateVar = "Ben Cherry",
 publicVar = "Hey there!";
 function privateFunction() {
 console.log( "Name:" + privateVar );
 }
 function publicSetName( strName ) {
 privateVar = strName;
 }
 function publicGetName() {
 privateFunction();
 }
 // Reveal public pointers to 
 // private functions and properties

return {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName
};

}();

myRevealingModule.setName( “Paul Kinlan” );

Advantages
This pattern allows the syntax of our scripts to be more consistent. It also makes it easier to tell at the end of the module which of our functions and variables may be accessed publicly, which eases readability.

Disadvantages
A disadvantage of this pattern is that if a private function refers to a public function, that public function can’t be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation, and the pattern doesn’t apply to public members, only to functions.
Public object members that refer to private variables are also subject to the no-patch rule.
As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.

53
Q

What is the scope? Provide an example.

A

Нуждата от ясно дефинирани правила за това къде се запазват променливите и как се намират по-късно се нарича скоуп.

Scope: space or environment in which a certain variable is declared (variable environment in case of function). Scope defines the area, where functions, variables, and such are available.

function grandfather() {
 var name = 'Hammad'
 // likes is not accessible here
 function parent() {
 // name is accessible here
 // likes is not accessible here
 function child() {
 // Innermost level of the scope chain
 // name is also accessible here
 var likes = 'Coding';
 }
 }
}

console.log(likes); // ReferenceError: likes is not defined

54
Q

What is Global scope?

A

Global scope

  1. outside of any function or block
  2. variables declared in the global scope are accessible everywhere
const me = “My and myself”
const year = 2022
55
Q

What is Function scope?

A

Function scope

  1. Variables are accessible only inside functions, not outside.
  2. Also called local scope
function calcAge (birthYear ) {
 Const now = 2022;
 Const age = now- birthYear; return age;
 } 

Console.log(now) // Reference Error

56
Q

What is Block scope?

A

Block scope (ES6)

  1. Variables are accessible only inside the block (block scoped). However, this applies only to let and const variables
  2. Functions are also block-scoped, only in strict mode
  3. We use block scope because we need to declare variables as close as possible (as local as possible) to where they will be used
57
Q

What is Scope chain?

A

Variable lookup in scope chain:

  1. Every scope always has access to all the variables from all its outer scopes (parent’s scopes).
  2. Variables are not copied from one scope to another. Instead, scopes simply look up in the scope chain until they find the variable that they need, and then they use it
  3. A certain scope will never ever have access to variables of on inner scope
  4. The way that we can access variables depends on where the scope is placed ( where it is written in the code)
  5. Scope chain only works upwards not sideways
58
Q

What is lexical scope? What is lexing-time?

A

Lexical Scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope even if the parent function has returned. Lexical scope is sometimes also referred to as Static Scope.

  • Lexical scope това е мястото където нашата променлива е написана
  • lexical scope is scope that is defined at lexing time
59
Q

What is the difference between const, let and var?

A

Demonstrate the difference between var and let

  • Var is function scoped
  • Let and const are block-scoped
if (true) {
 var a = 42;
}
console.log(a); // a = 42
if (true) {
 let b = 34;
}

console.log(b); // ReferenceError: b is not defined

const foo = () =\> {
 var c = 12;
};

console.log(c); // ReferenceError: c is not defined

const foo = () =\> {
 const c = 12;
};

console.log(c); // ReferenceError: c is not defined

60
Q

What is the difference between == and ===?

A

• The strict equality operator (===) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
• The most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to convert them to the same type before comparing.
• If the operands are of different types, return false.
• If both operands are objects, return true only if they refer to the same object
• If both operands are null or both operands are undefined, return true.
• If either operand is NaN, return false.
• Otherwise, compare the two operand’s values:
o Numbers must have the same numeric values. +0 and -0 are considered to be the same value.
o Strings must have the same characters in the same order.
o Booleans must be both true or both false.

61
Q

What is type coercion?

A

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.

62
Q

What is variable and function hoisting?

A

Hoisting is the process of collecting variables by the JavaScript compiler.

JS engine прочита, че имаме някаква променлива, преди тя да бъде декларирана и използвана, но само отчита този факт. Ако променливата е декларирана като let или const и ние се опитаме да я достъпим преди декларация– връща грешка, ако е var – undefined.

Var дава възможността стойността да бъде достъпена като undefined стойност.
Function declaration-а може да бъде изпълнен, защото е деклариран на едно място и директно се качва най-отгоре в нашия скоуп. Важно е да се знае, че се качват само техните декларации, а по-късно се достъпват и стойностите им или се извикват функциите.

Hoisted
Var hoisted = ‘Telerik Academy’
Not hoisted

63
Q

What is hoisted and what is not?

A
  • Everything in JavaScript is hoisted (even let and const )
  • let and const are in the temporal dead zone before declared, so they will throw an error if accessed before declared
  • Let and const are accessible only after declaration.
  • Var and function declarations function a() are accessible even before they are declared
64
Q

What is a closure?

• Explain what is closure and how it’s connected to scopes.

A

Formal: A closure is the closed-over variable environment of the execution context in which a function was created, even after that execution context is gone.

Less formal: A closure gives function access to all the variables of its parent function, even after that parent function has returned. The function keeps a reference to its outer scope, which preserves the scope chain throughout time.

Less former: A closure makes sure that a function doesn’t lose connection to variables that existed at the function’s birthplace.

Less formal: A closure is like a backpack that a function carries around wherever it goes. This backpack has all the variables that were present in the environment where the function was created.

65
Q

What is Scoping?

A

Scoping: how our program’s variables are organized and accessed, “where do variables live?” or “where can we access a certain variable, and where not”.

66
Q

What will be printed in the console?

console.log(addDecl(2, 3));

function addDecl(a, b) {
 return a + b;
}
A

Output: 5

This is because we are able to call function declaration before it was defined in the code.

67
Q

What will be printed in the console?

console.log(addArrow(2, 3));

const addArrow = (a, b) => a + b;

A

ReferenceError: Cannot access ‘addArrow’ before initialization

68
Q

What will be printed in the console?

console.log(addExpr(2, 3));

const addExpr = function (a, b) {
 return a + b;
};
A

Cannot access ‘addExpr’ before initialization

69
Q

What will be printed in the console?

console.log(addExpr(2, 3));

var addExpr = function (a, b) {
 return a + b;
};
A

TypeError: addExpr is not a function

Because addExpr is declared as var it is hoisted, and its value is undefined.

So, we are trying to do this: undefined(2, 3).

70
Q

What will be printed in the console?

console.log(addArrow(2, 3));

var addArrow = (a, b) => a + b;

A

TypeError: addArrow is not a function

Because addArrow is declared as var it is hoisted, and its value is undefined.

So, we are trying to do this: undefined(2, 3).

71
Q

What will be printed on the console?

let d = 4;
function two() {
let d;
d = 5;

console.log(d);
}
two();
console.log(d);

A

5

4

72
Q

What will be printed on the console?

let a = 1;

function one() {
 a = 2;
 var a = 3;
 console.log(a);
}

one();
console.log(a);

A

3

1

73
Q

What will be printed on the console?
let f = 5;
function three() {
let f = g = 6;
console.log(f);
three();
console.log(g, f);

A
74
Q

Demonstrate how to provide access to a variable’s value outside the function it is defined in.

A
75
Q

Provide an example of closure:

A
boardingPassengers = function (n, wait) {
 const perGroup = n / 3;
 setTimeout(() { console.log(`We are now boarding all ${n} passengers.`); 
console.log(`There are 3 groups, each with ${perGroup} passengers.`);
 }, wait \* 1000);
console.log(`Will start boarding in ${wait} seconds.`);
};
const perGroup = 1000;
boardingPassengers(180, 3);
perGroup Is registered
setTimeout is registered
console.log(`Will start boarding in ${wait} seconds.`); is executed
after 3 seconds function is executed: 
function () {
 console.log(`We are now boarding all ${n} passengers.`);
 console.log(`There are 3 groups, each with ${perGroup} passengers.`);
 },
This function has access to the n, wait, and perGroup from its parent boardingPassengers function,
The closure has priority over the scopes that is why the function looks first in its closure for perGroup and not in the scope chain (in this case global scope)
76
Q

In a given piece of code, determine if closure exists and identify it

(function () {

const header = document.querySelector(‘h1’);

header.style.color = ‘red’;

 document.querySelector('body').addEventListener('click', 
 function () {
 header.style.color = 'blue'; });
})();
A

There is a closure over the IIFE function - the function in the event listener has access to the header variable even when IIFE is gone.

The header is in the backpack of the event listener function.

77
Q

What is printed?

if (true) {
 let name = 'Pesho';
 };
 console.log(name);
A

ReferenceError: name is not defined

78
Q

What kind of function is this?:

 function sum (...args) {
 return args.reduce((sum, num) =\> sum + num, 0);
}
A

Function declaration.

79
Q

What kind of function is this?:

const sum = function (...args) {
 return args.reduce((sum, num) =\> sum + num, 0);
};
A

Function expression

80
Q

What kind of function is this?:

const sum = (...args) =\> {
 return args.reduce((sum, num) =\> sum + num, 0);
};
A

Arrow function

81
Q

What will be printed?

if (false) {
 let name = 'Pesho';
 };
 console.log(name);
A

ReferenceError: name is not defined

82
Q

What will be printed?

if (false) {
 var name = 'Pesho';
 };
 console.log(name);
A

undefined

83
Q

What will be printed?

one();
function one() {
console.log(1);
}

A

1

84
Q

What will be printed?

one();
const one = function () {
console.log(1);
}

A

ReferenceError: one is not defined

85
Q

What will be printed?

for (var i = 0; i < 3; i++) {
console.log(i);
};
console.log(i);

A

0
1
2
3

86
Q

What will be printed?

let a = '5';
let b = 5;

console. log(a + b);
console. log(a - b);
console. log(a * b);
console. log(a / b);

A

55 -> string
0 -> number
25 -> number
1 -> number

87
Q

What will be printed?

let a;
(() => { a = 5; })();
console.log(a);

A

5

88
Q

What will be the value of constants?

const nums = [1, 2, 3, 4, 5];

const filtered = nums.filter((x) => true);

const mapped = filtered.map((x) => false);

const found = mapped.some((x) => true);

A

[1, 2, 3, 4, 5]
[false, false, false, false, false]
true

89
Q

What will be printed?

let a;
((a = 5) => { })(a);

console.log(a);

A

undefined

90
Q

What will be printed?

if (Math.random() \< 0.5) {
 var x = 5;
}
console.log(x);
A

undefined OR 5

91
Q

What will be printed?

const value = 5;

const increment = (x) =\> x++;
increment(value);

console.log(value);

A

5

92
Q

What will be printed?

const person = { name: “Pesho”, age: 30 };

const updateAge = (objcopy, age) =\> {
 objcopy.age = age;

return objcopy;
};

const newPerson = updateAge(person, 20);
console.log(person.age, newPerson.age);
A

20 20

93
Q

What will be printed?

const person = {
 name: "Gosho",
 age: 20,
};
const log = (person = { name: "Pesho" }) =\> {
console.log(person.name);
};

log();
console.log(person.name);

A

Pesho
Gosho

94
Q

What will be printed?

console. log(0 == false);
console. log(null == undefined);
console. log(“” == false);

A

true

true

true