JavaScript Flashcards
What is Javascript?
A high-level interpreted programming language that allows developers to add behavior to web pages
Let vs Const
let allows reassignment
const does not allow reassignment after declaration
var is no longer used
What is the difference between == & === ?
Quality operators.
== checks for equality regardless of type
=== checks for value and type equality
Explain prototypal inheritance
When we read a property from an object, and it’s missing, JS takes it from the hidden property - prototype
Example:
let animal = {eats: true};
let rabbit = {jumps: true};
rabbit.__proto__ = animal
alert( rabbit.eats ); //true
alert( rabbit.jumps ); //true
Explain closure
The combination of a function bundled together (enclosed) with references to its surrounding state (lexical environment)
Closure gives you access to an outer function’s scope from an inner function
Explain event delegation
A single event listener is attached to a common ancestor, and events are handled based on the target element
Explain the Event Loop
A mechanism that handles async operations by queuing them up, and executing them in the order they are queued
This keeps the main thread free to handle user interactions
Explain the bind method
A method used so that an object can borrow a method from another object
For example, if an object has a function that another object needs to use, you can bind it instead of duplicating functionality
Explain asynchronous programming
Allows the program to perform other tasks while waiting for async operations to complete.
Uses mechanisms like callbacks (older), promises, and async/await
Callback vs Promise
Callback: functions passed as args to other functions, and are executed after a task is completed.
* Can pass data from parent to child
* Runs after parent completes
Promise: objects representing the eventual completion or failure of an async operation.
* fulfilled - success
* rejected - failure
* pending - not fulfilled/rejected
* settled - fulfilled or rejected
Explain hoisting
Variable and function declarations are moved to the top of their scope during compilation
Allows them to be used before they’re declared
Explain the this keyword
Refers to the current execution context
Used to access or modify the props of the current object
Arrow vs Regular Functions
Arrow:
* simple, shorter, can skip the return keyword
* do not use ‘this’ or ‘arguments’
* cannot be used as constructors
const multiply = (num1, num2) => num1 * num2
Regular:
* have more flexibility
* can be used in more scenarios
Explain array.map
Creates a new array by applying a provided function to each element of an existing array
Explain array.filter
Creates a new array with elements that pass a specific test implemented by the provided function
Explain array.forEach
iterates over elements of an array and executes a provided function once for each element
Does not create a new array
Explain array.reduce
Reduces elements of an array to a single value.
Takes a callback function and an optional initial value, then the callback is applied to each array element, accumulating the result.
Explain debouncing
Used to optimize event handling by delaying the execution of a function for a specified period of time, or period of inactivity
Explain throttling
Used to optimize event handling by limiting how often a function can be called in a period of time
Explain error handling
Errors are handled using try/catch blocks.
The code that may throw an error is contained in the try block, and the error handling is contained in the catch block
Explain local storage
A web storage object for storing key value pairs locally on the client’s browser
It persists after the browser is closed
Explain session storage
A web storage object for storing key value pairs locally on the client’s browser
It clears after a session ends (i.e. a browser is closed)
Explain CORS, and ways to mitigate it
A mechanism that supports secure requests and data transfers from outside origins (domain, scheme, or port)
For example, when using fonts hosted from another website.
Prevents unauthorized cross-origin requests
null vs undefined
null represents the intentional absence of a value
undefined is assigned to variables that have been declared but not yet assigned a value
Explain Promise.all
takes an iterable of promises as input
returns a single promise that resolves when all the promises in the iterable have resolved,
or rejects when any one of the promises is rejected
Explain prototypes
Objects can be linked to other objects, forming a prototype chain.
When a property or method is accessed on an object, the JavaScript engine first checks if that property or method exists on the object itself.
If it does not, it will check the object’s prototype, and so on, until it reaches the end of the prototype chain.
If the property or method is not found, it will return undefined.
Explain ES6 Classes
The class keyword provides a more familiar and clean syntax for creating objects and their methods
but under the hood, it still uses prototypes to link objects and inherit properties and methods.
Explain a ‘pure’ function
A function that, given the same input, always returns the same output with no side effects
It does not modify or rely on state
Explain …spread
allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected
- combining arrays
*adding a new value to the front of an array - updating an object
Explain async/await
async defines an asynchronous function
await is used inside the async function to wait for the resolution of a promise before proceeding to the next line
Explain how fetch works for HTTP requests
fetch makes an http request, and returns a promise that resolves to the response to that request
Explain setInterval() and setTimeout()
functions for scheduling the execution of a function later in time
setInterval calls a func repeatedly with a fixed time interval
setTimeout calls a func after a fixed time delay
Explain Same-Origin policy
A security measure implemented by web browsers to restrict web pages from making requests to a different domain
Explain Object.create()
a method used to create a new obj with the specified prototype obj and optional props
enables prototype-based inheritance
Explain cookies
Data stored in small text files, used to remember information about a user
Useful for remembering user names, emails, etc.
By default they’re deleted when the browser is closed
Explain the addEventListener method
attaches an event handler to a specified element, which executes when the event occurs
Explain memoization
Storing the results of expensive function calls when the same inputs occur again
Improves the performance of recursive functions by avoiding redundant computations
Explain the typeOf operator
determines the type of a variable, returns type as a string
“number,” “string,” “boolean,” “object,” “function,” or “undefined.”
Explain the Symbol data type
Creates unique, immutable (unchanging) values that can be used as object properties
Often used as keys in objects to avoid naming conflicts
Function declaration vs Function expression
Declarations
standalone statements, can be hoisted - used before they’re declared
Expressions
can be anonymous or assigned to variables, can be passed as arguments, not hoisted
How do you handle CORS related issues?
Configure the server to include the appropriate CORS headers
Access-Control-Allow-Origin
Explain currying
When a func with multiple args is transformed into a sequence of funcs, each taking a single arg
Allows partial application of the fun, creating new funcs with fewer args
Explain Object.keys
Returns an array of a given object’s own string-keyed property names
Explain WeakMap and WeakSet
ES6 collections
Allow devs to create a mapping of key-value pairs, or set of unique values without preventing the garbage collection of keys
Shallow vs Deep copying
Both
* create a new obj or array
Shallow
* copies refs of the original obj’s properties or array elements
*may share refs
Deep
*recursively copies all nested objects or arrays
* creates new refs
Explain isNaN and Number.isNaN
Both
* determine if a value is the number value, NaN
Number.isNaN (ES6)
* true if the given value is a number with value NaN. Otherwise, false.
isNaN
* true if the given value is NaN after being converted to a number; otherwise, false.
Explain the module pattern
Design pattern that encapsulates private and public members within a module.
Typically uses closures to create a private scope for variables and functions, exposing only what is necessary to the outside world.
Primitive data types
undefined
null
boolean
number
string
symbol
Truthy vs Falsy values
Falsy values: false,
0, ‘ ‘ empty string, null, undefined, NaN
Everything else is truthy
Explain Infinity
a numeric value representing positive infinity
represents values that exceed the upper limit of the floating-point
How do you convert a string to a number
3 ways:
* parseInt - extracts the whole number
*parseFloat - extracts the whole number and decimals
*unary plus operator (+)
Explain type coercion
Automatic conversion of values from one data type to another
*comparing values of different types
*using operators
Explain string interpolation
The process of evaluating variables and expressions within a string literal
(${someString}
)