This Is All Commented Console - Log (10) None of This Is Going To Run! Console - Log (99)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

what is console:

It is the panel that displays important messages, like errors


In java script console keyword refers to an object, a collection
of data and actions, that we can use in out code.
Console.log(); here .log() is a method put anything inside it; will
get printed.

Comment:
/*This is all commented console.log(10);None of this is going to run!
console.log(99);*/
//for single line comment

In JavaScript, there are seven fundamental data types:

 Number: Any number, including numbers with decimals: 4, 8, 1516, 23.42.


 String: Any grouping of characters on your keyboard (letters, numbers, spaces, symbols, etc.)
surrounded by single quotes: ' ... ' or double quotes " ... ". Though we prefer
single quotes. Some people like to think of string as a fancy word for text.
 Boolean: This data type only has two possible values— either true or false (without
quotes). It’s helpful to think of booleans as on and off switches or as the answers to a “yes”
or “no” question.
 Null: This data type represents the intentional absence of a value, and is represented by the
keyword null (without quotes).
 Undefined: This data type is denoted by the keyword undefined (without quotes). It also
represents the absence of a value though it has a different use than null.
 Symbol: A newer feature to the language, symbols are unique identifiers, useful in more
complex coding. No need to worry about these for now.
 Object: Collections of related data.

console.log(22+3.5);
console.log(2020-1969);
console.log(65/240);
console.log(0.2708*100);
console.log('Hello' + 'World');
console.log('Hello'+ ' ' + 'World');
console.log('Teaching the world how to code'.length);
console.log('Codecademy'.toUpperCase());
console.log('    Remove whitespace   '.trim());
console.log(Math.floor(Math.random() * 100));
console.log(Math.ceil(43.8));//returns the smallest integer greater tha
n or equal to a decimal number
console.log(Number.isInteger(2017));//if it is integer or not
var favoriteFood ='pizza';
var numOfSlices=8;
console.log(favoriteFood);
console.log(numOfSlices);

The let keyword signals that the variable can be reassigned a


different value.
let changeMe=true;
changeMe=false;
console.log(changeMe);

const entree='Enchiladas';
console.log(entree);
entree = 'Tacos';

let levelUp = 10;
levelUp+=5;
let powerLevel = 9001;
powerLevel-=100;
let multiplyMe = 32;
multiplyMe*=11;
let quarterMe = 1152;
quarterMe/=4;
let gainedDollar = 3;
gainedDollar++;
let lostDollar = 50;
lostDollar--;

let favoriteAnimal = "giraffe";

console.log("My favorite animal: " + favoriteAnimal);

String Interpolation

let myName = 'Natalia';
let myCity = 'Mexico City';

console.log(`My name is ${myName}. My favorite city is ${myCity}.`)

let newVariable = 'Playing around with typeof.';
console.log(typeof(newVariable));
newVariable=1;
console.log(typeof(newVariable));

let sale = true;
sale = false;

if(sale) {
  console.log('Time to buy!');
}
else{
  console.log('Time to wait for a sale.');
}

 the and operator (&&)


 the or operator (||)
 the not operator, otherwise known as the bang operator (!)

let mood = 'sleepy';
let tirednessLevel = 6;
if(mood==='sleepy' && tirednessLevel>8){
  console.log('time to sleep');
}
else{
  console.log('not bed time yet');
}

Truthy and falsy


let wordCount = 10;

if (wordCount) {
  console.log("Great! You've started your work!");
} else {
  console.log('Better get to work!');
}
let favoritePhrase = '';
if (favoritePhrase) {
  console.log("This string doesn't seem to be empty.");
} else {
  console.log('This string is definitely empty.');
}

Example 2:
let tool = 'marker';

// Use short circuit evaluation to assign  writingUtensil variable belo
w:
let writingUtensil=tool || 'pen';
console.log(`The ${writingUtensil} is mightier than the sword.`);
let tool = 'marker';

// Use short circuit evaluation to assign  writingUtensil variable belo
w:
let writingUtensil=tool || 'pen';
console.log(`The ${writingUtensil} is mightier than the sword.`);

Ternary operator:
let isNightTime = true; isNightTime ? console.log('Turn
if (isNightTime) { on the lights!') :
console.log('Turn on the console.log('Turn off the
lights!'); lights!');
} else {
console.log('Turn off the
lights!');
}

let season = 'summer';

if (season === 'spring') {
  console.log('It\'s spring! The trees are budding!');

else if(season === 'winter'){
  console.log('It\'s winter! Everything is covered in snow.');
}
else if(season === 'fall'){
  console.log('It\'s fall! Leaves are falling!');
}
else if(season==='summer'){
  console.log('It\'s sunny and warm because it\'s summer!');
}
else {
  console.log('Invalid season.');
}

Switch statement;
et athleteFinalPosition = 'first place';
switch(athleteFinalPosition){
  case 'first place':
  console.log('You get the gold medal!');
  break;
  case 'second place':
  console.log('You get the silver medal!');
  break;
  case 'third place':
  console.log('You get the bronze medal!');
  break;
  default:
  console.log('No medal awarded.');
  break;
}

Function:
function getReminder(){
  console.log('Water the plants.');
}
function greetInSpanish(){
  console.log('Buenas Tardes.');
}

Call function:
function sayThanks(){
  console.log('Thank you for your purchase! We appreciate your business
.');
}
sayThanks();
sayThanks();
sayThanks();
Using a parameter;
function sayThanks(name) {
  console.log('Thank you for your purchase '+name+'! We appreciate your 
business.');
}
Default parameters;
function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'egg
s'){
  console.log(`Remember to buy ${item1}`);
  console.log(`Remember to buy ${item2}`);
  console.log(`Remember to buy ${item3}`);
}
Return :
function monitorCount(rows,columns){
  return rows*columns;
}
const numOfMonitors=monitorCount(5,4);
console.log(numOfMonitors);
Helper function
function monitorCount(rows, columns) {
  return rows * columns;
}
function costOfMonitors(rows,columns){
  return monitorCount(rows, columns) *200;
}
const totalCost=costOfMonitors(5,4);
Function expression;
const plantNeedsWater = function(day) {
  if(day === 'Wednesday'){
    return true;
  } else {
    return false;
  }
};

plantNeedsWater('Tuesday');
console.log(plantNeedsWater('Tuesday'));

Arrow function:ES6 introduced arrow function syntax, a shorter way to


write functions by using the special “fat arrow” () => notation.

Arrow functions remove the need to type out the keyword function every time you
need to create a function. Instead, you first include the parameters inside the ( )
and then add an arrow => that points to the function body surrounded in { } like
this:

const rectangleArea = (width, height) => {


let area = width * height;
return area;
};
const plantNeedsWater = (day) => {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};

Concise Body Arrow Functions


JavaScript also provides several ways to refactor arrow function syntax. The most
condensed form of the function is known as concise body. We’ll explore a few of
these techniques below:

1.

Functions that take only a single parameter do not need that parameter to be
enclosed in parentheses. However, if a function takes zero or multiple
parameters, parentheses are required.

2.

const hobbies=['sleep','eat','play
'];
console.log(hobbies);

const famousSayings = ['Fortune favors the brave.', 'A joke is a very s
erious thing.', 'Where there is love there is life.'];
let listItem=famousSayings[0];
console.log(listItem);
console.log(famousSayings[2]);
console.log(famousSayings[3]);
famousSayings[0]=’sleep tight’;
Concise body arrow unctions:
The most condensed form of the function is known as concise body.
Functions that const greaterThanFive = (num) => {
take only a return num > 5 ? true : false;
single parameter };
do not need that const greaterThanFive = num => num > 5 ? true :
parameter to be false;
enclosed in
parentheses.
However, if a
function takes
zero or multiple
parameters,
parentheses are
required.
A function body const plantNeedsWater = day => day === 'Wednesday' 
composed of a ? true : false;
single-line block
;
does not need
curly braces.
Without the curly
braces, whatever
that line
evaluates will be
automatically
returned. The
contents of the
block should
immediately
follow the arrow
=> and the return
keyword can be
removed. This is
referred to as
implicit return

Scope: Scope defines where variables can be accessed or referenced.


While some variables can be accessed from anywhere within a program,
other variables may only be available in a specific context.
Block;used before in function and if statement.
A block is the code found inside a set of curly braces {}. Blocks
help us group one or more statements together and serve as an
important structural marker for our code.
const city = 'New York City';

const logCitySkyline = () => {
  let skyscraper = 'Empire State Building';
  return 'The stars over the ' + skyscraper + ' in ' + city;
};

console.log(logCitySkyline());

In global scope, const satellite = 'The Moon';


variables are const galaxy = 'The Milky Way';
declared outside of
const stars = 'North Star';
blocks. These
variables are called
global variables. const callMyNightSky = () => {
Because global   return 'Night Sky: ' + satellite + ', ' + star
variables are not
bound inside a s + ', and ' + galaxy;
block, they can be };
accessed by any code
in the program, console.log(callMyNightSky());
including code in
blocks.
const color =
'blue';
const returnSkyColor
= () => {
return color; //
blue
};
console.log(returnSk
yColor()); // blue

When a variable is const logVisibleLightWaves = () => {


defined inside a   const lightWaves = 'Moonlight';
block, it is only
  console.log(lightWaves);
accessible to the
code within the };
curly braces {}. We
say that variable logVisibleLightWaves();
has block scope
because it is only // console.log(lightWaves);
accessible to the
lines of code within
that block.
const logSkyColor =
() => {
let color =
'blue';

console.log(color);
// blue
};
logSkyColor(); //
blue
console.log(color);
// ReferenceError

Scope pollution is const satellite = 'The Moon';


when we have too const galaxy = 'The Milky Way';
many global
let stars = 'North Star';
variables that exist
in the global
namespace, or when const callMyNightSky = () => {
we reuse variables   stars = 'Sirius';
across different   return 'Night Sky: ' + satellite + ', ' + star
scopes. Scope
s + ', ' + galaxy;
pollution makes it };
difficult to keep
track of our console.log(callMyNightSky());
different variables console.log(stars);
and sets us up for
potential accidents.
For example,
globally scoped
variables can
collide with other
variables that are
more locally scoped,
causing unexpected
behavior in our
code.
Tightly scoping your const logVisibleLightWaves = () => {
variables will greatly   let lightWaves = 'Moonlight';
improve your code in   let region = 'The Arctic';
several ways:
  // Add if statement here:
 It will make your   if (region === 'The Arctic'){
code more legible     let lightWaves = 'Northern Lights';
since the blocks will
    console.log(lightWaves);
organize your code
into discrete   }
sections.   
 It makes your code
  console.log(lightWaves);
more understandable
since it clarifies which };
variables are
associated with
logVisibleLightWaves();
different parts of the
program rather than
having to keep track
of them line after
line!
 It’s easier to maintain
your code, since your
code will be modular.
 It will save memory
in your code because
it will cease to exist
after the block
finishes running.

 Scope is the idea in programming that some variables are


accessible/inaccessible from other parts of the program.
 Blocks are statements that exist within curly braces {}.
 Global scope refers to the context within which variables
are accessible to every part of the program.
 Global variables are variables that exist within global
scope.
 Block scope refers to the context within which variables
that are accessible only within the block they are defined.
 Local variables are variables that exist within block scope.
 Global namespace is the space in our code that contains
globally scoped information.
 Scope pollution is when too many variables exist in a
namespace or variable names are reused.

Difference between let and const:


let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];
condiments[0]='Mayo';
console.log(condiments);
condiments=['Mayo'];
console.log(condiments);
const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];
utensils[3]='Spoon';
console.log(utensils);
Console.log(utensils.length);

const chores = ['wash dishes', 'do laundry', 'take out trash'];
chores.push('buy medicines','take a nap');
console.log(chores);
const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook di
nner', 'mop floor'];
chores.pop(4);
console.log(chores.pop(4));
Some arrays methods that are available to JavaScript developers
include: .join(), .slice(), .splice(), .shift(), .unshift(), and
.concat()
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown 
rice', 'pasta', 'coconut oil', 'plantains'];
groceryList.shift();//remove first item from array
console.log(groceryList);
groceryList.unshift('popcorn');//begining of grocery list
console.log(groceryList);
console.log(groceryList.slice(1, 4));//add few more
console.log(groceryList);
const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);
//function and array
const concept = ['arrays', 'can', 'be', 'mutated'];

function changeArr(arr){
  arr[3] = 'MUTATED';
}
changeArr(concept);
console.log(concept);
function removeElement(newArr){
  newArr.pop();
}
removeElement(concept);
console.log(concept);

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

const target = numberClusters[2][1];//access 6 as a nested loop

For loop;
// Write your code below
for(let counter=5;counter<11;counter++) {
  console.log(counter);
}
// The loop below loops from 0 to 3. Edit it to loop backwards from 3 t
o 0
for (let counter = 3; counter >= 0; counter--){
  console.log(counter);
}

const vacationSpots = ['Bali', 'Paris', 'Tulum'];

// Write your code below
for(let i=0;i < vacationSpots.length;i++){
  console.log('I would love to visit '+vacationSpots[i]);
}

Work on 3 arrays mutual concept:


// Write your code below
let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin'];
let tinasFollowers = ['Sam', 'Marta', 'Elle'];
let mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
  for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) {
      mutualFollowers.push(bobsFollowers[i]);
    }
  }
};

While loop:
const cards = ['diamond', 'spade', 'heart', 'club'];

// Write your code below
let currentCard;
while(currentCard!='spade'){
  currentCard = cards[Math.floor(Math.random() * 4)];
  console.log(currentCard);
}

Do-while:
// Write your code below
let cupsOfSugarNeeded=2;
let cupsAdded=0;
do{
  cupsAdded++
}
while(cupsAdded<cupsOfSugarNeeded);

const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"];

Break statement example:


// Write you code below
for (let i = 0; i < rapperArray.length; i++){
  console.log(rapperArray[i]);
  if (rapperArray[i] === 'Notorious B.I.G.'){
    break;
  }
}
console.log("And if you don't know, now you know.");
Javascript function behaves like any other data type:

higher-order functions are functions that accept other functions as


arguments and/or return functions as output. This enables us to build
abstractions on other abstractions,

const announceThatIAmDoingImportantWork = () => {


console.log("I’m doing very important work!");
};

What if we wanted to rename this function without sacrificing the source code? We
can re-assign the function to a variable with a suitably short name:

const busy = announceThatIAmDoingImportantWork;


busy(); // This function call barely takes any space!

busy is a variable that holds a reference to our original function. If we could look up
the address in memory of busy and the address in memory of
announceThatIAmDoingImportantWork they would point to the same place. Our
new busy() function can be invoked with parentheses as if that was the name we
originally gave our function.

Notice how we assign announceThatIAmDoingImportantWork without parentheses


as the value to the busy variable. We want to assign the value of the function itself,
not the value it returns when invoked.

Function as a DATA:

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

// Write your code below
const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;
is2p2();
console.log(is2p2.name);

Function behaves as any other type of data in Javascript:


We can also pass function as a para meter.A higher-order function is a
function that either accepts functions as parameters, returns a
function, or both! We call the functions that get passed in as
parameters and invoked callback functions because they get called
during the execution of the higher-order function.

Involking funcrion == adding ()

const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

const addTwo = num => num + 2;

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};
// Write your code below
const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTi
mes);
//Save a variable, time2p2. Assign as its value the result of invoking 
the timeFuncRuntime() function with the checkThatTwoPlusTwoEqualsFourAM
illionTimes() function. 
const checkConsistentOutput = (func, val) => {
    let firstTry = func(val);
    let secondTry = func(val);
    if (firstTry === secondTry) {
        return firstTry
    } else {
        return 'This function returned inconsistent results'
    }
};
checkConsistentOutput(addTwo, 10);
Abstraction allows us to write complicated code in a way that’s easy
to reuse, debug, and understand for human readers
We can work with functions the same way we would any other type of
data including reassigning them to new variables
JavaScript functions are first-class objects, so they have properties
and methods like any object
Functions can be passed into other functions as parameters
A higher-order function is a function that either accepts functions
as parameters, returns a function, or both

1. .forEach()

The first iteration


method that we’re going to learn is .forEach(). Aptly named,
.forEach() will execute the same code for each element of an array.

.forEach() takes an argument of callback function(callback fn passed


as an argument into another fn.)

· .forEach() loops through the array and executes the callback function for each element.
During each execution, the current element is passed as an argument to the callback function.
· The return value for .forEach() will always be undefined.
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits array to log I want to eat a plus the name of ea
ch fruit to the console. For example, I want to eat a mango.
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`))

2. .map():

Similar to .forEach except .map() returns a new array


const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Wha

 numbers is an array of numbers. const numbers =


 bigNumbers will store the return value of calling .map() on [1, 2, 3, 4, 5];
numbers. const bigNumbers =
 numbers.map will iterate through each element in the
numbers.map(number
numbers array and pass the element into the callback
function. => {
 return number * 10 is the code we wish to execute upon return number *
each element in the array. This will save each value from the 10;
numbers array, multiplied by 10, to a new array. });

le', 'octopus', 'rabbit', 'lion', 'dog'];

// Use .map() to create a new array that contains the first character o
f each string in the animals array. Save the new array to a const varia
ble named secretMessage.
const secretMessage=animals.map(animal => {
  return animal[0];
});
console.log(secretMessage.join(''));
const bigNumbers = [100, 200, 300, 400, 500];
// Create the smallNumbers array below to divide all the numbers in big
Numbers by 100
const smallNumbers=bigNumbers.map(num =>{
  return num/100;
});

3. Filter()

Returns an array of elements after filtering out certain elements from original
array..filter() method should return true or false depending on the
element that is passed to it.

const words = ['chair', 'music',  words is an array that contains string


'pillow', 'brick', 'pen', elements.
'door'];  const shortWords = declares a
new variable that will store the returned
const shortWords =
array from invoking .filter().
words.filter(word => {
 The callback function is an arrow
return word.length < 6; function has a single parameter, word.
});
Each element in the words array will be
passed to this function as an argument.
 word.length < 6; is the condition
in the callback function. Any word from
the words array that has fewer than 6
characters will be added to the
shortWords array.

const randomNumbers = [375, 200, 3.14, 7, 13, 852];

// Call .filter() on randomNumbers below
const smallNumbers=randomNumbers.filter(num => {
  return num < 250;
});
const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 
'serene'];
// Call .filter() on favoriteWords below
const longFavoriteWords=favoriteWords.filter(num2 =>{
  return num2.length>7;
})

4. .findIndex():on an array will return the index of the first


element that evaluates to true in the callback function.

const jumbledNums = [123, 25, 78, · const lessThanTen = declares a new


5, 9]; variable that stores the returned index number
const lessThanTen = from invoking .findIndex().
jumbledNums.findIndex(num => { · The callback function is an arrow function
has a single parameter, num. Each element in the
return num < 10;
jumbledNums array will be passed to this
});
function as an argument.
· num < 10; is the condition that elements
are checked against. .findIndex() will return
the index of the first element which evaluates to
true for that condition.
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 
'salamander', 'elephant'];

const foundAnimal = animals.findIndex(animal => {
  return animal === 'elephant';
});
const startsWithS = animals.findIndex(animal => {
  return animal[0] === 's' ? true : false;
});

5. Reduce():

.reduce() method returns a single value after iterating through the


elements of an array, thereby reducing the array.
const numbers = [1, 2, 4, 10]; · summedNums is a variable that stores the
const summedNums = returned value of invoking .reduce() on
numbers.reduce((accumulator, numbers.
currentValue) => { · numbers.reduce() calls the
return accumulator + .reduce() method on the numbers array and
currentValue takes in a callback function as argument.
}) · The callback function has two parameters,
console.log(summedNums) // accumulator and currentValue. The value
Output: 17 of accumulator starts off as the value of the
first element in the array and the
currentValue starts as the second element.
To see the value of accumulator and
currentValue change, review the chart
above.
· As .reduce() iterates through the array,
the return value of the callback function becomes
the accumulator value for the next iteration,
currentValue takes on the value of the
current element in the looping process.

const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue;
}, 10);
console.log(newSum);

Iterator documenatation;
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];

// Something is missing in the method call below
console.log(words.some(word => {
  return word.length < 6;
}));
// Use filter to create a new array
const interestingWords = words.filter((word) => {return word.length > 5
});
// Make sure to uncomment the code below and fix the incorrect code bef
ore running it
console.log(interestingWords.every((word) => {return word.length > 5}))
;

Different types and methods :

const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'D
enver', 'Eskisehir', 'Medellin', 'Yokohama'];

const nums = [1, 50, 75, 200, 350, 525, 1000];

//  Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));

// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);

// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
  return acc + currVal[0]
}, "C");

console.log(word)

// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);

// Choose a method that will return a boolean value
nums.every(num => num < 0);
// OR nums.some(num => num < 0);

· .forEach() is used to execute the same code on every element in an array but does not
change the array and returns undefined.
· .map() executes the same code on every element in an array and returns a new array with the
updated elements.
· .filter() checks every element in an array to see if it meets certain criteria and returns a
new array with the elements that return truthy for the criteria.
· .findIndex() returns the index of the first element of an array which satisfies a condition in
the callback function. It returns -1 if none of the elements in the array satisfies the condition.
· .reduce() iterates through an array and takes the values of the elements and returns a single
value.
· All iterator methods takes a callback function that can be pre-defined, or a function expression,
or an arrow function.

Introduction to objects:
7 fundamental datatypes in javascript; string,number,boolean,null,undefind and
symbol and seventh type objects.

let spaceship = {}; // spaceship is an empty object has key and value

let spaceship = {
'Fuel Type': 'diesel',
color: 'silver'
};
Accessing properties: examples
With the property of dot notation, we let spaceship = {
write the object’s name, followed by dot
operator and then property name(key):   homePlanet: 'Earth',
  color: 'silver',
  'Fuel Type': 'Turbo Fuel',
  numCrew: 5,
let spaceship = {
homePlanet: 'Earth',   flightPath: ['Venus', 'Mars', 'Saturn'
color: 'silver' ]
};spaceship.homePlanet; // };
Returns
'Earth',spaceship.color; //
Returns 'silver', // Write your code below
let crewCount=spaceship.numCrew;
let planetArray=spaceship.flightPath;

Bracket notation: let spaceship = {


[‘A’,’B’][0];//return ‘A’
  'Fuel Type' : 'Turbo Fuel',
  'Active Mission' : true,
let spaceship = {
  homePlanet : 'Earth', 
'Fuel Type': 'Turbo Fuel',
'Active Duty': true,   numCrew: 5
homePlanet: 'Earth',  };
numCrew: 5
};spaceship['Active Duty']; let propName =  'Active Mission';
// Returns
truespaceship['Fuel Type']; // Write your code below
// Returns 'Turbo
Fuel'spaceship['numCrew'];
let isActive = spaceship['Active Mission
// Returns
5spaceship['!!!!!!!!!!!!!!!' '];
]; // Returns undefined
console.log(spaceship[propName]);

let returnAnyProp =
(objectName, propName) =>
objectName[propName];
returnAnyProp(spaceship,
'homePlanet'); // Returns
'Earth'

Objects are mutable; let spaceship = {


  'Fuel Type' : 'Turbo Fuel',
 If the property already exists on
the object, whatever value it   homePlanet : 'Earth',
held before will be replaced with   color: 'silver',
the newly assigned value.
  'Secret Mission' : 'Discover life outs
 If there was no property with
that name, a new property will ide of Earth.'
be added to the object.  
};

// Write your code below
spaceship.color='glorious gold';
spaceship.numEngines=8;
delete spaceship['Secret Mission'];

Methods: let retreatMessage = 'We no longer wish 
When the data stored on an object is a
function we call that a method. to conquer your planet. It is full of do
A property is what an object gs, which we do not care for.';
has, while a method is what
an object does. let alienShip = {
  retreat() {
    console.log(retreatMessage)
  },
  takeOff() {
    console.log('Spim... Borp... Glix... 
Blastoff!')
  }
};
//invoke methods
alienShip.retreat();
alienShip.takeOff();
Nested object let spaceship = {
:Create a variablecapFave
  passengers: [{name: 'Space Dog'}], 
and assign the captain‘s
  telescope: {
favorite food (the element
in the 0th index of her     yearBuilt: 2018,
'favorite foods' array) to     model: "91031-XLT",
it. Make sure to use bracket     focalLength: 2032 
and dot notation to get the   },
value of the food through
  crew: {
nested access (don’t just
copy the value into the     captain: { 
variable!)       name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We 
got this!') },
     'favorite foods': ['cookies', 'cake
s', 'candy', 'spinach'] }
  },
  engine: {
    model: "Nimbus2000"
  },
  nanoelectronics: {
    computer: {
      terabytes: 100,
      monitors: "HD"
    },
    'back-up': {
      battery: "Lithium",
      terabytes: 50
    }
  }
}; 

let capFave = spaceship.crew.captain['fa
vorite foods'][0];

let firstPassenger = spaceship.passenger
s[0];

Object is passed by reference: let spaceship = {


when we pass a variable
  'Fuel Type' : 'Turbo Fuel',
assigned to an object into a
function as an argument, the   homePlanet : 'Earth'
computer interprets the };
parameter name as pointing
to the space in memory // Write your code below
holding that object. As a
//Write a function greenEnergy() that ha
result, functions which
change object properties s an object as a parameter and sets that 
actually mutate the object object’s 'Fuel Type' property to 'avocad
permanently (even when the o oil'
object is assigned to a let greenEnergy = obj => {
const variable).
  obj['Fuel Type'] = 'avocado oil';
const spaceship = {
}
homePlanet : 'Earth',
color : 'silver' //Write a function remotelyDisable() tha
}; t has an object as a parameter and sets 
let paintIt = obj => { (or reassigns) that object’s disabled pr
obj.color = 'glorious operty to true.
gold' let remotelyDisable = obj => {
};
paintIt(spaceship);   obj.disabled = true;
spaceship.color // Returns }
'glorious gold'
greenEnergy(spaceship);

remotelyDisable(spaceship);

console.log(spaceship)

Looping through objects: for..in let spaceship = {


    crew: {
Using for...in, iterate
through the spaceship.crew     captain: { 
object in the code editor         name: 'Lily', 
and console.log() a list of         degree: 'Computer Engineering', 
crew names and degrees in         cheerTeam() { console.log('You g
the following format: '[crew
ot this!') } 
member's name]: [crew
member's degree]',         },
i.e.,'Lily: Computer     'chief officer': { 
Engineering'         name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, 
captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets o
n!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The t
ank is full!') } 
        }
    }
}; 

// Using for...in, iterate through the s
paceship.crew object in the code editor 
and console.log() a list of crew roles a
nd names in the following format: '[crew 
member's role]: [crew member's name]', e
.g.,'chief officer: Dan

for (let crewMember in spaceship.crew) {
  console.log(`${crewMember}: $
{spaceship.crew[crewMember].name}`)
};

for (let crewMember in spaceship.crew) {
  console.log(`$
{spaceship.crew[crewMember].name}: $
{spaceship.crew[crewMember].degree}`)
};

You might also like