JavaScript Flashcards
What is a Promise?
A Promise is a special JavaScript object. It produces a value after an asynchronous (aka, async) operation completes successfully, or an error if it does not complete successfully due to time out, network error, and so on.
Successful call completions are indicated by the resolve function call, and errors are indicated by the reject function call.
What is asynchoronous?
Refers to the management of a single thread that can move past tasks that are waiting to complete the rest of the program. Synonymous with non-blocking.
Can you overwrite variable declarations without an error using var?
Yes; var camper = 'James'; var camper = 'David'; console.log(camper); // logs 'David'
What will let math = 12 + ‘13’; console.log to?
1213
What is the result of this: const s = [5, 6, 7]; s = [1, 2, 3]; // ???? s[2] = 45; // ?????? console.log(s); // ?????
s = [1, 2, 3]; // throws error, trying to assign a const
s[2] = 45; // works just as it would with an array declared with var or let
console.log(s); // returns [5, 6, 45]
Objects (including arrays and functions) assigned to a variable using const are still mutable. Using the const declaration only prevents reassignment of the variable identifier.
What function prevents data mutation of an object?
Object.freeze(obj);
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY']; let arr2;
arr2 = arr1;
arr1[0] = ‘OCT’
console.log(arr2); /// what does this log?
[ ‘OCT’, ‘FEB’, ‘MAR’, ‘APR’, ‘MAY’ ]
arr1 and arr2 are referencing the same array (object), so when arr1 is update, arr2 is updated.
To make an array that won’t change with arr1, use the spread operator:
arr2 = […arr1]
What does Array.shift() do?
Removes the first item from an array
let array = [‘today’, ‘was’, ‘not’, ‘so’, ‘great’];
let splice = array.splice(2, 2);
What are the values of array and splice?
array now equals [‘today’, ‘was’, ‘great’]
splice equals [‘not’, ‘so’]
(removes 2 elements beginning with the 2nd index)
Array.splice(starting index, how many to remove, (optional items to add in place))
const arr = ['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms'] const newArr = arr.slice(2, 4) What is newArray?
[ ‘warm’, ‘sunny’ ]
arr.slice() returns a new array and takes in up to 2 arguments- first the starting index and second the ending index (not included).
arr will return the same array as it is not affected
What are data structures?
Techniques for storing and organizing data that make it easier to modify, navigate, and access. Data structures determine how data is collected, the functions we can use to access it, and the relationships between data.
What makes JavaScript functions first class objects?
a function can be assigned to a variable, passed around as an argument to another function and can also be returned from another.
What does this return?
console.log(square(5));
var square = function(n) { return n * n; }
TypeError: square is not a function
If you define a function as a variable, the variable name will be hoisted but you cannot access until JS execution encounters its definition.
If this was not assigned to a variable, would not return an error.
What are the six falsy values?
undefined, null, NaN, 0, “” (empty string), and false
Will these return true or false?
1) false == “”
2) NaN == undefined
3) 0 == null
4) null == undefined
5) NaN == NaN
6) 0 == “”
1) false == “”, true
2) NaN == undefined, false
3) 0 == null, false
4) null == undefined, true
5) NaN == NaN, false (NaN is not equivalent to anything, not even itself!)
6) 0 == “”, true
If can use Object.is(NaN, NaN) to see if it is equal (will return true)
What are the 6 primitive data types of JavaScript?
undefined Boolean Number String BigInt Symbol
How do you make a new object, using an existing object as the prototype of the newly created object?
let obj = Object.create(proto, [descriptors])
Example: let animal = { eats: true };
// create a new object with animal as a prototype let rabbit = Object.create(animal);
Technically, we can get/set [[Prototype]] at any time. But usually we only set it once at the object creation time and don’t modify it anymore. Changing a prototype “on-the-fly” with Object.setPrototypeOf or obj.__proto__= is a very slow operation as it breaks internal optimizations for object property access operations.
Can inherited properties of an object be overwritten?
Yes!
What is a JavaScript object?
An object is a collection of properties, and a property is an association between a name (or key) and a value. The object can contain any data types (numbers, arrays, object etc.)
Describe encapsulation.
Refers to bundling data with methods that can operate on that data within a class It is the idea of hiding data within a class, preventing anything outside that class from directly interacting with it Members of other classes can interact with the attributes of another object through its methods It’s generally best to not allow external classes to directly edit an object’s attributes Prevents data from getting into unwanted states
Describe abstraction
Refers to only showing essential details and keeping everything else hidden
Users of the classes should not worry about the inner details of those classes and should not directly interact with other classes’ data
If classes are entangled, then on change creates a ripple effect that causes many more changes
Creating an interface through which classes can interact ensures that each piece can be individually developed
What is the difference between encapsulation and abstraction
Abstraction is about hiding unwanted details while giving out the most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect the inner working of an object from the outside world. In other words, Abstraction means extracting common details or generalizing things.
What is polymorphism and what is the difference between static and dynamic polymorphism?
Polymorphism is the ability to call the same method on different objects and have each of them respond in their own way.
Dynamic:
-Occurs during the runtime of the program (when it is being executed)
-Describes when a method signature is in both a subclass and a superclass
-The methods share the same name but have different implementation
-The subclass that the object is an instance of overrides that of the superclass
Static:
-Occurs during compile-time rather than during runtime
-Refers to when multiple methods with the same name but different arguments are defined in the same class
-Despite the methods having the same name, their signatures are different due to their different arguments
What will this print: function Foo(){ console.log(this); }
It prints the window object because this is a global object. Whatever parent scope is, it will be inherited by the child.
let obj1 = {name: 'GreenRoots'}; let obj2 = {name: 'GreenRoots'};
obj1 == obj2 // ???
obj1 === obj2 // ???
Object.is(obj1, obj2); // ???
They all return false because non-primitive data types are passed by reference (unlike primitive types that are passed by value).
Hence both obj1 and obj2 the value at the different memory locations that they are created on.
What will this return in strict mode and non-strict mode? function f1() { return this; }
Non-strict: // In a browser: f1() === window; // true // In Node: f1() === globalThis; // true
Strict:
f1() === undefined; // true
What is execution context? Explain 2 types.
An execution context is an abstract concept of an environment where the JavaScript code is evaluated and executed.
- Global execution context: The code that is not inside any function is in the global execution context. It performs two things: it creates a global object which is a window object (in the case of browsers) and sets the value of this to equal to the global object.
- Functional execution context: Every time a function is invoked, a brand new execution context is created for that function. Each function has its own execution context, but it’s created when the function is invoked or called.
What is a lexical environment?
A structure that holds identifier-variable mapping, where identifier refers to the name of variables/functions, and the variable is the reference to actual object or primitive values.
Every time the JavaScript engine creates an execution context to execute the function or global code, it also creates a new lexical environment to store the variables defined in that function during the execution of that function.
Why is Math.max() smaller than Math.min()?
If no arguments are given, Math.min() returns infinity and Math.max() returns -infinity . This is simply part of the specification for the max() and min() methods, but there is good logic behind the choice.
How does a function expression differ from a function declaration?
Function declarations are hoisted, which means they are moved to the top of their scope by the interpreter. This allows you to call it anywhere in your code. You can only call function expressions linearly. Thus function expressions are more predictable and structured. Assigning them to let and const also provides control is it can be re-assigned or not.
What are the differences between var, let, and const?
Const can't be reassigned (although does allow for variable mutation... just can't re-assign the variable itself). Const also can't be declared without a value... will have syntax error All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized. During compile time, JavaScript only stores function and variable declarations in the memory, not their assignments (value). They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. Var is function scoped while let and const are block scoped (scoped within things like if statements and for loops
What is hoisting?
During compile phase, just microseconds before your code is executed, it is scanned for function and variable declarations. All these functions and variable declarations are added to the memory inside a JavaScript data structure called Lexical Environment. So that they can be used even before they are actually declared in the source code. Conceptually, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code
What is temporal dead zone?
A time span between variable creation and its initialization where they can’t be accessed.
What will this output?
let a;
console.log(a);
a = 5;
Undefined.
Here during the compile phase, the JavaScript engine encounters the variable a and stores it in the lexical environment, but because it’s a let variable, the engine does not initialize it with any value.* *Would have same result with var because the assignment does not get hoisted, just the variable name.
During the execution, when the engine reaches the line where the variable was declared, it will try to evaluate its binding (value), because the variable has no value associated with it, it will assign it undefined.
Without the declaration of “let a” at the top, the output would be a Reference Error: a is not defined.
console.log(a); var a = 5;
This however would not return an error but show undefined (variable name hoisted, but not assignment.)
What are things not allowed in ‘use strict’
Strict mode changes previously accepted “bad syntax” into real errors.
- Using a variable, without declaring it, is not allowed like x=5
- Mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
- assigning values to non-writable properties
- deleting a variable or function
- duplicating parameters
- The this keyword refers to the object that called the function. If the object is not specified, functions in strict mode will return undefined and functions in normal mode will return the global object (window):
What happens if you assign a variable without a keyword?
If not using strict mode, it will be assigned to the window. So x = 1 will be window.x = 1
Describe Object Oriented Programming.
OOP is based around the concept of “objects”. These are data structures that contain data fields — known in JavaScript as “properties” — and procedures — known as “methods”.
Some of JavaScript’s in-built objects include Math (used for methods such as random , max and sin ), JSON (used for parsing JSON data), and primitive data types like String , Array , Number and Boolean .
Whenever you rely on in-built methods, prototypes or classes, you are essentially using Object-Oriented Programming
What are the 4 main principles of Object Oriented Programming?
Encapsulation, abstraction, inheritance, and polymorphism
Explain functional programming.
FP is based around the concept of “pure functions”, which avoid shared state, mutable data and side-effects. Given the same inputs, a pure function always returns the same output. It does not have side effects
What’s the difference between imperative and declarative programming?
Imperative programming is concerned with how you do something. It spells out the steps in the most essential way, and is characterized by for and while loops, if and switch statements, and so on. OOP is an example of imperative programming.
Declarative programming is concerned with what to do, and it abstracts away the how by relying on expressions. This often results in more concise code, but at scale, it can become more difficult to debug because it’s that much less transparent. Functional programming is an example of declarative programming.
What is a closure?
A closure is the combination of a function and the lexical environment (the scope of the function- identifiers it has access to) within which that function was declared. In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
What makes closures powerful is when a function is returned from another function. When a function is declared in a function, but returned and run outside of where it was declared it will still have access to the scope it was declared in because of closure.
The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods (any exposed method defined within the closure scope)
const getSecret = (secret) => { return { get: () => secret }; };
console.log(secret) // ReferenceError: secret is not defined const obj = getSecret(1); const actual = obj.get(); console.log(actual) //1
What is scope and describe the types.
Scope determines the accessibility of variables. Scope determines where the identifier, such as a variable or function name, is visible and accessible.
Variables declared within a function have local scope and can only be accessed from within the function.
A global variable has global scope and all scripts and functions on a web page can access it.
What are prototypes?
Prototypes are the mechanism by which JavaScript objects inherit methods and properties from one another.
What is a ReferenceError and name common examples.
A ReferenceError indicates that an invalid reference value has been detected.
A JavaScript program is trying to read a variable that does not exist:
dog
dog = 2 (need use strict)
Or there are unexpected assignments (such as using = when you should use ==
What is a SyntaxError and name some examples.
- A function statement without name
- Missing comma after an object property definition
- Trying to use a reserved identifier like delete or class
- Missing ) or } or ; or ,
What is a type error and name some examples.
A TypeError happens when a value has a type that’s different than the one expected
- Mistyping a method… blank is not a function
- Unexpected undefined and null types
Describe Node.js. List benefits and drawbacks.
Node.js is a JavaScript runtime built on Chrome’s v8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O (in-out) model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world. A runtime is something that provides custom functionality so various tools and libraries specific to the environment (it is not a programming language).
Benefits:
- It re-uses Javascript- meaning a front-end Javascript developer can also build an entire server themselves
- It’s easily extendable- numerous plugins exist to expand on the capabilities of Node
- Fast-implementation- which allows for the creation of an entire working server with only a few lines of code
- Single-threaded asynchronous model- meaning it can handle multiple requests simultaneously and not get bottlenecked
- It is non-blocking because Node uses other threads in C++ to manage your events