Basic JS Flashcards
Add JS to your file
<script src="main.js"></script>
define variables
let - variables that can be redefined
const - variables that cannnot be redefined (can be used for arrays and objects, which can be manipulated but not reassigned)
let variables can be declared without being assigned a value
const variables will throw an error if you try to declare them without a value
primitive data types
strings, number, boolean, null, undefined, symbols
check what type a variable is
typeof variableName
check length of string
stringVar.length
this is a property
add variable to strings
using backticks and the ${} syntax -
`This string includes a ${variable}`
change case of string
str.toUpperCase()
str.toLowerCase()
these are string methods
get only part of a string
str.substring(0, 5)
takes the starting index, the index where the substring ends (not inclusive)
combining string methods
str.substring(0, 5).toUpperCase()
split a string into an array
- str.split(‘’) - pushes every letter of the string to an array
- Array.from(‘word’)
- Use the spread operator e.g. const newArr = […myWord]
comments
// single line comment
/* multiple line
comment */
get a specific element from an array
target item via index = arr[2]
add item to end of array
arr.push()
returns new length of array
add item to start of array
arr.unshift()
returns length of new array
remove item from end of array
arr.pop()
returns the element
changes the length of the array
check if something is an array
Array.isArray(someVar)
returns boolean
get index of a certain value
arr.indexOf(‘item’)
returns index
returns -1 if not present
check if item is in an array
arr.includes(‘item’)
returns boolean
merge two or more arrays
- arr1.concat(arr2) returns new array
- Spread Operator [… arr 1, …arr2]
concatenate all items of array into a string
arr.join(‘ ‘)
returns a string where each element is separated by a space
similar to arr.toString(), but this returns a string of items of the array separated by commas with no spaces.
.join() is only a method on arrays
what are objects
collection of data in key value pairs separated by commas
const person = {
firstName: ‘John’,
lastName: ‘Smith’,
address: {
street: ‘50 Main St’,
city: ‘Boston’,
state: ‘MA’
}
access single value in objectq
using dot notation
object.key
e.g. person.firstName