JS210
How can you access the last value in an array?
arr[arr.length - 1];
What is another term for primitive object that means they don't have parts that can change?
atomic
What does `forEach` always return?
undefined
What is returned by a function if it does not contain an explicit `return` that includes a value?
undefined
What value does a variable that is declared by not initialized have?
undefined
Which primitive value does not have an object counterpart?
undefined
Within a function, an argument that wasn't provided in the call will be assigned to what value?
undefined
What do we mean when we say that closures are defined lexically?
'Closure definitions are purely lexical' means that closures are based on the program's structure, not by what happens when it is executed. If a particular function is never called, that function still forms a closure with its surrounding scope. Closures are created when you define a function or method. The closure essentially closes over its environment -- what's in scope. In effect, the function definition and its scope become a single entity called a closure. When the function is invoked, it has access to everything in its environment. That is, it can use any variable that was in the lexical scope where the function was defined. Even if those variables aren't in the lexical scope where you invoke the function, it can still access them.
What is considered actual elements in an array?
- A property name is an array index when it is a non-negative integer. Values that have been assigned to index properties are called elements of the array. All other property names and their associated values are not considered to be elements of the array. The value of `length` is entirely dependent on the largest array index. - Logging an array logs all the indexed values and every key: value pair that the object contains. It logs only the value (e.g., '`baz`', '`qux`') if it's an element. Otherwise, it logs the `key: value` pair. - To count all of the properties in an Array object, use `Object.keys(array).length`. `array.length` only counts the actual elements of the array, the values associated with an index.
Describe when you should choose an array vs. an object.
- Do the individual values have names or labels? If yes, use an object. If the data doesn't have a natural label, an array should suffice. - Does order matter? If yes, use an array. - Do I need a stack or queue structure? Arrays are good at mimicking simple "last-in-first-out" stacks and "first-in-first-out" queues.
What are instances of a function not being in called to use it as intended?
- If a required argument is omitted, the function isn't being used as intended. - If you pass an array to a function that expects a number, the function isn't being used as intended. - If you call a function before you've done any required preparations (such as opening a connection to a remote server), the function isn't being used as intended.
What are the differences between the rest parameters and the `arguments` object.
- rest parameters are only the ones that haven't been given a separate name (i.e. formally defined in function expression), while the arguments object contains all arguments passed to the function. The arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly; - the arguments object has additional functionality specific to itself (like the `callee` property).
What is a ReferenceError?
A `ReferenceError` occurs when you attempt to use a variable or function that doesn't exist.
What is a `SyntaxError`?
A `SyntaxError` is special in that one usually occurs immediately after loading a JavaScript program, and before it begins to run. JavaScript detects `SyntaxErrors` solely from the text of your program. There are several cases where JavaScript can throw a `SyntaxError` while a program is running.
What is a TypeError?
A `TypeError` usually occurs when you try to access a property on a value that does not have any properties, such as null. Trying to call something that isn't a Function can also raise a `TypeError`.
What is a closure?
A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. Closures let a function access a variable that was in scope at the function's definition point even when that variable is no longer in scope or "the combination of a function and the lexical environment within which that function was [defined]." You can think of closure as a function combined with all of the variables in its lexical scope, including function and class names.
What is a pure function?
A function that has no side effects, always returns a value that is dependent on the arguments that are passed to it, and given the same set of arguments, the function always returns the same value during the function's lifetime.
What is a pragma?
A language construct that tells a compiler, interpreter, or other translator to process the code in a different way. Such as: "use strict";
What is the non-strict equality operator?
Also known as the loose equality operator. When the operands have different types it coerces one of the operands to the other operands type before comparison.
What does the `getDate` method return?
A number that represents the day of the week.
Describe what property names and values can be?
A property name can be any valid string. A property value can be any valid expression.
What is object destructuring?
A shorthand syntax that lets you perform multiple assignments in a single expression.
What is a static method?
A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static methods are used to implement functions that belong to the class, but not to any particular object of it
What does Object.assign do?
A static method that combines the key-value pairs of 2 or more objects into a single object.
What does Object.entries do?
A static method that returns an array of nested arrays. Each nested array has 2 elements, one of the objects keys and its corresponding value.
How do you enable strict mode at the global or function level?
Add this bit of code to the beginning of the program file or function definition: "use strict"; Note that the quotes are required.
Describe the JavaScript `length` property?
All property names in an array that are non-negative integer values represent array indexes. The length of the array is always 1 greater than the largest index. The `length` property can be set explicitly. Note that the `length` property does not only count elements (the array indexes that have been assigned values)—the number of "empty slots" is also included in the count. In other words, the value of length is not necessarily the same as the number of elements in an array.
Why is it not good practice to define methods as arrow functions?
Arrow functions have a subtle behavior that can make them unsuitable for use as methods, such as..... - Note that it is safe to use arrow functions in the body of a method; just don't use them to define the actual method.
When should you not use spread syntax with objects?
Because it only returns the properties that `Ojbect.keys` would return it's not the right choice when you need to duplicate objects that inherit from another object. The spread syntax only returns enumerable "own" properties so the prototype is lost. Also note that the length property of an array is not enumerable.
How can you access the value of an object property?
By appending the property name with dot notation or using bracket notation where value inside the bracket is an object key set as a string.
How do some JavaScript engines optimize closures?
By only "including" variable names that the function needs. If it doesn't use a particular variable name, that name isn't included in the closure.
How can the limitations of omitted arguments being set to undefined and excess arguments being ignored be handled?
By using either the `arguments` object or the rest parameter.
How can you remove a key value pair from an object?
By using the `delete` keywordored. `delete person.age`. This will return `true` unless it cannot delete the property.
When is a closure created?
Closures are a lexical feature (not a run-time feature) that are closely related to scope. Closures use the scope at a function's definition point to determine what variables that function has access too. So the variables that are in scope during a function's execution depend on the closure formed by the function's definition. These variables can still be accessed by the function even if those variables aren't in the lexical scope of where the function is invoked.
What is the relationship between closures and scope?
Closures use the scope in effect at a function's definition point to determine what variables that function can access. What variables are in scope during a function's execution depend on the closure formed by the function's definition. It's somewhat circular reasoning, but it's impossible to separate the two.
How can a function be invoked in a way that lets it access something that isn't in scope?
Closures, In JavaScript, functions are first-class objects. We can assign them to variables, pass them as function arguments, and use them as function return values**. That means that we don't have to execute a function in the same scope in which we defined it; we can call it from a completely different part of the program. This is easiest to see with a higher-order function that returns a function object.
How can a function be invoked in a way the lets it access something that isn't in scope?
Closures, In JavaScript, functions are first-class objects. We can assign them to variables, pass them as function arguments, and use them as function return values**. That means that we don't have to execute a function in the same scope in which we defined it; we can call it from a completely different part of the program. This is easiest to see with a higher-order function that returns a function object.6
Are the arithmetic operators useful for arrays?
No, they behave in ways that are not useful and do not produce a warning.
What are some use of the spread syntax with objects?
Create a clone of the object Merge objects
When writing code what can cause errors to arise?
Errors typically occur where assumptions are made in code.
When should you control exceptions?
Exceptions are for exceptional circumstances: situations that your program can't control very easily, such as not being able to connect to a remote site in a web application.
What happens when you set an arrays length to a value larger than the current length?
It places 'empty slots' equal to the original array's length - the new set length.
Describe what a method is?
Functions define the behavior of an object, when the function is part of an object they are referred to as methods. To call a method on an object, you access the method as though it is a property (it is!). JavaScript methods are just Functions with some special behavior such as.....
What does Object.freeze do?
It prevents the properties from being changed but only one level deep. If the object contains nested arrays or other objects, the values inside them can still be changed.
Can a function access variables that are in scope at invocation?
If those variables were in scope when the function was defined, then the function has access to them, but if those variables were not in scope at the function definition point, then they won't be accessible to the function. They will not be in the function's closure. Only the variables that were in scope when the function was defined are available to the function.
Define what we mean by an empty array.
If we're only interested in elements, then we can use length to determine whether the array is empty. However, if we need to include non-elements, then we need to look at the object keys to learn whether the array is empty. If we want to include the gaps, then we can use `length` to determine whether the array is empty. However, if we need to ignore the gaps, then we must look at the object keys to learn whether the array is empty, keeping in mind that some of the object keys may not be unsigned integers. Note, also, that `Object.keys` will include the key of a explicitly `undefined` element in the return value. It does not include the `key` for any 'empty slots'
Although dot notation is preferred, when must you use bracket notation?
When a property name is an invalid identifier, such as `a name` or when the property name is the same as a variable.
What is rest syntax?
Instead of spreading an array or object out into separate items like the spread syntax, it collects multiple items into an array or object. Rest syntax is used most often when working with functions that take an arbitrary number of parameters.
How does the flag `/g` effect the return value of a successful match when using the `match` method.
It provides some additional properties in the value returned such as: - `index`: the index within the string where the match begins - `input`: a copy of the original string - `groups`: used for "named groups"
What is Object Oriented Programming?
Is a way of programming that models problems as objects that have behavior and state. An objects behavior are methods it has access to and its state is represented by characteristics that distinguish it from other object. Focuses on objects, which have attributes and methods. Instead of just programming through actions. This provides the opportunity for: - Encapsulation (closures) - which will give you the ability to keep stuff private and give access to only what you want. - Inheritence - Lets the object inherit the data-type of the parent class. - Polymorphism - An object's datatype can be changed from what it originally was. Ex: circle, square, triangle "classes" could all inherit from shape. However all of these "classes" could morph based on what is needed from them, but still retain inherited properties.
What can be a negative to using a `for/in` loop to iterate through an object?
It also iterates through the properties on an objects prototype. This may not be what is intended for your program.
What happens when you use the String function with an array argument?
It coerces the array into a string in the following manner: `String(['A', 'H', 'E']) // "A, H, E"`
What is an Array prototype object?
It defines the methods for Arrays, all JavaScript arrays inherit from the prototype object.
Describe the `slice` method.
It extracts and returns a portion of the array. `slice` takes 2 arguments with the first being the extraction starting point, the second argument is the stopping point, meaning that every element from the first argument index up to but not including the second argument index. If no second argument is given it returns the rest of the array starting with the index given by the first argument. If no arguments are given `slice` returns a copy of the entire array, which is useful when a destructive method needs to be used on the array but mutating the original array is not desirable.
What Does Strict Mode Do?
It helps to eliminate some silent errors that can occur by throwing errors, prevent code that can cause JavaScript to run in an non-optimal way, and prevents programmers form using names and syntax that may conflict with future JavaScript versions. The changes made by strict mode help to: prevent/lessen bugs, simplify debugging, run code faster, avoid conflicts with future versions of JavaScript.
What is a JavaScript object?
It is a collection type that can store multiple values.
What is Object.create?
It is a static message that provides a way to create a new object that inherits from an existing object. It create a new object and sets the prototype of that object to the object passed as an argument. `b = Object.create(a)`
What does Object.values do?
It is a static method that extracts the values from every own property in an object to an array.
What does Object.keys do?
It is a static method that returns an objects keys as an array. It will only return the objects own keys, no keys are returned from the prototype objects.
How is strict mode scoped?
It is lexically scoped, it only applies to the code that enables it.
What causes a function to be considered as having side effects?
It reassigns any non-local variable. - It mutates the value of any object referenced by a non-local variable. - It reads from or writes to any data entity (files, network connections, etc.) that is non-local to your program. - It raises an exception. - It calls another function that has side effects. If the function can have side effects when used as intended, then we say the function itself has side effects. In practice, functions that have side effects have them regardless of what arguments are passed in.
What does the `hasOwnProperty` method accomplish?
It returns `true` if the objects property passed as an argument is the name of one of the calling objects own properties, else `false`.
How does `includes` work internally?
It uses `===` to compare elements of the array with the argument. So it cant be used to check for the existence of a nested array or object.
What happens to variables that are defined with out a `let`, `const`, or `var` keyword?
JavaScript binds those variables to be a "property" of the global object. This is "almost" the same as if the variable was globally declared.
What happens when non-string keys are entered for an object?
JavaScript coerces the non-string keys to strings. So the values, 1 and '1' represent the same key, as do true and 'true'.
What happens for array indexes that aren't explicitly assigned a value?
JavaScript designates them as `empty`. These empty items have no value at all and if you try to access values at these indexes `undefined` is returned.
Describe hoisting for function declarations.
JavaScript hoists function declarations to the top of the scope; it hoists the entire function declaration, including the body.
What happens when an array is compared with a non-array using the non-strict equality operator?
JavaScript implicitly coerces the array into a string before performing the comparison.
Describe briefly the variables as pointers concept for JavaScript?
JavaScript stores primitive values in variables, but it uses pointers for non-primitive values like arrays and other objects. Pointers can lead to surprising and unexpected behavior when two or more variables reference the same object in the heap. Primitive values don't have this problem. When using pointers, it's also important to keep in mind that some operations mutate objects, while others don't. For instance, `push` mutates an array, but `map` does not. In particular, you must understand how something like `x = [1, 2, 3]` and `x[2] = 4` differ: both are reassignments, but the second mutates `x` while the first does not. The idea that JavaScript stores primitive values directly in variables is an oversimplification of how it works in the real world, but it mirrors reality well enough to serve as a mental model for almost all situations.
So how are we able to call a method on a primitive value?
JavaScript temporarily coerces primitives to their object counterpart when needed.
What are some values that represent silent failures in JavaScript?
Nan, undefined, null, -1
Should the relational comparison operators, `>, >=, <, and <=`, be used with arrays?
No they return true or false in unexpected ways.
How are we able to create custom objects in JavaScript?
Object literal notation - {} Using `new` Using `Object.create` method
Describe a JavaScript object's makeup?
Objects are containers for data and behavior, with the data consisting of named items with values. These values represent the attributes of the object. The associations between a key and a value are called properties.
In regards to JavaScript objects, what are prototypes?
Objects can inherit from other objects. When object `b` inherits from object `a`, `a` is the prototype of `b`. `b` now has access to the properties defined in `a` even though it did not define those properties itself. This relationship, the prototype and the child object, implements inheritance in JavaScript.
When should you use `try/catch`?
Only use `try/catch/finally` blocks when the following conditions are both true: A built-in JavaScript Function or method can throw an Error and you need to handle or prevent that Error. A simple guard clause is impossible or impractical to prevent the Error.
What is the benefit of not having to explicitly create the object form of strings, number, and booleans?
Programmers do not have to create their explicit object form to call methods on them.
What does the `test` method do?
Returns a boolean value based on whether a string argument matches the regex provide.
Describe the data structure object in JavaScript?
Similar to a Ruby hash. A JavaScript object stores a collection of key-value pairs. An objects keys are strings but the value can be any other valid JavaScript type.
Name some of the objects in JavaScript.
Simple Objects Arrays Date Objects Functions
What does the `match` method do?
Sometimes the boolean values of test don't provide enough info about a match, this is when `match` can be used. `match` takes a regex as the argument and returns an array that describes the match. If no match occurs it returns `null`.
When is strict mode enabled automatically?
Strict mode gets enabled automatically inside ES6 classes and JavaScript modules.
What are examples of of standard built-in objects in JavaScript?
String Array Object Math Date
How do the arithmetic operators treat arrays before perfoming their operation?
The array is converted into a string without mutating the array like so: ```javascript let initials = ['A', 'H', 'E']; initials + 'B'; // "A,H,EB" initials; // [ "A", "H", "E" ]
What happens when you set an arrays length to a value smaller or equal to the array's current largest index?
The array will be truncated and lose the data that is removed.
What is partial function application?
Take a function that accepts multiple arguments, bind values to some of them, and return a new function that only accepts the remaining arguments. When invoked, a partially applied function will invoke the original function and merge the passed-in arguments. Partial function application refers to the creation of a function that can call a second function with fewer arguments than the second function expects. The created function supplies the remaining arguments.
What does JSON.parse do?
Takes a single String argument that contains some data in JSON format and converts it to an object. JSON strings look a lot like JavaScript object literals. The main differences are that we double quote the keys, and the literal value appears inside a String.
What is possibly the most important feature of a pure function and what does it imply?
That the same arguments always produce the same return value. This implies that nothing else in the program can influence the function during the function's lifetime. In addition the consistent return value and lack of side effects make them easy to test. Since they are effectively isolated from the rest of the program, you don't have to worry about what happens elsewhere. Nothing outside of the function can have any effect on it. Nothing in the function can have any impact on the rest of the program.
What is an important concept to remember about iterating over JavaScript object keys?
The JavaScript standard doesn't specify an order, so some engines take advantage of that to provide improved performance. Thus, you can't depend on the order of iteration.
When does the `===` operator return true for Date objects?
The `===` operator only returns true with Date objects if the objects are the same object.
What is hoisting?
The behavior that we try to explain with hoisting is merely a consequence of how JavaScript runs programs in two phases. The creation phase prepares your code for execution. In effect all variable declarations are moved to the top of their respective function or block, so block-scoped declarations get "moved" to the top of the block and function-scoped declarations get "moved" to the top of their functions. All function declarations get hoisted to the top of their defined scope.
Describe what happens when a function encounters a variable name during execution?
The function fist looks inside it's local scope for that name. If it isn't found, it then looks to see if the name is inside of it's closure. If it is JavaScript can follow the pointer and get the current value of the variable.
JavaScript Properties
key-value pairs within a JavaScript object.
How do the built-in Array methods handle properties that are not array indexes or 'empty slots'?
The most notable issue is that properties that are not array indexes will not be processed by the built-in Array methods. "Empty slots" also will not be processed by the Array methods, since they're not array elements.
What is a sparse array?
The number of elements in an array isn't necessarily the same as its length: there can be gaps in the array. One way to create these gaps is by increasing the size of the length property without adding any values to the array.
What is exception handling?
The process that deals with errors in a manageable and predictable manner. The reserved words try and catch and finally are used in JavaScript exception handling. It uses the try/catch statement to catch exceptions that the code in the try block raises, and lets the programmer deal with the problem in a way that makes sense and perhaps prevents bugs.
Describe the behavior of the rest parameter. `...args`
The rest parameter syntax allows us to represent an indefinite number of arguments as an array. A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" JavaScript array. Only the last parameter can be a "rest parameter". function myFunction(a, b, ...args) { // ... }
What happens when 2 arrays that contain the same values are compared with `==` or `===`?
The result is always false because they are different objects. Arrays are only equal when the 2 arrays are the same array in a strict sense.
What is the spread syntax and what are common use cases of it for arrays?
The spread syntax uses `...` to "spread" the elements of an array or object into separate items. To create a clone of an array. Concatenate arrays Insert an array into another array
What actions are able to be performed on a variable that contains only primitive values?
The variable can only be used in an expression or reassigned. All operation on primitive values evaluate to new values. Even `0 + 0 = 0` results in a new value.
Give a mental model of closures.
When a function is defined, JavaScript gathers all of the variable names within the scope of the function definition. It places all of those names in a "backpack" that is attached to the function object. Each name in the backpack is a pointer to the original variable, not the value it contains. Therefore if the value of a variable is changed the closure has access to the new value.
Explain the datatype object?
They are complex values composed of primitive values or other objects. This means we are able to mutate an object because it contains parts that are mutable, such as a value that is an array.
What happens to omitted function arguments?
They are given a value of `undefined` within the function and the function ignores any excess arguments.
How do you check if 2 arrays contain the same elements?
They must be compared element by element
True/False. Function names and parameters are both considered variable names in JavaScript.
True
When should you use an array vs. an object?
Use an array when data is more like list and/or you need to maintain data in a specific order. With arrays most interactions involve adding/retrieving elements, modifying or removing elements, and iterating over elements. Use an object if the data is more like an entity with many parts. With objects interaction usually involves accessing a value via its key, using the key to add, retrieve, modify, or delete data. Use an object if you need to access values base on the names of those values.
When should you use capitalized vs. lowercase names when speaking about primitive types and object forms of primitive types?
Use capitalized names when speaking about the object form. Use lowercase if speaking about a primitive type.
When should you use object vs. Object?
Use object to refer to objects in general. Use Object when referring to methods and properties from the Object 'class'.
What are some of the AirBnB guidlines?
Use single quotes `(')` with Strings, unless the String contains single quotes. The style guide recommends one `let` declaration per variable. Also, variable names should use camelCase. Always always use the strict equality operators. Always use braces around multi-line if statements: Always use two spaces to indent code, and surrounding operators with spaces. Recommends to use explicit string coercion. Recommends using named function expressions instead of function declarations.
When should you use (or not use) strict mode?
Use strict mode in any new code that you write. If you're adding new functions to an old code base, it's safe to use function-level strict mode in the new functions. If you're not creating a new function in that old code base, you probably shouldn't try to use strict mode. The changes in semantics, particularly those having to do with variable declarations, this, and silent failures, can easily break code that otherwise works well.
How can we compare 2 different Date objects with the same value and return true?
Use the `toDateString` method on each operand.
How are strings compared?
Using Unicode lexicographical ordering
How can you raise your own exceptions?
Using the `throw` keyword: `throw new TypeError("string argument here")`
How can instead of avoiding errors, can we handle them in JavaScript?
Using the `try/catch/finally` block.
Describe the best practices to avoid hoisting confusion.
When possible use `let` and `const` instead of `var`, If you need to use `var`, declare all of the variables at the top of scope. If you can use `let` and `const`, declare them as close to their first usage as possible: Declare functions before calling them:
When can you omit the quotes for an objects key?
When the key consists of entirely of alphanumeric characters and underscores
What is the temporal dead zone
When variables that are declared with `let` and `const` are hoisted they are left in an 'unset' state, meaning they are "not defined". If you try to access variable in this state JavaScript throws an error.
When can the fall-through behavior of a switch statement be useful?
When you want to execute the same action for 2 or more cases.
Describe the mutability of objects.
While primitive values are immutable: you cannot modify them. Operations on these values return a new value of the same type, objects are mutable: you can modify them without changing their identity. Objects contain data inside themselves; it's this inner data that you can change.
How can a specific value in an object be accessed?
With dot notation. `person.name` With bracket notation. `person['name']` If you have a variable that contains a keys name you must use bracket notation to access the value.
How do the built-in objects that share their name with with primitive values differ from each other, eg String vs. string?
With primitive values theoretically we can't call methods on them. Getting the length of a string for example. Only the object data type can have methods called on it.
Describe how code behaves under both strict and sloppy mode.
You cannot create global variables implicitly. Functions won't use the global object as their implicit context. Forgetting to use this in a method raises an error. Leading zeros on numeric integers are illegal. Strict mode makes other changes as well, but the above changes are the most important for most JavaScript developers.
How can an array be created in JavaScript?
[] let count = new Array(1, 2, 3); let count = [1, 2, 3];
How is the `arguments` object different than an Array?
`argument object`.isArray is false. Array methods cannot be called on the `argumenets` object.
How can you create an Array from the `arguments` object?
`let args = Array.prototype.slice.call(arguments)` Here we are 'borrowing' the `slice` method from the Array global object giving us an array that contains the same values as those in the `arguments` object.
What are closures good for?
callbacks partial function applications creating private data currying - a special form of partial function application emulating private methods creating functions that can only be executed once Memoization - avoiding repetitive resource intensive operations. iterators and generators the module pattern Asynchronous operations
What are some ways to avoid errors?
guard clause - best used when a Function can't trust that its arguments are valid. Invalid arguments can have incorrect types, structures, values, or properties. Think about whether your program can violate your assumptions. What happens when they do? We call these situations edge cases because they often involve values at the extreme end of the range of possible values. Think about how particular combinations of values can create unexpected conditions.
Are closures a run-time or lexical feature of JavaScript?
lexical
What are 4 ways to create a date object?
new Date(); new Date(value); new Date(dateString); new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);)
Does `reduce` mutate the caller?
no
Can you access arguments values in the `argument` object using bracket notation?
yes
Can you change an objects properties when the object was declared with `const`?
yes
Does `sort` mutate the caller?
yes
Does the `arguments` object have a `length` property?
yes
How can a string be coerced into a boolean?
By comparing the string representation of a boolean with `true`. 'true' === 'true'; // true 'false' === 'true' // false
How can you determine whether a variable references an array?
By using the `Array.isArray()` method.
What is the strict equality operator?
Also known as the identity operator, it returns true when the operands have the same type and value.
What are the best practices concerning implicit type coercion?
Always use explicit type coercion. Always use strict equality operators.
What happens when a JavaScript function is called with too few arguments?
An error is not raised based on too few or too many arguments being used in the function call.
What is an expression?
Any valid code that resolves to a value, such as `'hello'`, `2 + 3`, `total = 7`.
What is an expression in JavaScript?
Any valid code that resolves to a value. "Hello"; 10 + 3; sum = 11;
What are local variables?
Any variable declared inside a block or function. All other variables are global variables.
What are arrow functions most often used for and why are they useful?
As callback functions. Arrow function inherit the execution context for the surrounding code.
What does the following code do? array[array.length] = 10;
It adds the number 10 to the end of the array.
What does the splice method do?
It allows for the removal or replacement of one or more elements from an array from anywhere in the array. You can pass the first argument which represents the index to start deleting at followed by the number of elements to be deleted.
How is passing a function expression as and argument to another function useful?
It allows the other the function to call the function represented by the argument. In the case of `forEach` method, `forEach` loops through each element in the array sequentially from the first element. For each element in the array `forEach` invokes the function passed as an argument.
What is a function expression?
It defines a function as part of a larger expression syntax, typically a variable assignment.
What happens when JavaScript encounters the `return` statement?
It evaluates the expression, terminates the function, and returns the expression's value (`undefined` if no expression is present) to the location where it was called. Control is returned to the caller.
What does the break statement do?
It exits from a loop immediately.
Describe what a while loop does?
It first evaluates the condition, then executes the statements in the loop body if the condition has a truthy value. When the execution of code in the block reaches the end of the block, control is passed back to the expression again, if the condition is still a truthy value, the statements in the loop body are executed again. This process continues until the condition produces a falsy value.
Describe the do/while loop.
It first executes the code in the loop body, and then passes control to the while condition. If it is truthy, the statements in the body of the loop are executed again. This process is repeated until the condition is falsy.
How can the value of a JavaScript function variable be used?
It follows general scoping rules and can be used like other JavaScript variables.
What is a callback?
It is a function that is passed to another function as an argument. The called function then invokes the callback function at certain times when it runs, such as for each element in an array when passed to the `forEach` method.
In the context of `&&` and `||` what is the return value?
It is always the value of the last operand evaluated.
What does the `filter` method do?
It returns a new array that include all the elements from the calling array for which the callback function returns a truthy value.
What does the Object.keys method do?
It returns an array's keys, which are its index values, as an array of strings.
How does the operator % behave in JavaScript?
It returns the remainder of integer division. 10 % 3 = 1 10 % -3 = 1
What does the continue statement do?
It skips the current loop iteration and returns to the top of the loop to execute the next iteration.
What are the main interactions with arrays?
Iterating through an array and performing an action on each value and accessing and manipulating specific elements of an array.
What is implicit coercion?
Its is JavaScript trying to make sense of an expression by converting values to types that it can operate own, such as `'4' + 3` , where 3 is coerced to the string '3', so the result is '43'. Implicit coercion can lead to undetected bugs.
What happens when you create an array "element" with something other than a non-negative integer?
JavaScript places them into the array not as true elements but as properties on the array object. They do not count towards the length of the array.
What is the result if one operand is a string and the other is a number when the operator is a mathematical operator is not the `+`?
JavaScript will coerce the string into a number and then perform the operation, if the string cannot be coerced into a number the calculation results in `NaN`.
What is a way to limit name clashing among variables in a program?
Limit the scope of variables to the smallest scope possible.
Does `concat` mutate the array that calls it?
no
What are the JavaScript primitive data types?
number boolean string null undefined symbols big integers
What are the JavaScript primitive datatypes?
number boolean string null undefined symbols big integers
What are the JavaScript compound datatypes?
object
What does `typeof null` return?
object
List and describe JavaScripts special number values.
`Infinity` - when you need a number that is greater than any other number. `-Infinity` - when you need a number that is less than any other number. `NaN` - "not a number" is returned when a math function encounters an error. Note that `typeof NaN` returns number.
What is `NaN`?
`NaN` is a special value in JavaScript that represents an illegal operation on numbers.
What is the main difference between a while loop and a for loop?
In a while statement, the scope includes the code that surrounds the loop. In a for statement, the scope is the for statement and its body.
What is the major advantage of a ternary operator versus an if/statement?
The fact that it is an expression which means it can be treated like a value an be assigned to a variable and passed as an argument.
Demonstrate how the Boolean function can be used to convert any value into a boolean value based on the truthy and falsy rules in JavaScript.By comparing the string representation of a boolean with `true`.
'true' === 'true'; // true 'false' === 'true' // false Boolean(null); // false Boolean(NaN); // false Boolean(0); // false Boolean(''); // false Boolean(false); // false Boolean(undefined); // false Boolean('abc'); // other values will be true Boolean(123); // true Boolean('true'); // including the string 'true' Boolean('false'); // but also including the string 'false'!
How does Object.keys treat unset values versus undefined values?
(Unset values are set to `undefined` by JavaScript as an after effect of calling another method, while explicit `undefined` are ones that are purposely set in an array.) The `length` property of Array includes `undefined` in the count regardless of how it got set while `Object.keys` only counts those that were set explicitly.
Describe when you should use each type of JavaScript function?
- Use arrow functions for callbacks - Use function declarations or function expressions for other functions but be consistent through out your code. - If you use function expressions, named function expressions are better for debugging and to help clarify the intent of those functions.
How can variables be added to a current scope?
- use `let`, `const`, or `var` - define parameters for a function (create variables by naming the arguments to a function via its parameters) - a function declaration creates a variable - a class declaration creates a variable
What data type does `prompt` return?
A string value
What is meant by "JavaScript is a dynamically typed language " ?
A variable can hold a reference to any data type and can be reassigned a different type without error.
What is meant by dynamic typing?
A variable may point to a value of any data type and can be reassigned to a different type.
List the operators in order of precedence.
Comparison `<=`, `<`, `>`, `>=` Equality `==`, `!=` Logical AND `&&` Logical OR `||`
What can named function expressions be useful for?
Debugging. The debugger can show the function's name in the call stack. They cal also be useful for recursive functions.
What are 3 ways to define a function?
Function declaration Function expression Arrow function
Describe the for loop.
If allows for the combination of 3 key elements of a loop: setting the initial state, evaluating a condition, and making some type of change before re-evaluating the condition. 1. It first executes the initialization statement which may include variable declarations. 2 .The condition is then evalutaed at which point the loop terminates if the condition is falsy. 3. The body of the loop is executed. 4. The increment expression is executed 5. The next iteration of this process is starts over at step 2.
How does JavaScript handle evaluating if 2 arrays are equal?
If the 2 arrays being compared are the same array then they are equal. They must occupy the same space in memory.
How can you differentiate between function declarations and named function expressions?
If the statement begins with the `function` keyword, it is a function declaration, else it is a function expression, even placing parentheses around the statement is enough to turn a function declaration into a function expression.
What property does an arrow function have that a function declaration and function expression do not?
Implicit return values. An explicit return statement can be omitted when the function body has one expression.
What is a conditional statement?
Sets of commands that are triggered when a condition is true.
Describe how anonymous functions may be referred to by other programmers and what that means.
Some developers refer to anonymous functions by the name of the variable to which it is assigned. For instance, instead of saying the "anonymous function assigned to `foo` returns..", we can instead say the "`function foo` returns..". While at Launch School and in job interviews, use the former, more precise, wording. You can also leave out "anonymous" unless it is relevant.
What is a statement?
Statements don't necessarily resolve to a value. They are usually responsible for controlling the execution of a program, such as a variable declaration, `let sum;`. Statements always evaluate as undefined. Unlike expressions they cannot be used as part of an expression.
What is an initializer?
The expression to the right of the = sign in a variable declaration.
What happens if you change an array's length property to a new smaller value
The array gets truncated; all the elements beyond the new final element are removed permanently.
What are determinants of whether a variable is local or global?
The keyword used to declare the variable and the location where the variable is declared.
What happens if you change an array's length property to a new longer value?
The new elements do not get initialized. JavaScript treats the unset array elements as missing, but the length property includes the unset elements.
What is function composition?
The process by which JavaScript allows the use of a function call as an argument to another function.
What is lexical scoping?
The structure of the source code is used to determine a variable's scope. Scope is created when a variable, function, or block is created.
What does `push` return?
The updated length of the array that called it.
What are operands?
The values the operator works on.
What are the characteristics of a nested function?
They are created and destroyed every time a function runs. They are private functions, they cannot be accessed from outside the function where it is defined. The code within an inner scope can access any variables in the same scope or any surrounding scope.
Describe what is meant by "local variables are short-lived"?
They are destroyed when the function that corresponds to their scope returns. When the function is called a new scope is started. Any variables that are declared belong to the scope. When the last of the code runs in that scope the scope goes away along with any variables declared in it.
What is meant by "a function is a first class function"?
They can be treated like any other value. They can be assigned to a variable, pass them as arguments to other functions, and return them from a function call.
What is meant by primitive types are immutable?
They cannot be changed once they are created. No function, method, or other operation will modify a primitive data type.
How are strings compared in JavaScript?
They use unicode lexographical ordering
What is a purpose of a function?
To extract code that needs to be run several times and run it as a separate unit. This can help to make a program more flexible. To perform an operation and return a result to the call location for later use.
True/False. Parameters are local variables.
True
True/False. Parameter values inside the function are also called arguments.
True - you can think of parameters as placeholders, while arguments refer to the values that get stored in the placeholders.
How can you check if a variable holds NaN?
Using the `Number.isNaN` function.
Show several ways to create an array.
[] // Using the Array constructor let count = new Array(1, 2, 3); // Or let count = [1, 2, 3];
When can block scoping occur?
When `let` or `const` is used inside a block.
What is meant by mutating the caller?
When a method permanently alters the object that invoked the method.
What is a method invocation?
When a variable name or value is followed by a `.` and a function name.
Describe the difference between the two form of `++`, the pre-increment operator and the post-increment operator.
While both increment the variable, they differ in what gets returned by the expression. The pre-increment form returns the new value of the variable. The post-increment form returns the previous value of the variable.
Can a function mutate its arguments?
Yes
Can a statement have an expression as part of it's syntax?
Yes for instance `let total = 11;`. In this `let` statement the code to the right of the `=` is an expression.
Do constants have to initialized when they are declared?
Yes, they cannot be assigned later because they will already be assigned to undefined. constants cannot be reassigned.
What is a key difference between function declarations and function expressions?
You cannot invoke a function expression before it appears in your program.
What type of numbers does JavaScript use?
double precision floats
What values are treated as false in JavaScript?
false 0 -0 '' undefined null Nan
What is the return value of comparing NaN with any value?
false, even with `NaN === NaN`
What structure/syntax does a function have?
the `function` keyword the name of the function a list of comma separated parameters the function body which is a block of statements
Can you modify the contents of an array declared with the `const` keyword?
yes
Does the `push` method mutate its caller?
yes