JS101 Flashcards
instead of:
if (x > 3) return true
You should?
return x > 3
Instead of:
variable <= 0 || variable >= 5 || Number.isNaN(Number(variable))
break;
you should?
Check it’s existence on an array:
If (![‘1’, ‘2’, ‘3’, ‘4’].includes(variable))
Instead of:
variable <= 0 || variable >= 5 || Number.isNaN(Number(variable))
break;
to check if the number is between two numbers and is a number, you should?
Check it’s existence on an array:
If (![‘1’, ‘2’, ‘3’, ‘4’].includes(variable))
How does Try/Catch work?
When should you use it? (2 considerations)
try {
// Do something that might fail here and throw an exception.
} catch (error) {
// This code only runs if something in the try clause throws an exception. // “error” contains the exception object.
} finally {
// This code always runs even if the above code throws an exception. }
Only use try/catch/finally blocks when the following conditions are both true:
A built-in JavaScript function or method can throw an exception and you need to handle or prevent that exception.
A simple guard clause is impossible or impractical to prevent the exception.
What’s the difference between String and .toString()
String
> String(null) ‘null’
> String(undefined) ‘undefined’
.toString()
> null.toString();
Error
What happens with:
` ${ undefined} ` ?
undefind is converted into a string.
This is why you don’t do String() or .toString() in template literal.
What is returned from:
+[]
+[1]
+[1, 2]
0
1
NaN
When should you do implicit conversion (at launch school)?
Never
When should you use ==
never
When a string and number are compared, what is coerced to what?
‘12’ == 12
String to number
When Boolean is compared to something, what is converted to what?
true == ‘apple’
Boolean always converted to number
Above is false;
true == ‘1’
true
true + true == ‘2’
rue
When an Object is compared to a primitive, what is converted to what?
When an object is compared with a primitive value, the object is coerced into a primitive value and compared again using the == operator.
> ’’ == {}
false
‘[object Object]’ == {}
true
[] == ‘’
true
> [] == 0
true
[] becomes ‘’
which then is compared again and becomes 0
Null == undefined?
Null === undefined?
True
False
true >= 1
> [] == 0
> 1 == true
true
true
true
> 3 == true
0 == false
false
true
> ‘[object Object]’ == {}
‘[object Object]’ == {rt: 21}
[] == ‘’
String([1, [1, 2]])
true
true
true
1,1,2
String + something?
Becomes a string
Number, boolean, null, undefined, + together?
true + true
null + 3 + undefined
Becomes number
2
NaN
Object/Array + something?
Becomes a string
Three rules for conversion/comparison at launch school
One rule for conversion in template literals
Always use explicit
Always use strictcomprison
Can use + for technically implicit number coersion
Don’t use String() or toString() inside ${…} expressions in template literals (just redundant).
What are the elements of PEDAC
Problem
Examples
Data Structures
Algorithm
Code
What is involved with PROBLEMS in PEDAC? (4 things)
Understand the problem
- read the problem description
- examine all given examples for info
- ask clarifying questions
- identify INPUTS/OUTPUTS
- identify RULES/REQUIREMENTS
- mental model problem. Sort of like a VERY simple algorithm. Just describe what you broadly need to do.
What is involved with EXAMPLES in PEDAC (4 things)
- understand how the input translates to output
- identify VALID CASES
- identify EDGE CASES
- create the test cases and confirm outputs
What is involved with DATA STRUCTURES in PEDAC? (3 things)
- what sort of actions do you have to do (sort, collect, filter, etc.)
- what kind of data are you primarily dealing with? (strings, arrays, numbers, objects, etc.)
- focus on methods for these types
What is involved with ALGORITHM in PEDAC? (2 things)
- step by step process that takes you from input to output, your code will depend on your algorithm
- handles edges cases and valid example inputs
Instead of radius * 3.14
What should you do?
pi = 3.14
radius * pi
Otherwise it’s a “magic” number. Don’t do it.
Which should you do?
const FIRST_CHARACTER_CODE = 97;
vs
const FIRST_CHARACTER_CODE = ‘a’.charCodeAt();
Second one. More readable and understandable.
A function is said to have side effects if it does any of the following:
(5 things)
It reassigns any non-local variable. Reassigning a variable in the outer scope would be a side effect.
It mutates the value of any object referenced by a non-local variable. Mutating an array or object argument, for instance, would be a side effect.
It reads from or writes to a file, network connection, browser, or the system hardware. Side effects like this include writing to the console log and reading input from the terminal.
It raises an exception without handling it.
It calls another function that has side effects.
A function should not have a side effect AND return a value
T or F
True
If you write functions that do both, you may have trouble remembering one of those – either you’ll forget about the side effect, or you’ll forget that there’s a return value that you need to examine.
How to name a function that has a side effect vs a return?
Can do “display” to show user
“print” to show in console.
“compute” suggests a return
“get” suggests asking. maybe “ask”
“read”
“write”
Why is this:
while (true) {
console.log(‘Continue? (y/n)’);
let answer = readline.question();
if (answer.toLowerCase() === ‘n’) break;
}
Better than this:
let answer = ‘’;
while (answer.toLowerCase() !== ‘n’) {
console.log(‘Continue? (y/n)’);
answer = readline.question();
}
Because if answer isn’t defined in the second instance, the program won’t run.
Write a function that takes a number as an argument. If the argument is a positive number, return the negative of that number.
function negative(number) {
return Math.abs(number) * -1;
}
An equation that gives a random number in between 2 values?
How to make it so that if the user puts the numbers in the wrong order it still works?
function randomNumberBetween(minNum, maxNum) {
if (minNum >= maxNum) {
[minNum, maxNum] = [maxNum, minNum];
}
return Math.floor(Math.random() * (maxNum + 1 - minNum)) + minNum;
}
You’re repeating certain mathematical things, like ‘string’.length / 2. What should you do?
Make it a variable.
centerIndex = ‘string’.length / 2
What happens with:
let myVar = [1];
function myFunc(myVar) {
myVar[0] = 2;
}
myFunc();
console.log(myVar);
let myVar = [1];
function myFunc(myVar) {
myVar[0] = 2;
}
myFunc(); // TypeError: Cannot set properties of undefined (setting ‘0’)
console.log(myVar);
What happens with:
let myVar = 1;
function myFunc(myVar) {
myVar = 2;
}
myFunc(myVar);
console.log(myVar);
let myVar = 1;
function myFunc(myVar) {
myVar = 2;
}
myFunc(myVar);
console.log(myVar); // 1
let myVar = [1];
function myFunc(myVar) {
myVar = [2];
}
myFunc();
console.log(myVar);
let myVar = [1];
function myFunc(myVar) {
myVar = [2];
}
myFunc();
console.log(myVar); // [1]
let myVar = [1];
function myFunc(myVar) {
myVar[0] = 2;
}
myFunc(myVar);
console.log(myVar);
let myVar = [1];
function myFunc(myVar) {
myVar[0] = 2;
}
myFunc(myVar);
console.log(myVar); // [2]
What happens if an block’s variable or parameter has the same name as one outside?
The inner one shadows the outer one.
Are Blocks and Function bodies the same thing basically?
Yes but no. Function bodies are not blocks
There are subtle differences that we will see later. But often function similarly.
What will this log to console?
let num = 5;
function myFunc() {
console.log(num);
let num = 10;
}
myFunc();
console.log(num);
Error!
The program sees the num used before it’s called in the function body.
What is logged?
function bar(array) {
return array;
}
let array = [1, 2, 3];
let newArray = bar(array);
console.log(array === newArray);
array.push(4);
console.log(array);
console.log(newArray);
function bar(array) {
return array;
}
let array = [1, 2, 3];
let newArray = bar(array);
console.log(array === newArray); // true (they are same object)
array.push(4);
console.log(array); // [ 1, 2, 3, 4 ]
console.log(newArray); // [ 1, 2, 3, 4 ]
What is logged?
function changeMyWords(words) {
console.log(words);
words = [‘Hi’, ‘Goodbye’];
}
let myWords = [‘Hello’, ‘Goodbye’];
changeMyWords(myWords);
console.log(myWords);
[‘Hello’, ‘Goodbye’]
[‘Hello’, ‘Goodbye’]
What is logged?
let myVar = [1];
function myFunc() {
myVar = [2];
}
myFunc();
console.log(myVar);
let myVar = [1];
function myFunc() {
myVar = [2];
}
myFunc();
console.log(myVar); // [2]
What is logged?
let myVar = [1];
function myFunc(myVar) {
myVar = [2];
}
myFunc(myVar);
console.log(myVar);
let myVar = [1];
function myFunc(myVar) {
myVar = [2];
}
myFunc(myVar);
console.log(myVar); // [1]
What is logged?
let color = ‘purple’;
let colors = [‘red’, ‘green’, ‘blue’];
function addColor(colors, color) {
colors.push(color);
return colors;
}
function removeColor(colors) {
color = colors.pop();
return colors;
}
let newColors = removeColor(colors);
addColor(colors, color);
console.log(newColors);
[‘red’, ‘green’, ‘blue’]
What is logged?
function capitalize() {
return word[0].toUpperCase() + word.slice(1);
}
function exclaim() {
return word += ‘!!!’;
}
let word = ‘hello’;
let capitalizedWord = capitalize(word);
let exclaimedWord = exclaim(capitalizedWord);
console.log(word);
console.log(capitalizedWord);
console.log(exclaimedWord);
hello!!!
Hello
hello!!!
function capitalize(word) {
return word[0].toUpperCase() + word.slice(1);
}
function exclaim(word) {
return word += ‘!!!’;
}
let word = ‘hello’;
let capitalizedWord = capitalize(word);
let exclaimedWord = exclaim(capitalizedWord);
console.log(word);
console.log(capitalizedWord);
console.log(exclaimedWord);
hello
Hello
Hello!!!
Where should constant declarations go in the file?
global constants get defined near the top of the program file, usually just after any require calls.
What’s wrong with this?
words.forEach(word => {
console.log(word);
words.shift();
});
Mutates something as you’re iterating over it:
words.forEach(word => {
console.log(word); // logs: scooby, on, two (in that order)
words.shift();
});
How do you make this look more intentional:
let someVariable;
if (someVariable = getAValueFromSomewhere()) {
console.log(severable);
}
if ((someVariable = getAValueFromSomewhere())) {
console.log(someVariable);
}
If you have a callback function and don’t want to use the parameter, what should you do?
Use an underscore:
names.forEach(_ => {
console.log(‘Got a name!’)
});
What can you do instead of (and why?):
function isInvalidChoice(choice) {
return (!Object.keys(getOptionsAndRules()).includes(choice) &&
!Object.keys(ABBR_OPTIONS).includes(choice)) ||
(!Object.keys(getOptionsAndRules()).includes(ABBR_OPTIONS[choice]) &&
!Object.keys(getOptionsAndRules()).includes(choice));
}
or even
function isInvalidChoice(choice) {
return (isInvalidOption(choice) &&
(isInvalidAbbr(choice) || abbrIsNotInRuleSet(choice)))
}
Probably to make the conditional more readable
function isInvalidChoice(chioce) {
const invalidOpt = isInvalidOption(choice);
const invalidAbbr = isInvaloidAbbr(choice);
const notInRuleSet = abbrIsNotInRuleSet(choice);
return invalidOpt && invalidAbbr || notInRuleSet;
}
If you have functions that mutate objects, what should you do instead? why?
To make sure the reader doesn’t have to go into updateScoreCard
to see that it’s modifying the score.
And to make it easier to make a copy of the object rather than relying on mutating it.
Instead of:
function playTournament(winLimit) {
let scoreCard = {
compWins: 0,
playerWins = 0,
}
updateScoreCard(scoreCard);
}
Do:
function playTournament() {
let scoreCard = {
compWins: 0,
playerWins = 0,
}
scoreCard = getUpdatedScoreCard(scoreCard, results);
}
What are the primitive values. How many?
7
numbers
strings
boolean
undefined
null
BigInt
symbols