Skip to content

Instantly share code, notes, and snippets.

@deconstructionalism
Created May 9, 2019 15:06
Show Gist options
  • Select an option

  • Save deconstructionalism/e29c9d42e0a3598bc6c56f205b9f8689 to your computer and use it in GitHub Desktop.

Select an option

Save deconstructionalism/e29c9d42e0a3598bc6c56f205b9f8689 to your computer and use it in GitHub Desktop.
/*
For loop for iteration
without an array
*/
for (let i=0; i<10; i++) {
console.log(i)
}
// 0
// 1
// 2
//...
// 9
/*
For loop for iteration
with an array
*/
const values = [ 0, 23, 56, 67, 100 ]
for (let i=0; i<values.length; i++) {
const value = values[i]
console.log(value)
}
/*
forEach method can be more succinct
*/
// short
values.forEach(value => console.log(value))
// shorter
values.forEach(console.log)
/*
you can only break out of loops
in for loops not forEach
*/
// works
for (let i=0; i<values.length; i++) {
if (i > 2) {
break
}
const value = values[i]
console.log(value)
}
// still goes through each element,
// break does nothing
values.forEach((value, index) => {
if (i > 2) {
break
}
console.log(value)
})
/*
template strings use backticks and
are good for adding in (interpolating)
values in to a string
*/
const name = 'Arjun'
const day = 'Thursday'
const number = 33.4
// good (can include line breaks directly)
`my name is ${name} and the day is ${day},
and my favorite number is ${number}`
// sucks (the '/n' means line break)
'my name is ' + name + ' and the day is ' + day + ',\nand my favorite number is ${number}'
/*
using map on an array returns an array
of the same length where each element
in the original array has been transformed
by whatever logic you want
*/
const data = [
{
name: 'Bethany',
grade: 99
},
{
name: 'Arjun',
grade: 85
},
]
// long-winded way
function makeStudentReports (data) {
const results = []
for(let i=0; i<data.length; i++) {
const item = data[i]
results.push(`${item.name}: ${item.grade}`)
}
return results
}
// using map
function makeStudentReports (data) {
return data.map(item => `${item.name}: ${item.grade}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment