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
Q

vad är en callback function?

A

En funktion som skickas som argument till en annan funktion.

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

Vad betyder scope?

A

Var variabler och funktioner är åtkomliga i koden.

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

Vad är ett closure?

A

En funktion med åtkomst till sitt eget scope och den omgivande funktionens scope.

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

Vad är en event handler?

A

En funktion som svarar på händelser som click eller knapptryck.

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

Vad är asynkron programmering?

A

Asynkron programmering tillåter icke-blockerande exekvering av kod.

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

Vad är promises?

A

Objekt som representerar det eventuella resultatet av en asynkron operation.

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

Vad är nyckelordet this?

A

Det refererar till det nuvarande objektet. Ofta i metoder i ett objekt.

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

Vilket syfte fyller console.log() ?

A

Skriver output till konsolen för debugging.

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

Hur kan man definiera en iife?

A

( function () {…} )();

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

Hur aktiverar man ”modern mode” i JavaScript?

A

”use strict”

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

for…of

A

Loops over array or other iterable

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

for…in

A

Loops over object properties

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

Where can JS run?

A

Anywhere there’s a JS-engine

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

The three steps of executing JS?

A
  1. Engine parses script (where’s the optimization and JIT-compiling?)
  2. Converts to machine code
  3. Machine code runs, pretty fast
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

JS statements =

A

syntax constructs and commands that perform actions

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

Difference between statements and expressions

A

Statements = control flow, variable assignment etc.
Expressions produce values.

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

How to strict mode?

A

“use strict” at top of script OR use classes or modules

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

when to use const UPPER_CASE ?

A

Storing hard to remember values, known prior to execution.

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

3 things good variable names are ?

A
  1. clean,
  2. obvious and
  3. descriptive of the data they store
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What is immutable code?

A

It contains no datastructures that can be modified

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

How to write immutable code?

A

Instead of modifying data, create new data with desired changes

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

Four rules for good variable names?

A
  1. Human readable
  2. No abbreviations
  3. Maximize descriptiveness + consicesness
  4. Be consistent, “newUser” implies “user”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What 2 bugs are related to typeof?

A
  1. typeof null returns Object
  2. typeof [any function] returns function (which isn’t one of the 8 types in JS)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What does unary + do?

A

Number conversion.

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

What does binary + do?

A

Sum numbers or concatenate strings (if one operand is string).

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

What’s an operand?

A

A value an operator is applied to.

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

How to give precedence to operators?

A

(expression to give precedence)

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

What’s the difference between n++ and ++n?

A

Postfix (n++) increments after returning n
Prefix (++n) increments before returning n

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

What 2 values shouldn’t be used in comparisons?

A

Null and undefined

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

When to use the ternary operator?

A

To return one value or another depending on one condition

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

When to use if statements?

A

To execute different branches of code

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

What does || do?

A

OR operator finds first truthy value and returns it

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

What does && do?

A

AND operator finds first falsy value and returns it

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

What does ! do?

A

NOT operator converts to boolean and returns the opposite !0 == true

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

Use case for !! ?

A

Double NOT, simple boolean conversion

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

What does ?? do?

A

Nullish coalescing, returns first defined value

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

Arity of reduce()?

A
  1. Callback for each element
  2. Starting point for final output
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Arity of the callback in reduce()?

A
  1. Starting point by reference (like ‘sum’) after first iteration it refers to the result from previous iteration
  2. Current element
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Method for preventing adding new properties on an object?

A

Object.preventExtensions(obj)

64
Q

Method for preventing adding/removing properties on an object?

A

Object.seal(obj)

65
Q

Method for preventing adding/removing/changing properties on an object?

A

Object.freeze(obj)

66
Q

for-loop syntax?

A
for(  let i = 0; i < numberOfIterations; i++) {
// loop body
}
67
Q

Use case for infinite loops?

A

In combination with break. Great for checking conditions in many places in loop body,

68
Q

What does continue do?

A

Stops the current iteration in a loop and jumps to the next.

69
Q

Use case for labeling loops?

A

To be able to use break and continue in nested loops.

70
Q

How to label loops?

A
labelName: for(…) {
  // …
}
71
Q

No more than___ lines of code without blank line.

A

9

72
Q

Two ways of avoiding too much nesting in JS functions ?

A
  1. Negative ifs and using continue
  2. Nested else can be avoided with return
73
Q

4 things that warrants a comment?

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

Object property value shorthand?

A
function makeUser (name, age) {
    return {
        name,
        age
    }
}
75
Q

How to test for existence of a property in an object?

A

With in operator:
property in object

76
Q

How to loop over object properties?

A
for (let prop in obj) {
  // loop body
}
77
Q

What does a variable assigned to an object store?

A

An address to the object (in memory). I.e a reference to the object

78
Q

How to clone an object?

A
Object.assign(dest, …sourceObjects)
79
Q

When are objects garbage collected in JS?

A

When it isn’t reachable anymore. I.e when there is no longer any existing reference to that object.

80
Q

How to make method calls chainable?

A

Make every method return this

81
Q

How does JS handle this?

A

this is not bound
this is evaluated during runtime depending on context

82
Q

What´s this in an arrow function?

A

Arrow functions inherit this from the outer function.

83
Q

What’s a constructor function?

A

A function that is used to create new objects.

84
Q

Give two examples of built-in constructors?

A
  1. new Date()
  2. new Set()
85
Q

What three things happen when a constructor function is called with the new keyword?

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

What is the main purpose of constructor functions?

A

Implement reuseable code for object creation.

87
Q

What to use instead of constructor functions for more complex objects?

A

Class syntax.

88
Q

What does ?. do?

A

Optional chaining. If the value before ?. is null or undefined evaluation stops and undefined is returned.

89
Q

What is the use case for the symbol type in JS?

A

Symbols are used as unique keys in objects.

90
Q

Symbols … a uniqe identifier

A

represent

91
Q

How to create a new symbol?

A
const mySymbol = new Symbol()
92
Q

Can symbol properties be accessed by accident?

A

No

93
Q

Fem steg för att skapa test i JS?

A
  1. Välj test framwork.
  2. Förbered testmiljö.
  3. Konfigurera testramverket.
  4. Skriv test.
  5. Kör test.
94
Q

Vad finns det för testramverk för JS?

A

Jest, mocha, chai, Vitest

95
Q

Hur sätter man upp jest som testmiljö i ett JS-projekt?

A

npm install --save-dev jest
skapa folder för test t.ex. ‘__test__’ eller vad som är brukligt för testramverket.

96
Q

Hur konfigurerar man testramverket i en npm/node app ?

A

config.json:

"scripts": {
  "test": "jest"
}
97
Q

5 best practice regler för att skriva bra JS-test?

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

Hur kör man sina test i ett JS-projekt?

A

npm test

99
Q

How to get all symbolic properties of an object “obj”?

A

Object.getOwnPropertySymbols(obj)

100
Q

How to get all properties, including symbolic, of object “obj”?

A

Reflect.ownKeys(obj)

101
Q

Give an example of when automatic object-to-primitive conversion takes place.

A

When an operator or function expects a primitive value (boolean, number, string, anything but objects).

102
Q

What methods do JS call to do automatic conversion object-to-primitive?

A
  1. objSymbol.toPrimitive
    If it exists. Else if hint === “string”
  2. obj.toString()
    Else if hint === (“number”||”default”)
    obj.valueOf() OR obj.toString()
103
Q

What method if it exists is used for all hints in object-to-primitive conversion?

A

obj[Symbol.toPrimitive]

104
Q

What method can be over-written and used as a “catch all” when it comes to object-to-primitive conversion?

A

obj.toString()

Because if the other two doesn’t exist it will handle all conversions.

105
Q

What’s the default return value of obj.toString?

A

[object Object]

106
Q

How can there be methods on primitives in JS?

A

A special “object wrapper” is created when the method call is made and then destroyed.

107
Q

What happens when a method is called on a primitive value in JS?

A

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
Q

What types of numbers can be represented by the number type in JS?

A

Any integer or double precision float above -(253 -1) and below (253 -1)

109
Q

What type to use for numbers outside of the range for number?

A

BigInt
Above (253 -1) and below (-253 -1)

110
Q

How to round numbers to a specific number of decimals in JS?

A

Rounding myNumber to two decimals:
myNumber.toFixed(2)

111
Q

How to remove decimals from a number in JS?

A

Math.trunc(myNumber)

112
Q

How to round up, down and to nearest integer in JS?

A

Down: Math.floor(myNumber)
Up: Math.ceil(myNumber)
Int: Math.round(myNumber)

113
Q

Why are some calculations imprecise in JS?

A

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
Q

What to do if mathematical precision is mandatory in JS?

A

Multiply numbers by 100 before calculating and divide back before returning.

115
Q

What three “special values” are also considered numbers?

A

Infinity, -Infinity and NaN (Not a number)

116
Q

How to find the max of a series of numbers?

A

let myNumbers = [1, 2, 3]
Math.max(...myNumbers)
// returns 3

117
Q

How many types of quotes can be used to denote strings in JS?

A
  1. ’, “, `
118
Q

How to get last char of string?

A

myString.at(-1)
String.at() counts from end if given negative number as arg.

119
Q

Are strings iterable?

A

Yes, with for… of:
for (let char of myString) { console.log(char + " ") }

120
Q

How to search for substring in a string in JS?

A

myString.indexOf(substring, [start pos])
or
myString.includes(substring, [start pos])

121
Q

Whats the difference between string.includes() and string.indexOf()?

A

includes returns boolean
indexOf returns position of match (-1 if no match)

122
Q

How to return a substring from a string in JS?

A

myString.slice(start, [end])
Both arguments can be negative values, counting from end of string.

123
Q

What array methods work at end?

A

push() and pop()

124
Q

What array methods work at start?

A

shift(), unshift()

125
Q

Is it faster to work at start or end of array?

A

End is faster. Use it like a stack. LIFO.

126
Q

What two array methods to use if array is used as queue?

A

shift() and push()
Remove from beginning, add at end

127
Q

Are arrays objects?

A

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
Q

How to loop over arrays?

A

for… of:

for (let item of arr) {
    console.log(item)
}
129
Q

How to get last item of array?

A

myArray[myArray.length -1]
or
myArray.at(-1)
(Last is newer syntax and may need polyfilling)

130
Q

Why do we need throttling and debouncing?

A

To optimize and control frequency of execution of a function. Eg limiting the amount of API calls.

131
Q

What’s debouncing?

A

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
Q

What’s throttling?

A

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
Q

What does arr.concat() do?

A

Return a new concatenated array from all args added to arr.

134
Q

What does arr.splice() do?

A

Insert , delete items from arr.

135
Q

What does arr.splice return?

A

An array of the deleted elements.

136
Q

Arguments of arr.splice()?

A

Start, deletecount, insert element…

137
Q

What does arr.forEach() return?

A

Nothing

138
Q

What are the parameters of the function called on each item in a arr.forEach()?

A

Item, index, arr

139
Q

What’s the difference between assigning a function and assigning a function call to a variable?

A

Assigning a function call stores the returned value. Assigning a function makes the variable callable.

140
Q

What four methods are used for searching in an array?

A
  1. arr.indexOf(item)
  2. arr.lastIndexOf(item)
  3. arr.includes(item)
  4. arr.find(fn)
141
Q

Return value of arr.IndexOf(item)

A

Index of first match of item (-1 if not found)

142
Q

Return value of arr.lastIndexOf(item)

A

Index of first match but searches from end of array

143
Q

Return value of arr.includes(item)

A

true if found else false

144
Q

What is the second optional parameter of arr.indexOf?

A

from representing an index to start the search from

145
Q

Is there a difference in how arr.indexOf and arr.includes matches elements?

A

Yes, arr.indexOf uses ‘===’,
arr.includes uses “a more up to date comparison algorithm”

146
Q

What are the parameters of fn in arr.find(fn)?

A

item, index, array (same as in arr.forEach())

147
Q

Return value of arr.find(fn)?

A

The item where fn returns true. Like arr.filter() but only returns the first match. If nothing is found it retuns undefined

148
Q

What’s the difference between arr.find(fn)and arr.findIndex(fn)?

A

arr.findIndex(fn) returns index of match instead of the matched item itself. If no match it returns -1

149
Q

What’s the difference between arr.findIndex(fn)and arr.findLastIndex(fn)?

A

They work the same but arr.findLastIndex(fn) searches from end of arr.

150
Q

How to search an array and return a new array of all the matched elements?

A

Use arr.filter(fn(item, [index, array])). If fn returns true for item it’s included in the returned array.

151
Q

What does arr.map(fn) do?

A

It calls fn for every item in the array and returns a new array.

152
Q

What are the parameters of fn in arr.map(fn)?

A

item, index, array (same as arr.find, arr.filter arr.forEach and so on.)

153
Q

What array method works like || (OR)?

A

arr.some( (item, index, arr) => )
(returns true if callback function returns true for any item in arr)

154
Q

What array method works like && (AND)?

A

arr.every( (item, index, arr) => )
(only returns true if callback function returns true for every item in arr)

155
Q

What’s the static keyword used for?

A

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
Q

What type of functions are often declared as static members?

A

Utility functions that don’t depend on specific instance data.

157
Q

What type of data should be declared as static members?

A

Constants that are shared among all instances of the class.