Important Javascript facts Flashcards
Explain Javascript primitives
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.
Explain Javascript non-primitives
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.
What is an expression?
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.
Explain function expression vs function declaration
Declaration:function myFunction(){};
Expression: var myFunction=function(){}
Describe the problem with mutabality.
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
`
When is a variable undefined?
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
Explain Javascript hoisting and which variable types are hoisted.
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
Which variable types should be copied and what is the difference between a shallow copy and a deep copy.
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 to make a shallow copy of an object.
Using the rest operator:
var {…duplicate}=oldObject;
Using the spread operator:
var newObject={…oldObject};
Using Object.assign:
var newObject=Object.assign({},oldObject);
How to make a shallow copy of an array
Using the rest operator:
var […duplicate]=oldArray;
Using the spread operator:
var newArray=[…oldArray];
Using .slice:
var newArray=oldArray.slice(0);
How to make a deep copy of objects and arrays
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
Example object literal
var objectLiteral={
key:”value”,
key2:”value”,
doSomething:function(){
}
}
null vs undefined vs not defined
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.
What is a function/method signature
The arguments it expects, along with it’s types. May also include the return value and it’s type
What is HOF (Higher Order Function)
A function or method that takes a callback function as an argument or returns a function or both.
What are falsy and truthy values
Falsy:
null
undefined
false
0
NaN
empty string: “”, ‘’ or ``
Anything else is truthy
How to negate a value
Use an exclamation in front of the variable for example !someVariable
What is the purpose of double negation
Turns truthy values to boolean true and falsy values to boolean false.
Explain nullish coalescence
const someVar = null;
const newVar = someVar??’other-value’
If somevar is null OR undefined, use ‘other-value’ instead
Explain super keyword
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.
Explain optional chaining
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()
Explain ES6
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.
What is an expression in programming?
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;
What is delayed initialization
When a variable is created (let var) but not assigned a value to start with.
let someVar;
someVar = ‘someValue’;
Explain keyword this
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 apply
methods 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.
Explain mutability
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;
`
Explain the heap, stack, event loop, callback queue
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.
What does a function that returns nothing return
undefined, in typescript with type void
Different types of casing
PascalCase
kebab-case
snake_case
camelCase
MAKRO_CASE
What is a factory function
It is a function that returns an object of some kind. Think of a custom hook in React, or the revealing module pattern.
Import module aliases setup
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.
Explain what the DOM is
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())
What is unique about const
and let
variables?
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.
Event bubbling - propagation
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.
Explain memory leak
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.
What is nullish in Javascript
Null/Undefined
Time and space complexity - Big O
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)
What is a big difference between function declarations and function expressions, regarding JS runtime.
Function expressions are hoisted, without value assignment/initialization (If var is used)
Function declarations are hoisted, along with it’s value assignment.
What is the BOM
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.
Javascript causes of memory leaks
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.
How do you access the global object, no matter the environment JS is running in (node, web browser)
globalThis
object.
In a browser this is the window
object
In node it’s the global
object
What are global variables and functions (declarations and expressions) attached to.
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.
Arrow functions purpose
- 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 losethis
context. Advanced object literal methods should be used, under no circumstances should arrow functions be used as methods to object literals, becausethis
will then refer to whateverthis
is outside of the object, instead of the closest parent object.
How global vars are created
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.
What makes const and let unique?
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.
What is the problem with Javascript string functions?
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.
Example of unicode unaware function and unicode aware function for measuring string length
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.
What are the different types of scopes?
global scope
function scope
block scope
Increment/decrement/exponentiation operator Javascript
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
When is bracket notation the only option for object literal properties?
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;
`
Explain strict mode
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
What is variable initialization?
When a variable is assigned a value.
Two object bracket notation syntaxes
const someObject = {
[‘some property’]:’value’
}
const object = {};
object[‘some property’] = ‘value’
What does it mean to say a function is a first-class citizen in Javascript?
It means that a function can be passed around and returned just like variables.
What is a function interpreted as in Javascript
An object, that is why useCallback
is required in React, in order to ensure that the object doesn’t change between re-renders