Js Coding For Beginners
Js Coding For Beginners
ARRAYS
● Arrays have zero-based indexes
Nested arrays
console.log(letters[1][1][1][1]) = //
RESULT
[e]
const userInfo = {
firstName: "Avi",
lastName: "Flombaum",
companyName: "Flatbook Labs",
jobTitle: "Developer Apprentice",
friend1firstName: "Nancy",
friend1lastName: "Burgess",
friend1companyName: "Flatbook Labs",
friend1jobTitle: "Developer Apprentice",
friend2firstName: "Corinna",
friend2lastName: "Jackson",
friend2companyName: "Flatbook Labs",
friend2jobTitle: "Senior Developer",
project1title: "Flatbook",
project1description:
"The premier Flatiron School-based social network in the world.",
project2title: "Scuber",
project2description:
"A burgeoning startup helping busy parents transport their
children to and from all of their activities on scooters.",
};
function shallowRetrieval(target) {
for (const key in target) {
console.log(target[key]);
console.log(key);
console.log(key, target[key]);
}
}
RESULT // console.log(target[key])
Returns key values
Avi
Flombaum
Flatbook Labs
Developer Apprentice
Nancy
Burgess
Flatbook Labs
Developer Apprentice
Corinna
Jackson
Flatbook Labs
Senior Developer
Flatbook
The premier Flatiron School-based social network in the world.
Scuber
A burgeoning startup helping busy parents transport their children to and from all of their
activities on scooters.
RESULT // console.log(key)
Returns key titles
firstName
lastName
companyName
jobTitle
friend1firstName
friend1lastName
friend1companyName
friend1jobTitle
friend2firstName
friend2lastName
friend2companyName
friend2jobTitle
project1title
project1description
project2title
project2description
firstName Avi
lastName Flombaum
companyName Flatbook Labs
jobTitle Developer Apprentice
friend1firstName Nancy
friend1lastName Burgess
friend1companyName Flatbook Labs
friend1jobTitle Developer Apprentice
friend2firstName Corinna
friend2lastName Jackson
friend2companyName Flatbook Labs
friend2jobTitle Senior Developer
project1title Flatbook
project1description The premier Flatiron School-based social network in the world.
project2title Scuber
project2description A burgeoning startup helping busy parents transport their children to and
from all of their activities on scooters.
OBJECTS
● camelCaseEverything
● Start the key with a lowercase letter
● No spaces or punctuation
const address = {
street: {
line1: "11 Broadway",
line2: "2nd Floor",
},
city: "New York",
state: "NY",
zipCode: "10004",
}
console.log(address.street.line1) = 11 Broadway
Dot notation
address.street = { line1: '11 Broadway', line2: '2nd Floor' }
address.city = “New York”
address.street.line2 = “2nd Floor”
Bracket notation
address["street"] = { line1: '11 Broadway', line2: '2nd Floor' }
Address["city"] = “New York”
Address["street"]["line2"] = “2nd Floor”
Nonstandard Keys
const wildKeys = {
"Cash rules everything around me.": "Wu",
"C.R.E.A.M.": "Tang",
"Get the money.": "For",
"$ $ bill, y'all!": "Ever",
};
Dynamic access
address["zip" + "Code"] = address[zipCode] = “10004” ✓
const meals = {
breakfast: "Oatmeal",
lunch: "Caesar salad",
dinner: "Chimichangas",
};
const meals = {
[morningMeal]: 'French toast',
[middayMeal]: 'Personal pizza',
[eveningMeal]: 'Fish and chips',
};
const meals = {
morningMeal: "French toast",
middayMeal: "Personal pizza",
eveningMeal: "Fish and chips",
};
Object.keys()
Object.keys(<-- pass the object as an argument)
const wednesdayMenu = {
cheesePlate: {
soft: "Brie",
semiSoft: "Fontina",
hard: "Provolone",
},
fries: "Sweet potato",
salad: "Southwestern",
};
console.log(Object.keys(wednesdayMenu))
Method Argument
Example 1
Object.keys(wednesdayMenu) = [ 'cheesePlate', 'fries', 'salad' ]
Top-level results only
Example 2
Object.keys(wednesdayMenu.cheesePlate) = [ 'soft', 'semiSoft', 'hard' ]
2nd level results
Object.values()
Object.values(<-- pass the object as an argument)
console.log(Object.values(wednesdayMenu.cheesePlate))
Method Argument
Example 1
Example 2
✗ this returns the ‘values’ within the word “Southwestern” > key:salad
console.log(Object.values(wednesdayMenu.salad)) = ['S', 'o', 'u', 't', 'h', 'w', 'e', 's', 't', 'e', 'r', 'n']
Example 3
console.log(wednesdayMenu.salad) = “Southwestern”
*Replace an inner-key:value
*Add an inner-key:value
✓ dessert: 'brownies'
Updated code ✓
{
cheesePlate: { soft: 'Brie', semiSoft: 'Fontina', hard: 'Cheddar', nasty: 'Bleu' },
fries: 'Sweet potato',
salad: 'Southwestern',
dessert: 'brownies'
}
Create a property
Dot notation
circle.radius = 5;
Bracket notation
circle["diameter"] = 10;
console.log(circle)
✓ { radius: 5, diameter: 10, circumference: 31.41592653589793, area: 78.53981633974483 }
Modify a Property
const mondayMenu = {
cheesePlate: {
soft: "Chèvre",
semiSoft: "Gruyère",
hard: "Manchego",
},
fries: "Sweet potato",
salad: "Cobb",
};
Destructive
Dot notation
mondayMenu.fries = "Sweet potato";
console.log(mondayMenu) =
✓ { cheesePlate: { soft: "Chèvre", semiSoft: "Gruyère", hard:
"Manchego" }, fries: "Sweet potato", salad: "Cobb" }
Bracket notation
function destructivelyUpdateObject(obj, key, value) {
obj[key] = value BRACKET NOTATION USED BECAUSE NON-STANDARD KEY
return obj;
}
✓ console.log(tuesdayMenu) =
{ cheesePlate: { soft: "Chèvre", semiSoft: "Gruyère", hard:
"Manchego" }, fries: "Sweet potato", salad: "Caesar" }
Non-destructive
Verbose
function nondestructivelyUpdateObject(obj, key, value) {
const newObj = { ...obj };
newObj[key] = value;
return newObj;
}
Concise
function nondestructivelyUpdateObject(obj, key, value) {
return {
...obj,
[key]: value,
};
}
const sundayMenu = nondestructivelyUpdateObject(
tuesdayMenu,
"fries",
"Shoestring"
);
Destructive
function destructivelyUpdateEmployeeWithKeyAndValue(obj, key, value) {
obj[key] = value;
return obj;
}
const employeeUpdateDestroy =
destructivelyUpdateEmployeeWithKeyAndValue(
employee,
"streetAddress",
"12 Broadway"
);
Non-destructive
function updateEmployeeWithKeyAndValue(obj, key, value) {
return {
...obj,
[key]: value,
};
}
const wednesdayMenu = {
cheesePlate: {
soft: "Brie",
semiSoft: "Fontina",
hard: "Provolone",
},
fries: "Sweet potato",
salad: "Southwestern",
};
delete wednesdayMenu.salad;
CODE
const employee = {
name: "Josh",
streetAddress: "100 Rally Road",
}
Destructive
function destructivelyDeleteFromEmployeeByKey(obj, key, value) {
obj[key] = value;
return obj;
}
Non-destructive
function deleteFromEmployeeByKey(obj, key, value) {
return {
...obj,
[key]: value,
};
}
myArray["1"] = "Hi";
console.log(myArray["01"]) = "Ho"
console.log(myArray[01]) = "Hi"
console.log(myArray["01"]) = "Ho"
console.table(family) =
Nested Objects
const userInfo = {
firstName: "Avi",
lastName: "Flombaum",
company: {
name: "Flatbook Labs",
jobTitle: "Developer Apprentice",
},
friends: [
{
firstName: "Nancy",
lastName: "Burgess",
company: {
name: "Flatbook Labs",
jobTitle: "Developer Apprentice",
},
},
{
firstName: "Corinna",
lastName: "Jackson",
company: {
name: "Flatbook Labs",
jobTitle: "Lead Developer",
},
},
],
projects: [
{
title: "Flatbook",
description: "The premier Flatiron School-based social network in
the world.",
},
{
title: "Scuber",
description: "A burgeoning startup helping busy parents transport
their children to and from all of their activities on scooters.",
}
]
}
console.log(userInfo.friends[0].company.jobTitle) =
RESULT
Developer Apprentice
LOOPS
FOR loop
Use a for loop when you know how many times you want the loop to run (for example, when
you're looping through elements in an array).
function loopThroughBooks(books){
for(let i = 0; i < books.length; i++){
console.log(books[i])
}
}
loopThroughBooks(books)
OF loop
This iterates through the list of books without having to be told when to stop
let oneBook = {
title: 'Eloquent Javascript',
author: 'Marijn Haverbeke',
publisher: 'No Starch Press'
}
function loopThroughBooks(books){
for (let book of books) {
console.log(book)
}}
loopThroughBooks(books)
IN loop
Used to loop through objects
function loopThroughObject(obj) {
for(let key in obj) {
console.log(obj[key])
// A string can be called using bracket notation
console.log(key)
// returns the key titles but not values
}
}
loopThroughObject(oneBook)
// returns
Eloquent Javascript
Marijn Haverbeke
No Starch Press
loopThroughObject(oneBook)
// returns
title
author
publisher
WHILE loop
function plantGarden() {
let keepWorking = true;
while (keepWorking) { // WHILE keepWorking IS TRUE
chooseSeedLocation();
plantSeed();
waterSeed();
keepWorking = checkForMoreSeeds();
}
}
While ([condition]) {
[loop body]
}
function wrapGifts(gifts) {
let i = 0;
while (i < gifts.length) {
console.log(`Wrapped ${gifts[i]} and added a bow!`);
i++;
}
return gifts;
}
wrapGifts(gifts)
CountDown from 10 to 0
function countdown(i) {
while (i > -1) {
console.log(i);
i--;
}
return i;
}
countdown(10)
FOR loop
let is required because we are incrementing a counter variable
let myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
WHILE loop
let is required because we are incrementing a counter variable
let j = 0;
FOR...OF loop
const is ok we assign the next element in the collection to a new element variable
const myArray3 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
RESULT
bo
slambo
greese
chadliter
abletts
RESULT
H
e
l
l
o
,
w
o
r
l
d
!
FOR…IN loop
For key titles, use (keys) – for key values, use [keys]. Don't use for...in with arrays
● This iterates over the properties in an object, but it doesn't pass the entire property into
the block
● Instead, it only passes in the keys
● Use for…if statement whenever you want to enumerate the properties of an object
const address = {
street1: '11 Broadway',
street2: '2nd Floor',
city: 'New York',
state: 'NY',
zipCode: '10004',
};
RESULT
street1
street2
city
state
zipCode
const address = {
street1: '11 Broadway',
street2: '2nd Floor',
city: 'New York',
state: 'NY',
zipCode: "10004"
};
Dot notation
Don’t use it for this…the dot operator because it treats the variable name as a literal key
address.key = "Let's have a 'key' key!"; // ⇐ without this, address.key will return undefined
RESULT
undefined
With address.key = "Let's have a 'key' key!"
RESULT
Let's have a 'key' key!
Let's have a 'key' key!
Let's have a 'key' key!
Let's have a 'key' key!
Let's have a 'key' key!
Let's have a 'key' key!
RECURSION
A function that calls itself
function deepIterator(target) {
if (typeof target === "object") {
for (const key in target) {
deepIterator(target[key]);
}
} else {
console.log(target);
}
}
// This is an if/then statement. If the target is a kind of “object” (array, etc.), then run deepIterator
RESULT
1
2
4
5
6
3
To get a better look, this code shows both outputs of the if/then statement
function deepIterator(target) {
console.log("Argument: ", target);
if (typeof target === 'object') {
for (const key in target) {
deepIterator(target[key]);
}
} else {
console.log("Logged value: ", target);
}
}
deepIterator(numbers);
RESULT
Argument: [ 1, [ 2, [ 4, [Array], 3 ] ] ]
Argument: 1
Logged value: 1
Argument: [ 2, [ 4, [ 5, [Array] ], 3 ] ]
Argument: 2
Logged value: 2
Argument: [ 4, [ 5, [ 6 ] ], 3 ]
Argument: 4
Logged value: 4
Argument: [ 5, [ 6 ] ]
Argument: 5
Logged value: 5
Argument: [ 6 ]
Argument: 6
Logged value: 6
Argument: 3
Logged value: 3