JS Flashcards

1
Q

En uppgift =

A

en funktion

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

Vad är nackdelen med att skapa funktioner inuti loopar?

A

Det använder mycket minne. Skapa funktioner utanför loopar.

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

Vad är JavaScript?

A

Ett mångsidigt programmeringsspråk som används för webbutveckling.

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

Vad är en variabel?

A

En behållare för att förvara data/värde

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

Hur deklarerar man en variabel i JavaScript?

A

Via nyckelorden var, let, eller const.

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

Vad är skillnaden mellan var, let, och const?

A

var har functionscope, let och const har blockscope.

constvariabler kan inte ändras efter att de deklarerats.

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

Vilka 8 datatyper har JavaScript?

A

number, bigint, string, boolean, null, undefined, object och symbol

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

Vad används typeof operatorn till?

A

Ta reda på datatypen av ett värde eller en variabel.

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

Kommentera i JavaScript?

A

// för enradiga kommentarer

/* */för flera rader

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

Vad är en funktion i JavaScript?

A

Ett block av återanvändbar kod skriven för att utföra en viss uppgift.

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

Hur deklareras en funktion?

A

Via nyckelordet function.

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

Vad är en function parameter?

A

En variabel som används för att skicka data in till en funktion.

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

Vad är ett return statement i en funktion?

A

Det specificerar värdet som ska returneras av funktionen

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

Vad är en villkorssats i JavaScript?

A

Villkorssatser, som if, else if, och else, gör att man kan villkora delar av kod.

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

Vad är en operator i JavaScript?

A

En symbol som används för att operera på variabler och värden.

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

Vad gör === operatorn?

A

Strikt equality. Både typ och värde.

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

Vad är en array?

A

En datastruktur som innehåller en samling värden.

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

Hur kommer man åt värden i en array?

A

Via index, startar på 0.

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

Vad är ett JavaScript object?

A

En samling key-value par.

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

Hur skapar man ett object i JavaScript?

A

{}
Eller constructor-funktioner

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

Vad är en JavaScript-loop?

A

Loopar, som for och while, kan exekvera kod upprepade gånger.

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

Hur kan man bryta en loop?

A

break

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

Vilket syfte fyller switch i JavaScript?

A

switch används för villkorade förgreningar baserat på ett värde.

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

Vad är en anonym funktion?

A

En funktion utan namn

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
vad är en callback function?
En funktion som skickas som argument till en annan funktion.
26
Vad betyder scope?
Var variabler och funktioner är åtkomliga i koden.
27
Vad är ett closure?
En funktion med åtkomst till sitt eget scope och den omgivande funktionens scope.
28
Vad är en event handler?
En funktion som svarar på händelser som click eller knapptryck.
29
Vad är asynkron programmering?
Asynkron programmering tillåter icke-blockerande exekvering av kod.
30
Vad är promises?
Objekt som representerar det eventuella resultatet av en asynkron operation.
31
Vad är nyckelordet this?
Det refererar till det nuvarande objektet. Ofta i metoder i ett objekt.
32
Vilket syfte fyller console.log() ?
Skriver output till konsolen för debugging.
33
Hur kan man definiera en iife?
( function () {…} )();
34
Hur aktiverar man ”modern mode” i JavaScript?
”use strict”
35
for…of
Loops over array or other iterable
36
for…in
Loops over object properties
37
Where can JS run?
Anywhere there's a JS-engine
38
The three steps of executing JS?
1. Engine parses script (where's the optimization and JIT-compiling?) 2. Converts to machine code 3. Machine code runs, pretty fast
39
JS statements =
syntax constructs and commands that perform actions
40
Difference between statements and expressions
Statements = control flow, variable assignment etc. Expressions produce values.
41
How to strict mode?
"use strict" at top of script OR use classes or modules
42
when to use const UPPER_CASE ?
Storing hard to remember values, known prior to execution.
43
3 things good variable names are ?
1. clean, 2. obvious and 3. descriptive of the data they store
44
What is immutable code?
It contains no datastructures that can be modified
45
How to write immutable code?
Instead of modifying data, create new data with desired changes
46
Four rules for good variable names?
1. Human readable 2. No abbreviations 3. Maximize descriptiveness + consicesness 4. Be consistent, "newUser" implies "user"
47
What 2 bugs are related to typeof?
1. typeof null returns Object 2. typeof [any function] returns function (which isn't one of the 8 types in JS)
48
What does unary + do?
Number conversion.
49
What does binary + do?
Sum numbers or concatenate strings (if one operand is string).
50
What's an operand?
A value an operator is applied to.
51
How to give precedence to operators?
(expression to give precedence)
52
What's the difference between n++ and ++n?
Postfix (n++) increments after returning n Prefix (++n) increments before returning n
53
What 2 values shouldn't be used in comparisons?
Null and undefined
54
When to use the ternary operator?
To return one value or another depending on one condition
55
When to use if statements?
To execute different branches of code
56
What does || do?
OR operator finds first truthy value and returns it
57
What does && do?
AND operator finds first falsy value and returns it
58
What does ! do?
NOT operator converts to boolean and returns the opposite !0 == true
59
Use case for !! ?
Double NOT, simple boolean conversion
60
What does ?? do?
Nullish coalescing, returns first defined value
61
Arity of reduce()?
1. Callback for each element 2. Starting point for final output
62
Arity of the callback in reduce()?
1. Starting point by reference (like ‘sum’) after first iteration it refers to the result from previous iteration 2. Current element
63
Method for preventing adding new properties on an object?
`Object.preventExtensions(obj)`
64
Method for preventing adding/removing properties on an object?
`Object.seal(obj)`
65
Method for preventing adding/removing/changing properties on an object?
`Object.freeze(obj)`
66
for-loop syntax?
``` for( let i = 0; i < numberOfIterations; i++) { // loop body } ```
67
Use case for infinite loops?
In combination with `break`. Great for checking conditions in many places in loop body,
68
What does `continue` do?
Stops the current iteration in a loop and jumps to the next.
69
Use case for labeling loops?
To be able to use `break` and `continue` in nested loops.
70
How to label loops?
``` labelName: for(…) { // … } ```
71
No more than___ lines of code without blank line.
9
72
Two ways of avoiding too much nesting in JS functions ?
1. Negative `if`s and using `continue` 2. Nested `else` can be avoided with `return`
73
4 things that warrants a comment?
1. Describe architecture 2. Documentation of function parameters and usage 3. Why is the task solved this way 4. Subtle or counter intuitive features
74
Object property value shorthand?
``` function makeUser (name, age) { return { name, age } } ```
75
How to test for existence of a property in an object?
With `in` operator: `property in object `
76
How to loop over object properties?
``` for (let prop in obj) { // loop body } ```
77
What does a variable assigned to an object store?
An address to the object (in memory). I.e a *reference* to the object
78
How to clone an object?
``` Object.assign(dest, …sourceObjects) ```
79
When are objects garbage collected in JS?
When it isn’t reachable anymore. I.e when there is no longer any existing reference to that object.
80
How to make method calls chainable?
Make every method return `this`
81
How does JS handle `this`?
`this` is *not bound* `this` is *evaluated* during runtime depending on context
82
What´s `this` in an arrow function?
Arrow functions inherit `this` from the outer function.
83
What's a constructor function?
A function that is used to create new objects.
84
Give two examples of built-in constructors?
1. new Date() 2. new Set()
85
What three things happen when a constructor function is called with the `new` keyword?
1. A new empty object is created and assigned to the `this` keyword. 2. The body of the constructor function is executed (with `this` referring to the empty object, writing properties into it). 3. `this` is returned
86
What is the main purpose of constructor functions?
Implement reuseable code for object creation.
87
What to use instead of constructor functions for more complex objects?
Class syntax.
88
What does `?.` do?
Optional chaining. If the value before `?.` is `null` or `undefined` evaluation stops and `undefined` is returned.
89
What is the use case for the `symbol` type in JS?
Symbols are used as unique keys in objects.
90
Symbols ... a uniqe identifier
**represent**
91
How to create a new symbol?
``` const mySymbol = new Symbol() ```
92
Can symbol properties be accessed by accident?
No
93
Fem steg för att skapa test i JS?
1. Välj test framwork. 2. Förbered testmiljö. 3. Konfigurera testramverket. 4. Skriv test. 5. Kör test.
94
Vad finns det för testramverk för JS?
Jest, mocha, chai, Vitest
95
Hur sätter man upp jest som testmiljö i ett JS-projekt?
`npm install --save-dev jest` skapa folder för test t.ex. '__test__' eller vad som är brukligt för testramverket.
96
Hur konfigurerar man testramverket i en npm/node app ?
config.json: ``` "scripts": { "test": "jest" } ```
97
5 best practice regler för att skriva bra JS-test?
1. Skriv små fokuserade test. 2. Använd deskriptiva testnamn. 3. Testa gränsfall (edge cases) 4. Isolera test (ett test ska inte bero på ett annat) 5. Använd mocking för externa tjänster och APIer för att isolera enheten eller modulen under test.
98
Hur kör man sina test i ett JS-projekt?
`npm test`
99
How to get all symbolic properties of an object "obj"?
`Object.getOwnPropertySymbols(obj)`
100
How to get all properties, including symbolic, of object "obj"?
`Reflect.ownKeys(obj)`
101
Give an example of when automatic object-to-primitive conversion takes place.
When an operator or function expects a primitive value (boolean, number, string, anything but objects).
102
What methods do JS call to do automatic conversion object-to-primitive?
1. obj[Symbol.toPrimitive](hint) If it exists. Else if hint === "string" 2. obj.toString() Else if hint === ("number"||"default") obj.valueOf() OR obj.toString()
103
What method if it exists is used for all hints in object-to-primitive conversion?
obj[Symbol.toPrimitive]
104
What method can be over-written and used as a "catch all" when it comes to object-to-primitive conversion?
obj.toString() Because if the other two doesn't exist it will handle all conversions.
105
What's the default return value of obj.toString?
[object Object]
106
How can there be methods on primitives in JS?
A special "object wrapper" is created when the method call is made and then destroyed.
107
What happens when a method is called on a primitive value in JS?
An "object wrapper" is created with different funcionality for each type. The wrapper knows the value of the primitive and once the method has executed, the object wrapper is destroyed.
108
What types of numbers can be represented by the `number` type in JS?
Any integer or double precision float above -(253 -1) and below (253 -1)
109
What type to use for numbers outside of the range for `number`?
BigInt Above (253 -1) and below (-253 -1)
110
How to round numbers to a specific number of decimals in JS?
Rounding `myNumber` to two decimals: `myNumber.toFixed(2)`
111
How to remove decimals from a number in JS?
`Math.trunc(myNumber)`
112
How to round up, down and to nearest integer in JS?
Down: `Math.floor(myNumber)` Up: `Math.ceil(myNumber)` Int: `Math.round(myNumber)`
113
Why are some calculations imprecise in JS?
Because machine code is binary, meaning base 2. We commonly use base 10. The problem is the same when dividing base 10 1/3 (infinite fraction).
114
What to do if mathematical precision is mandatory in JS?
Multiply numbers by 100 before calculating and divide back before returning.
115
What three "special values" are also considered numbers?
Infinity, -Infinity and NaN (Not a number)
116
How to find the max of a series of numbers?
`let myNumbers = [1, 2, 3]` `Math.max(...myNumbers)` `// returns 3`
117
How many types of quotes can be used to denote strings in JS?
3. ', ", `
118
How to get last char of string?
`myString.at(-1)` String.at() counts from end if given negative number as arg.
119
Are strings iterable?
Yes, with for... of: `for (let char of myString) { console.log(char + " ") }`
120
How to search for substring in a string in JS?
`myString.indexOf(substring, [start pos])` or `myString.includes(substring, [start pos])`
121
Whats the difference between string.includes() and string.indexOf()?
includes returns boolean indexOf returns position of match (-1 if no match)
122
How to return a substring from a string in JS?
`myString.slice(start, [end])` Both arguments can be negative values, counting from end of string.
123
What array methods work at end?
push() and pop()
124
What array methods work at start?
shift(), unshift()
125
Is it faster to work at start or end of array?
End is faster. Use it like a stack. LIFO.
126
What two array methods to use if array is used as queue?
shift() and push() Remove from beginning, add at end
127
Are arrays objects?
Yes, but don't treat them like it. But they are for example copied by reference like objects and not by value like primitives.
128
How to loop over arrays?
for... of: ``` for (let item of arr) { console.log(item) } ```
129
How to get last item of array?
myArray[myArray.length -1] or myArray.at(-1) (Last is newer syntax and may need polyfilling)
130
Why do we need throttling and debouncing?
To optimize and control frequency of execution of a function. Eg limiting the amount of API calls.
131
What's debouncing?
Delaying the execution of a function. Eg in relation to user input in a text field, we only want to show suggestions when user stops typing.
132
What's throttling?
Delaying the execution of a function by a set amount of time. It limits the rate of function calls to prevent overwhelming the system.
133
What does `arr.concat()` do?
Return a new concatenated array from all args added to arr.
134
What does arr.splice() do?
Insert , delete items from arr.
135
What does arr.splice return?
An array of the deleted elements.
136
Arguments of arr.splice()?
Start, deletecount, insert element…
137
What does arr.forEach() return?
Nothing
138
What are the parameters of the function called on each item in a arr.forEach()?
Item, index, arr
139
What’s the difference between assigning _a function_ and assigning _a function call_ to a variable?
Assigning a function call stores the returned value. Assigning a function makes the variable callable.
140
What four methods are used for searching in an array?
1. `arr.indexOf(item)` 2. `arr.lastIndexOf(item)` 3. `arr.includes(item)` 4. `arr.find(fn)`
141
Return value of `arr.IndexOf(item)`
Index of first match of `item` (-1 if not found)
142
Return value of `arr.lastIndexOf(item)`
Index of first match but searches from end of array
143
Return value of `arr.includes(item)`
`true` if found else `false`
144
What is the second optional parameter of `arr.indexOf`?
`from` representing an index to start the search from
145
Is there a difference in how `arr.indexOf` and `arr.includes` matches elements?
Yes, `arr.indexOf` uses '===', `arr.includes` uses "a more up to date comparison algorithm"
146
What are the parameters of `fn` in `arr.find(fn)`?
item, index, array (same as in `arr.forEach()`)
147
Return value of `arr.find(fn)`?
The item where `fn` returns true. Like `arr.filter()` but only returns the first match. If nothing is found it retuns `undefined`
148
What's the difference between `arr.find(fn)`and `arr.findIndex(fn)`?
`arr.findIndex(fn)` returns index of match instead of the matched item itself. If no match it returns -1
149
What's the difference between `arr.findIndex(fn)`and `arr.findLastIndex(fn)`?
They work the same but `arr.findLastIndex(fn)` searches from end of arr.
150
How to search an array and return a new array of all the matched elements?
Use `arr.filter(fn(item, [index, array]))`. If `fn` returns `true` for `item` it's included in the returned array.
151
What does `arr.map(fn)` do?
It calls `fn` for every item in the array and returns a new array.
152
What are the parameters of `fn` in `arr.map(fn)`?
item, index, array (same as arr.find, arr.filter arr.forEach and so on.)
153
What array method works like || (OR)?
arr.some( (item, index, arr) => ) (returns true if callback function returns true for any item in arr)
154
What array method works like && (AND)?
arr.every( (item, index, arr) => ) (only returns true if callback function returns true for every item in arr)
155
What's the `static` keyword used for?
Declaring static members on a class. Meaning properties or methods that are members of the class itself and not the specific instances of the class.
156
What type of functions are often declared as static members?
Utility functions that don't depend on specific instance data.
157
What type of data should be declared as static members?
Constants that are shared among all instances of the class.