Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Js Coding For Beginners

The document provides information on JavaScript objects and arrays. It discusses: - Accessing nested objects and arrays using dot notation and bracket notation - Iterating over objects and arrays - Common object properties like keys, values, and methods like Object.keys() - Modifying objects by adding, updating, and removing properties both destructively and non-destructively - Using functions to modify objects - Setting properties for arrays using bracket notation

Uploaded by

Spence Amhurst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Js Coding For Beginners

The document provides information on JavaScript objects and arrays. It discusses: - Accessing nested objects and arrays using dot notation and bracket notation - Iterating over objects and arrays - Common object properties like keys, values, and methods like Object.keys() - Modifying objects by adding, updating, and removing properties both destructively and non-destructively - Using functions to modify objects - Setting properties for arrays using bracket notation

Uploaded by

Spence Amhurst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

* deprecated

ARRAYS
● Arrays have zero-based indexes

Nested arrays

const letters = ['a', ['b', ['c', ['d', ['e']], 'f']]];

console.log(letters[1]) = // returns [ 'b', [ 'c', [ 'd', [Array] ], 'f' ] ]


console.log(letters[1][1]) = // returns [ 'c', [ 'd', [ 'e' ] ], 'f' ]
console.log(letters[1][1][1]) = // returns [ 'd', [ 'e' ] ]

console.log(letters[1][1][1][1]) = //

RESULT
[e]

Iterating over nested objects and arrays

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]);
}
}

shallowRetrieval(userInfo) // result below

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

RESULT // console.log(key, target[key])


Returns key titles and values

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",
};

Dot notation = wildKeys. "C.R.E.A.M." = ERROR


Bracket notation = wildKeys["C.R.E.A.M.”] = “Tang” ✓
BRACKET NOTATION USED with quotes, symbols, anything non-text

Dynamic access
address["zip" + "Code"] = address[zipCode] = “10004” ✓

const meals = {
breakfast: "Oatmeal",
lunch: "Caesar salad",
dinner: "Chimichangas",
};

let mealName = "lunch";

meals[mealName] = meals[lunch] = “Caesar salad” ✓


COPY ME
>


>

const morningMeal = 'breakfast';


const middayMeal = 'lunch';
const eveningMeal = 'dinner';

✓ square brackets return the [variable] and the key value

const meals = {
[morningMeal]: 'French toast',
[middayMeal]: 'Personal pizza',
[eveningMeal]: 'Fish and chips',
};

console.log(meals) = { breakfast: "French toast", lunch: "Personal pizza", dinner: "Fish


and chips" }

✗ no brackets returns the string instead of the variable…

const meals = {
morningMeal: "French toast",
middayMeal: "Personal pizza",
eveningMeal: "Fish and chips",
};

console.log(meals) = { morningMeal: "French toast", middayMeal: "Personal pizza",


eveningMeal: "Fish and chips" }
Methods

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

✓ this returns the value(s) in key:cheesePlate

console.log(Object.values(wednesdayMenu.cheesePlate)) = [ 'Brie', 'Fontina', 'Provolone' ]

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

✗ this returns “Southwestern”, but isn’t using the Object method

console.log(wednesdayMenu.salad) = “Southwestern”

*Replace an inner-key:value

// Change "Provolone" to "Cheddar"


wednesdayMenu.cheesePlate.hard = "Cheddar";

✓ cheesePlate: { soft: 'Brie', semiSoft: 'Fontina', hard: 'Cheddar', nasty: 'Bleu' },

*Add an inner-key:value

// Add a "nasty" key with the value "Bleu" to cheesePlate


wednesdayMenu.cheesePlate.nasty = "Bleu";

✓ cheesePlate: { soft: 'Brie', semiSoft: 'Fontina', hard: 'Cheddar', nasty: 'Bleu' },

*Add a top-level key:value

// Add a "dessert" key with the value "brownies"


wednesdayMenu.dessert = "brownies";

✓ dessert: 'brownies'

Updated code ✓

{
cheesePlate: { soft: 'Brie', semiSoft: 'Fontina', hard: 'Cheddar', nasty: 'Bleu' },
fries: 'Sweet potato',
salad: 'Southwestern',
dessert: 'brownies'
}
Create a property

// Create key(s) inside `circle` and set values

const circle = {};

Dot notation
circle.radius = 5;

Bracket notation
circle["diameter"] = 10;

circle.circumference = circle.diameter * Math.PI;


✓ 31.41592653589793

circle["area"] = Math.PI * circle.radius ** 2;


✓ 78.53981633974483

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;
}

const tuesdayMenu = destructivelyUpdateObject(mondayMenu, "salad",


"Caesar");

✓ 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;
}

const sundayMenu = nondestructivelyUpdateObject(


tuesdayMenu,
"fries",
"Shoestring"
);

Concise
function nondestructivelyUpdateObject(obj, key, value) {
return {
...obj,
[key]: value,
};
}
const sundayMenu = nondestructivelyUpdateObject(
tuesdayMenu,
"fries",
"Shoestring"
);

console.log(tuesdayMenu.fries)= "Sweet potato"


console.log(sundayMenu.fries = “Shoestring”

Using Functions to Modify

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 employeeUpdateNonDestroy = updateEmployeeWithKeyAndValue (


employee,
"name",
"Sam"
);
Remove a Property

const wednesdayMenu = {
cheesePlate: {
soft: "Brie",
semiSoft: "Fontina",
hard: "Provolone",
},
fries: "Sweet potato",
salad: "Southwestern",
};

delete wednesdayMenu.salad;

✓ wednesdayMenu = { cheesePlate: { soft: "Brie", semiSoft: "Fontina",


hard: "Provolone" }, fries: "Sweet potato" }

CODE
const employee = {
name: "Josh",
streetAddress: "100 Rally Road",
}

Destructive
function destructivelyDeleteFromEmployeeByKey(obj, key, value) {
obj[key] = value;
return obj;
}

const employeeDeleteDestroy = destructivelyDeleteFromEmployeeByKey(


employee,
delete employee.streetAddress
)

Non-destructive
function deleteFromEmployeeByKey(obj, key, value) {
return {
...obj,
[key]: value,
};
}

const employeeDeleteNonDestroy = deleteFromEmployeeByKey (


employee,
delete employee.streetAddress)

✓ console.log(employeeDeleteNonDestroy) = { name: 'Josh', true: undefined }

Setting Properties for Arrays/Objects


const myArray = [2, 3, 5, 7]

myArray["1"] = "Hi";

console.log(myArray) = [2, "Hi", 5, 7]

console.log(myArray["01"]) = "Ho"

console.log(myArray) = [2, "Hi", 5, 7, 01: "Ho"]

console.log(myArray[01]) = "Hi"

console.log(myArray["01"]) = "Ho"

Setting Tables for Arrays


const family = {
mother: {
firstName: "Susan",
lastName: "Doyle",
age: 32,
},
father: {
firstName: "John",
lastName: "Doyle",
age: 33,
},
daughter: {
firstName: "Lily",
lastName: "Doyle",
age: 5,
},
son: {
firstName: "Mike",
lastName: "Doyle",
age: 8,
},
};

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).

for ( [ initialization ]; [ condition ]; [ iteration ]) {

let books =['Eloquent Javascript' , 'Javascript: The Good Parts',


'Learn Javascript VISUALLY', 'You don\'t know js', 'Javascript: The
Definitive Guide']
let oneBook = {
title: 'Eloquent Javascript',
author: 'Marijn Haverbeke',
publisher: 'No Starch Press'
}

for ( [ initialization ]; [ condition ]; [ iteration ]) {


[ loop body ]
}

EVERY STATEMENT IS SEPARATED BY SEMICOLON

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 books =['Eloquent Javascript' , 'Javascript: The Good Parts',


'Learn Javascript VISUALLY', 'You don\'t know js', 'Javascript: The
Definitive Guide']

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]
}

const gifts = ["teddy bear", "drone", "doll"];

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)

Looping vs. Iteration


Looping
● The process of executing a set of statements repeatedly until a condition is met.
● It's great for when we want to do something a specific number of times (for loop) or
unlimited times until the condition is met (while or do while loop)
Iteration
● The process of executing a set of statements once for each element in a collection.
● We can accomplish this with a for loop

FOR loop
let is required because we are incrementing a counter variable
let myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

for (let i = 0; i < myArray.length; i++) {


console.log(myArray[i]);
}

WHILE loop
let is required because we are incrementing a counter variable

let myArray2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

let j = 0;

while (j < myArray2.length) {


console.log(myArray2[j++]);
}

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'];

for (const element of myArray3) {


console.log(element);
}

FOR…OF adding an item

const names = ["bo", "slambo", "greese", "chadliter"];

names.push("abletts");<== Non-dest copy adding item to each iteration

for (const element of names) {


console.log(element);
}

RESULT
bo
slambo
greese
chadliter
abletts

for (const char of 'Hello, world!') {


console.log(char);
}

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',
};

for (const key in address) {


console.log(key);
}

RESULT
street1
street2
city
state
zipCode

FOR…IN accessing object values


● Accessing the object's values is as simple as combining the passed-in key with the
bracket operator

const address = {
street1: '11 Broadway',
street2: '2nd Floor',
city: 'New York',
state: 'NY',
zipCode: "10004"
};

for (const key in address) {


console.log(address[key]);
}

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

for (const key in address) {


console.log(address.key);
}

Without address.key = "Let's have a 'key' key!"

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

const numbers = [1, [2, [4, [5, [6]], 3]]];

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);
}
}

const numbers = [1, [2, [4, [5, [6]], 3]]];

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

You might also like