Important Javascript facts Flashcards

1
Q

Explain Javascript primitives

A

Primitives are immutable, that is, they can only be changed by adding additional expressions for example:

var someValue=1;
someValue=2;

someValue will now be 2.

These are string, number, boolean, null and undefined. In essence, it excludes functions, objects and arrays.

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

Explain Javascript non-primitives

A

Objects , functions and arrays are non-primitives. Non-primitive values are mutable, that is, it can be modified after it is created without adding additional expressions.

For example:

Arrays can have keys pushed or popped. Indexes can have their values overwritten.

Object keys can be added and changed using dot or bracket notation.

This allows for an issue to occur, where if one reference to one of these heap items are updated, then the values are updated on all references to it.

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

What is an expression?

A

A line of code in which a value is assigned to a variable. These values can also be functions, and are then called function expressions.

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

Explain function expression vs function declaration

A

Declaration:function myFunction(){};
Expression: var myFunction=function(){}

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

Describe the problem with mutabality.

A

Non-primitives are stored in the heap when they are created. If this item is mutated in the heap, then any variable referencing this item in the heap will also be updated. Objects, functions and arrays can be mutated via dot notation, bracket notation (objects and functions) or pushing, popping, overwriting index values (arrays).

We make shallow/deep copies/clones to prevent the problem. Deep copies would be best, but maybe less performant when they are created.

`
Example of issue

const person = {
name:’Albert’,
attributes:{
hairColor:null,
age:36,
}
}

const person2 = person;

/*
Now we update the heap
*/

person.name=’Lucas’;
person.attributes.age=20;

/*
person and person2 point to the same object in the heap. When person one is mutated, then person2 is also mutated, by accident
*/

console.log(person2.name) // will also be Lucas
console.log(person2.attributes.age) // will also be 20

`

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

When is a variable undefined?

A

Variables that are declared but have not been assigned a value (var myCar) has a value of undefined. That is, not initialized even though it’s been declared - hoisting

When a property that is accessed does not exist on the object

When a function returns nothing, then a variable assigned to its invocation will be undefined

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

Explain Javascript hoisting and which variable types are hoisted.

A

Any variable declarations (when variables are created, also function expressions) are hoisted to the top of the function or script. Not const or let, just var.

This means that such a variable can be used before it is declared.

If used before declared, the value will be undefined because only declarations are hoisted. Value assignments/initializations are not.

Function declarations are hoisted as well

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

Which variable types should be copied and what is the difference between a shallow copy and a deep copy.

A

Arrays and objects only because it is tightly coupled with mutability and the way this data is updated in the heap and referenced by other variables.

With both shallow and deep copies other variables that reference the same item in the heap will no longer be changed when the cloned object/array is changed.

Shallow copies:

Only the case for top level items. Nested objects/arrays are still problematic.

Deep copies:

The case for all items, no matter how deeply the objects/arrays are nested.

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

How to make a shallow copy of an object.

A

Using the rest operator:
var {…duplicate}=oldObject;
Using the spread operator:
var newObject={…oldObject};
Using Object.assign:
var newObject=Object.assign({},oldObject);

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

How to make a shallow copy of an array

A

Using the rest operator:
var […duplicate]=oldArray;

Using the spread operator:
var newArray=[…oldArray];
Using .slice:
var newArray=oldArray.slice(0);

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

How to make a deep copy of objects and arrays

A

The stringify and parse approach won’t copy methods, which in most cases is a non-issue

var newObject=JSON.parse(JSON.stringify(oldObject));
var newArray=JSON.parse(JSON.stringify(oldArray));

OR

Lodash or similar

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

Example object literal

A

var objectLiteral={
key:”value”,
key2:”value”,
doSomething:function(){
}
}

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

null vs undefined vs not defined

A

If you as a developer want a value to be non-existent then use null.
If a variable is assigned a value of nothing, then Javascript itself will give it a value of undefined, for example if it declared but not assigned a value. You as a developer should not manually set it as undefined.

not defined is when a variable was not declared at all. If referencing this in your code then it will give an error.

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

What is a function/method signature

A

The arguments it expects, along with it’s types. May also include the return value and it’s type

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

What is HOF (Higher Order Function)

A

A function or method that takes a callback function as an argument or returns a function or both.

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

What are falsy and truthy values

A

Falsy:
null
undefined
false
0
NaN
empty string: “”, ‘’ or ``

Anything else is truthy

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

How to negate a value

A

Use an exclamation in front of the variable for example !someVariable

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

What is the purpose of double negation

A

Turns truthy values to boolean true and falsy values to boolean false.

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

Explain nullish coalescence

A

const someVar = null;

const newVar = someVar??’other-value’

If somevar is null OR undefined, use ‘other-value’ instead

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

Explain super keyword

A

This is used in a child class’s constructor, to send data up to it’s parent class’s constructor.

If a child class is instantiated, then in it’s constructor super() must be invoked as the first line. If no data is meant to be sent to the parent, just leave it empty. If you want to send data up, add it between the paranthesis.

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

Explain optional chaining

A

If the value, on which properties or methods are being accessed, is not an object but is null or undefined, then short-circuit the expression to have a value of undefined.

example

const person =null;

const thisValue = person?.role?.name;

thisValue will be undefined if role is null/undefined or person is null/undefined

Also functions if the function is nullish

myFunction?.() is the same as

If(myFunction) myFunction()

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

Explain ES6

A

The term ES6 refers to the newer Javascript versions. It started in 2015 and every year it is extended. Referring to ES2015 refers to the first new version, and ES2020 refers to the version released in 2020. Babel can transpile ES6 to ES5 (old Js) so that browsers can understand it. Some features are now natively supported without transpilation. Gulp, web pack, Parcel etc all use Babel for transpilation. babelrc file is required, which lists all the presets (grouped plugins), plugins and custom configuration. The output will be a single Javascript file that can be included in the HTML.

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

What is an expression in programming?

A

It is a single unit of code that evaluates to a value.

Example - all three are expressions:
const x = 5;
const y = 10;
const z = x + y;

24
Q

What is delayed initialization

A

When a variable is created (let var) but not assigned a value to start with.

let someVar;

someVar = ‘someValue’;

25
Q

Explain keyword this

A

1) In the global scope, or in a function that is in the global scope, the keyword this refers to the global object. Function expression, declaration and arrow function in global scope. Only when not strict mode.
2) Within an object literal, this refers to the closest parent object, so if it’s a nested object, then this refers to the closest object up the hierarchy. If an arrow function is used for methods, then this refers to whatever this is outside of the object, which is a problem.
3) In a regular callback function (not arrow function), this refers to the global object, unless bind() is used
4) In arrow function, this will refer to whatever it is just outside of the arrow function. Ideal for callback functions.
5) Within classes (new keyword), this inside of the class refers to either the class or parent class it inherits from. Remember only parent class protected or publoc methods and properties.
6) Within a constructor function, this refers to the constructor function. Functions and vars are added to this
7) call, apply and bind allows a developer to programmatically set what this should refer to inside the function body, by taking a thisArg which should be the object/this that this should refer to.
8) When using strict mode, then the keywordthis in a function in the global scope will the undefined.

call and apply are similar. The call and applymethods are used during the envokation of the function it’s used on. With call args are given to the function via separate args, with apply args are given to the function as an array.

const user = {
sayName(country){
return this.name+’ is from ‘+country;
}
}

const person ={
name:’Albert’
}

user.sayName.call(person,’South Africa’)
user.sayName.apply(person,[‘South Africa’])

bind: when .bind() is used when function is declared then this would refer to the thisArg when it’s invoked.

26
Q

Explain mutability

A

Mutability refers to mutation of a value, without reassignment.

Some variable types are immutable, for example strings (cannot be changed without reassignment) but others like objects and arrays can be changed (mutated) without reassignment, for example .push or .pop can be used on an array and object.property = 'new value' can be used to update an object.

The general rule is that primitives (anything but objects and arrays) are immutable (can only change with reassignments) and non-primitives (objects an arrays) are mutable, because they can be mutated without reassignment.

String example - primitives are immutable:

`
let myString = ‘some string’;
// the only way of changing this value is to assign a new value to it
myString =’some new string’

/* In order to make sure it cannot be reassigned a value, use the const keyword. */

`

Objects and arrays are mutable, and can be changed without reassignment:

`
const myArray = [];
myArray.push(‘some value’)

const person={
name:’Albert’
}

person.name=’new name’;
person.age = 122;
`

27
Q

Explain the heap, stack, event loop, callback queue

A

All of this is managed by the Javascript runtime

The heap stores by using memory:
- objects
- arrays
- functions
- strings
- all variables and data types

The heap includes a garbage collector that removes data that is no longer required.

The stack/callstack:
Keeps track of functions that need to be invoked, in the form of stack frames. The first stack frame is main. Each stack frame keeps track of the line number it’s being invoked on, so that the Javascript run-time can return to it after the next function is popped off the stack. The stack frames also keep track of the arguments and values passed to the function. It is processed in a LIFO (last in, first out) way. Stack frames are added to the top of the stack and popped off the stack when done.

Callback queue and event loop:
Any functions that are callbacks, not meant to be invoked immediately, are added to the callback queue, and the event loop keeps on checking if a callback is ready to invoked. If so, and the callstack is empty, the function is removed from the callback queue and is added to the callstack for invokation. This means that seeing as Javascript is single-threaded, it is not truly async. If the callstack is not empty, the event loop will only move the callback when the stack is empty, which might be after the callback was meant to be invoked.

28
Q

What does a function that returns nothing return

A

undefined, in typescript with type void

29
Q

Different types of casing

A

PascalCase
kebab-case
snake_case
camelCase
MAKRO_CASE

30
Q

What is a factory function

A

It is a function that returns an object of some kind. Think of a custom hook in React, or the revealing module pattern.

31
Q

Import module aliases setup

A

In tsconfig of jsconfig:

“baseUrl”: “.”,
“paths”: {
“@/components/”: [“components/”]
}

Allows import from @/components instead of relative paths, that is absolute paths from the baseUrl instead of relative paths.

32
Q

Explain what the DOM is

A

The DOM stands for Document Object Model.

All document. API properties and methods.

This is a data structure, in the form of an object, that Javascript can interact with. It is made up of Nodes, that Javascript can select, manipulate, or add event listeners to. The nodes are in a tree structure, with relationships such as:
- parent
- child
- descendant
- ancestor
- siblings

As soon as a node is manipulated, for example it is selected by ID or class and a style property is added to it, the HTML will be updated to reflect this change, and then it will change in color or whatever.

There is a direct correlation between the available html attributes and what can be assigned as a value, for example

document.getElementById(‘some-id’).style=’background:blue’

Classes are an exception to this, where classes are added in a different way - the classList API (.add())

33
Q

What is unique about const and let variables?

A

1) They are not hoisted at all, meaning, they cannot be used before they are initialized.

2) They are also block scoped, by block I mean if blocks, or ‘else’ blocks or loops.

This means that a const defined in the if is only accessible there as an example.

3) Lastly, global functions or variables that are declared with let or const are not attached to the window object in the browser.

34
Q

Event bubbling - propagation

A

A specific event, such as a click event, that is listening for this event on a descendant node, will fire such an event (click) that is assigned to an ancestor node, unless .stopPropagation() is invoked on the descendant’s event object returned in it’s listener.

35
Q

Explain memory leak

A

Memory refers to RAM.
Leak - memory is lost/destroyed.
If a program takes up a lot of memory, it might be leaking.

RAM is where running programs temporarily store data, such as variables.

A program requests memory, and the system assigns the memory. The program is meant to return it to the system after it’s no longer required. A leak occurs when the app can no longer identify what memory to return or when memory cannot be returned because there are unnecessary references to these stored variables.

A garbage collector, which is built into Javascript and runs without the developer worrying about doing garbage collection themselves, is responsible for returning the unnecessary memory to the system when possible.

36
Q

What is nullish in Javascript

A

Null/Undefined

37
Q

Time and space complexity - Big O

A

Big O notation is a notation used to describe time and space complexity.

Time (how long it takes to execute), and space (amount of memory required to store variables) complexity has to do with how long a function takes to execute based on the amount of items in an array that is given as input.

Loops within loops is quadratic complexity. O(N2)
A single loop is linear complexity O(N)
If the complexity remains the same no matter the size of the input array, then it’s constant complexity O(1)

38
Q

What is a big difference between function declarations and function expressions, regarding JS runtime.

A

Function expressions are hoisted, without value assignment/initialization (If var is used)

Function declarations are hoisted, along with it’s value assignment.

39
Q

What is the BOM

A

This stands for Browser Object Model. It is the window API that Javascript can interact with in order to give the browser instructions or to ask for information.

The APIs include:
- location
- navigator
- confirm, alert
- screen
etc

This would include global variables, that are attached to the window in a browser.

40
Q

Javascript causes of memory leaks

A

Global variables are not garbage collected and memory holding this temp data is not returned to the system.

Recursion.

Referring to a variable that is in an outer function, from within an inner function (closures). References to the outer function’s variables are kept, even when the outer function is no longer executing.

Referring to a variable that is outside of an event listener callback. The reference to this variable cannot be garbage collected.

Forgetting to clear timers

In React, accidentally recursively executing useEffect() callbacks.

41
Q

How do you access the global object, no matter the environment JS is running in (node, web browser)

A

globalThis object.

In a browser this is the window object
In node it’s the global object

42
Q

What are global variables and functions (declarations and expressions) attached to.

A

In a browser, to the window object
In node not

const and let variables/constants are not attached to the global object in a browser either.

In order to use global variables and methods (built into JS as well), then the window (in browser) does not have to be specified, ie.
window.alert and alert are both the same.

43
Q

Arrow functions purpose

A
  • Useful with implicit returns as most array helpers expect a return value in iterator functions.
  • Makes sure that the keyword this doesn’t lose it’s context, and refers to whatever it is right outside of the arrow function. So useful for callback functions, to not lose this context. Advanced object literal methods should be used, under no circumstances should arrow functions be used as methods to object literals, because this will then refer to whatever this is outside of the object, instead of the closest parent object.
44
Q

How global vars are created

A

define a variable without using the var, const or let keywords

Define it in the global scope, using var, let, const` keywords. let and const doesnt connect to global object though.

Define outside of any function, which includes object methods.

45
Q

What makes const and let unique?

A

1) Block-scoped - inside if for example
2) Not hoisted, so referencing it before it’s declared will cause errors
3) const and let are not added to the global object in a browser environment when defined as global variables.

46
Q

What is the problem with Javascript string functions?

A

It works on bytes. Each character in ASCII is 1 byte, which is fine for western characters and for unicode that contains only characters that can be mapped to ASCII, but not for other Unicode where each grapheme could be 1-4 bytes per code point and even worse, each grapheme could have multiple code points.

47
Q

Example of unicode unaware function and unicode aware function for measuring string length

A

string.length - unaware - measures bytes
[…string].length - aware, measures graphemes
v.countGraphemes(string) - aware, measures graphemes.

voca has countGraphemes method that can count the string length accurately, even when containing graphemes.

48
Q

What are the different types of scopes?

A

global scope
function scope
block scope

49
Q

Increment/decrement/exponentiation operator Javascript

A

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.

If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

Must be let

let x = 5;
let y = ++x (y is now 6)
let y = x++; (y is now 5)
Console.log(y) y is 6 now.

Decrement is –

Must be let. Prefix it immediately decrements on next line. If postfix, it only decrements on the line after the decrementing line.

Exponentiation:

May be const

Example:

Const b = 5
b**4

50
Q

When is bracket notation the only option for object literal properties?

A

When the property is more than one word or is kebab-case:
`
const something={
‘another-property’:10
};
something[‘just some property’]= 5;
something[‘just-some-property’]= 5;
`

51
Q

Explain strict mode

A

use strict is required at the top of the javascript files that is included in the HTML.

A few things - many more than this:

  • keyword this, in a global function’s body is undefined.
  • makes creating global variables (when forgetting var keyword for example) an error
52
Q

What is variable initialization?

A

When a variable is assigned a value.

53
Q

Two object bracket notation syntaxes

A

const someObject = {
[‘some property’]:’value’
}

const object = {};
object[‘some property’] = ‘value’

54
Q

What does it mean to say a function is a first-class citizen in Javascript?

A

It means that a function can be passed around and returned just like variables.

55
Q

What is a function interpreted as in Javascript

A

An object, that is why useCallback is required in React, in order to ensure that the object doesn’t change between re-renders