JavaScript tips
javascript bootstrap hugo
Declare JS variables
- var one = 1; (function scoped, available before declaration) (no need to var anymore)
- let two = 2; (block scoped, only available after declaration) (use in loops)
- const three = 3; (block scoped, cannot be changed) (use by default)
Converting between numbers and strings
- parseInt() / parseFloat()
- toString()
Manipulating Arrays
- push and pop - affects end of array eg:
- array.push(values)
- array.pop()
- shift and unshift - affects front of array eg:
- array.shift()
- array.unshift(values)
- concat - joins two arrays to make a new array
Loops in JavaScript
- while
const names = ['Justin','Sarah','Christopher'];
let index = 0;
while (index < names.length) {
const name = names[index];
console.log(name);
index++;
}
- for
const names = ['Justin','Sarah','Christopher'];
for (let index = 0; index < names.length; index++) {
const name = names[index];
console.log(name);
}
- for … of
const names = ['Justin','Sarah','Christopher'];
for (const name of names) {
console.log(name);
}
Function Syntax
function computePrice(cost, discount){
let reduction = cost*discount;
console.log("You saved $"+reduction);
return cost-reduction;
}
JSON Things to know
- Stringify: Serialize Object to JSON
- eg:
let bookJSON = JSON.stringify(book);
// stringify - object input - eg:
let myBooksJSON = JSON.stringify(myBooks);
// stringify - collection inupt
- eg:
- Parse: Deserialize JSON to Object
- examaple:
data = bookJSON;
let parsed = JSON.parse(data);
console.log(parsed);
data = myBooksJSON;
parsed = JSON.parse(data);
console.log(parsed);
console.log("Author of 2nd book: "+parsed[1].author);