Variables, Types, and Collections - 23% Flashcards
array method - .sort
Sorts a-z by default w/no cb.
For numbers, need to pass cb:
For reverse, pass a cb that returns a neg num if the 1st is > the 2nd
ASC - use .sort( (a, b) => a - b)
DES - (or rev alphabetical), use .sort( a, b) => b - a)
array method - .forEach
Pass cb, the fn gets called for every element. Does not modify elements.
array1.forEach(element => console.log(element));
can also pass index (item, index)
array method - .map
Modify elements using a cb.
let modifiedArr = arr.map(function(element){
return element *3;
});
array methods - .pop, .shift
pop - removes last el of array and returns it
shift - removes first el of array and returns it
array methods - .splice, .slice
splice - removing, replacing, or adding els in specified positions. Modifies origin array.
slice - cuts out subset of array and returns it as a shallow copy, orig array is not modified
array methods - .push, .unshift
push - adds el to end of array
unshift - adds el to start of array
array methods - .every
Returns a Boolean value that represents whether all els pass the condition in the cb fn
array methods - .filter
Returns a shallow copy of a subset of the array, with only the els that pass the condition in the cb fn
array methods - .indexOf
Returns the first index at which a given el can be found, or -1
array methods - .reduce
Reduces the array to a single value by applying the cb to each el and passing the return to the next.
Takes cb w/2 args (accumulated val and the current val) and and initial value (0 below):
array1.reduce((acc, current) => acc + current, 0);
array methods - .reverse
Reverses the array in place, returns ref to same array
Data Types (8)
String, Number,
BigInt - create by appending n to a num, for numbers > 2^53-1
Boolean,
Null - nothing, empty, or value unknown
Undefined - variable is declared, but value is not assigned
Object - not primitive, used to store collections of data
Symbol - used to create unique identifiers for objects
Map object
collection of key/value pairs, the keys are unique
Const myMap = new Map( );
myMap.add(‘apple’, ‘red’);
myMap.get(‘apple’) // returns ‘red’
myMap.size( ) // returns 1
myMap.has(‘banana’) // returns false
myMap.delete(‘apple’) // removes apple/red pair from myMap
myMap.clear( ) // removes all pairs from myMap
Map obj v. reg Obj
Map - keys can be any type
Object - keys only strings or symbols
Map - easy to get size
Object - have to keep track manually
Map - iteration is insertion order
for (const [key, value] of myMap)
Set obj
Collection of values, similar to array, except all are unique.
Const mySet = new Set( );
mySet.add(‘orange’);
mySet.has(‘orange’) // returns true
mySet.size( ) // returns 1
mySet.delete(‘orange’) // removes orange from mySet
Can iterate in insertion order:
for (const item of mySet)
Set v Array
Set - can delete by value: mySet.delete(val);
Array - deletion by value is slow: (arr.splice(arr.indexOf(val), 1))
Array - value NaN cannot be found by indexOf
Set - only unique vals, don’t have to keep track of duplicates
Convert b/t Array and Set
Array.from(mySet) // creates array
[…mySet] // creates array
new Set(myArray); // creates set, removes duplicates
var, let, const
var - gets hoisted, can declare w/o initializing, can reassign
let - can declare w/o initializing, can reassign
const - must initialize at declaration, cannot reassign
template literal
Strings declared w/backticks.
- can embed vars/JS in them
- line breaks are respected, no need for \n
escape chars in strings
Use backslash \
string / number conversion
Number(<string here>)
String(<num here>)
Types of Numbers
Integers - whole nums, can be positive or negative
Floating point numbers (floats) - have decimals
NaN (Not a Number): usually the result of an undefined or unrepresentable operation like division by zero.
Infinity: represents mathematical infinity. Can be positive or negative..
BigInt: can store and operate on integers beyond the safe integer limit for Numbers (15 places). e.g. 9007199254740991n
Binary, Octal, and Hexadecimal Numbers: JS supports binary (base 2), octal (base 8), and hexadecimal (base 16) numbers. For example, binary: 0b1010, octal: 0o755, hexadecimal: 0xABC.
In JS all nums are technically stored as 64-bit floating-point numbers, regardless of whether they are integers or decimals. This can lead to some precision issues for very large or very small numbers.
.toFixed(n) - Number method
Rounds a decimal to a specified number of places (n)
% operator
** operator
% = Remainder (or Modulo) - Returns the remainder after you’ve divided the left number by the right
8 % 3 // 2
** = Exponent - raises left num to right power
5 ** 2 // 25
equiv to Math.pow(5, 2)
Increment / Decrement operator
e.g. ++
or --
Can only use these on a var that represents a num, not on a num itself.
Used after the variable, returns the value THEN increments it.
Used before the variable, increments the value THEN returns it
Math obj
Obj built into JS, has properties and methods for mathematical constants and functions.
.floor(), .ceil() - Rounds down/up for the closest whole num
.min(), .max() - Returns the min or max val of a comma separated list of nums as arguments.
.random() - Returns a random number between 0 and 1.
ex: to get a random number less than “max”: Math.floor(Math.random() * max);
Date obj
Has many methods for setting, getting, and manipulating dates. It does not have any properties.
Create a Date obj
const now = new Date( );
Can pass a string in many different forms - differs among engines but all support YYYY-MM-DDTHH:mm:ss.sssZ - only the year, month and day are required.
const xmas = new Date(“2023-12-25”);
const alsoXmas = new Date(2023, 11, 25); - yes 11, since 0 index
Date obj methods
“set” methods,
“get” methods,
“to” - for returning string values from Date objects.
parse and UTC methods, for parsing Date strings.
Ex: xmas.getMonth() returns 11, and xmas.getFullYear() returns 2023.
The getTime and setTime methods are useful for comparing dates, since they return the num of ms since the epoch (1/1/1970)
Type Coercion
Automatic or implicit conversion of values from one data type to another (such as strings to numbers).
const value1 = “5”; // string
const value2 = 9; // num
let sum = value1 + value2;
console.log(sum); // “59”
JS converts 9 to a string automatically.
“9” == 9 // JS finds this true, converts automatically to be same type for the comparison
JS uses Type Coercion to determine truthy and falsy values
Falsy Values
null, undefined, false, NaN, 0 (The Number zero, also including 0.0, 0x0, etc),
-0 (The Number negative zero, also including -0.0, -0x0, etc.),
0n (the BigInt zero, also including 0x0n, etc. Note that there is no BigInt negative zero — the negation of 0n is 0n.),
“” (Empty string value, also including ‘’ and ``.),
document.all (The only falsy object in JavaScript is the built-in document.all)
Truthy Values
examples:
true, { }, [ ], 42, “0”, “false”, new Date( ), -42, 12n, 3.14, -3.14, Infinity, -Infinity
Note that empty objects, empty arrays, the string zero, and the string false, are all truthy.
JSON
JavaScript Object Notation:
A text-based format to represent object syntax, can be used independently from JS.
Mostly used for transmitting data in web applications.
Only properties (no methods).
Double-quotes around keys and values.
JSON / obj conversion
JSON.parse - accepts JSON, returns obj - deserialization
JSON.stringify - accepts obj, returns JSON - serialization
array.flat
myArr.flat( ) - defaults to depth of 1, otherwise provide a number
myArr.flat(2) - flattens to 2 levels.
myArr.flat(Infinity) - flattens all the way.
.trim and .padStart, .padEnd
.trim - removes whitespace from start and end of string
.padStart/.padEnd - takes a number for length, and a char to add
strict mode
JS modules and Classes are already in strict mode.
add “use strict”;
prevents accidentally creating global variables
Number( )
When declared with ‘new’ keyword, creates an obj.
When declared w/o ‘new’, coerces the input to a number or NaN
parseFloat, isInteger
parseFloat can be used by itself (global) or as a method of Number obj.
- converts a num that is represented as a string, into a floating point number.
.isInteger is a method of Number obj, returns boolean
toUTCString, toISOString
Both show time in UTC zone
Date.parse(date)
Takes string date, returns its timestamp
Symbol coercion
Symbol type can’t be implicitly coerced to String, only explicitly.