udacity lesson 7 : objects

In this example below you will see how to do a udacity lesson 7 : objects with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 120hit, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 120hit ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>udacity lesson 7 : objects</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/120hit/udacity-lesson-7-objects-EwyNqg */
TIP: It’s worth noting that while we can represent real-world objects as JavaScript objects, the analogy does not always hold. This is a good starting place for thinking about the structure and purpose of objects, but as you continue your career as a developer, you’ll find that JavaScript objects can behave wildly different than real objects.
NOTE: typeof is an operator that returns the name of the data type that follows it:

typeof "hello" // returns "string"
typeof true // returns "boolean"
typeof [1, 2, 3] // returns "object" (Arrays are a type of object)
typeof function hello() { } // returns "function"

objects are another form of arrays but inside an object you can add multiple functions and other things in it 

=========quiz= umbrella, ella ella, eh eh eh==============
Directions:
Using the umbrella example from the previous video, see if you can follow the example open() method and create the close() method. It's alright if you have trouble at first! We'll go into more detail later in this lesson.

var umbrella = { 
  color: "pink",
  isOpen: false,
  open: function() { 
    if (umbrella.isOpen === true) {
      return "The umbrella is already opened!";
    } else {
      umbrella.isOpen = true;
      return "Julia opens the umbrella!";
    }
   }
};
TIP: Remember to put all of your object's properties and methods inside curly braces: var myObject = { greeting: "hello", name: "Julia" };. Also, remember that an object is just another data type. Just like how you would put a semicolon after a string variable declaration var myString = "hello";, don't forget to put a semi-colon at the end of your object's declaration.

------------code-------------
/*
 * Programming Quiz: Umbrella (7-1)
 */

var umbrella = {
    color: "pink",
    isOpen: true,
  
    open: function() {
        if (umbrella.isOpen === true) {
            return "The umbrella is already opened!";
        } else {
            umbrella.isOpen = true;
            return "Julia opens the umbrella!";
        }
      
     close: function() {
       if (umbrella.isOpen === false){
           return "The umbrella is already closed!";
           }else{
             umbrella.isOpen = false;
             return "Julia closes the umbrella!";
           }
     }
      
    },
  console.log(umbrella);
  
  ------same code but cleaner----------------------------
  var umbrella = {
  
  color : "pink", 
  isOpen: true,
  
  open : function () {
  if (umbrella.isOpen === true)
  {return "x"};
  else
  {umbrella.isOpen = true;
   return "y"};
                     }
                     
  close : function () {
  if (umbrella.isOpen === false)
  {return "y"};
  else
  {umbrella.isOpen = false;
   return "x"};
                     }
}
console.log(umbrella)

------------
What Went Well
- Your code should have a variable umbrella
- The variable umbrella should be an object
- Your umbrella object should have a color property
- Your umbrella object should have a isOpen property
- Your umbrella object should have an open() method that toggles the value of isOpen
- Your umbrella object should have an close() method that toggles the value of isOpen



=============================objects literal===============================
so objects are form of an array 
----------------------------------------------------------------------------
like objects in real life , an objects has multiple sub ponints in an objects
-------------------------------------------------------------------------
the official name inside the object is called key and value.
---------------------------------------------------------
key and value is seperated by comma, for the next key and value
---------------------------------------------------------------
if you want to return the value you simply input 
---------------------------
var["key"] or var.key
---------------------------
in this example 
person["name"] //Rohit
person.name//Rohit
--------------------------
like for example
------------------------------------------
var person = {
  name : "Rohit",
  age : 22,
  favColor : "Royal Blue",
  parent : "Maya S",
  pet : true
};

----------objects with Methods---------------------
in the top example we only described the basic example 
but we didnt add stuff like what is rohit fav hobbies

inorder to add these methods we add/replace a function with the value

ex

var person = {
  name : "rohit",
  favSport : function()
{return "Rohits favotite hobby is playing soccer";}
};

person.favSport();

---------------udacity explanation------
The syntax you see above is called object-literal notation. There are some important things you need to remember when you're structuring an object literal:

The "key" (representing a property or method name) and its "value" are separated from each other by a colon
The key: value pairs are separated from each other by commas
The entire object is wrapped inside curly braces { }.

--------udacity example-----
What about methods?
The sister object above contains a bunch of properties about my sister, but doesn't really say what my sister does. For instance, let's say my sister likes to paint. You might have a paintPicture() method that returns "Sarah paints a picture!" whenever you call it. The syntax for this is pretty much exactly the same as how you defined the properties of the object. The only difference is, the value in the key:value pair will be a function.

var sister = {
  name: "Sarah",
  age: 23,
  parents: [ "alice", "andy" ],
  siblings: ["julia"],
  favoriteColor: "purple",
  pets: true,
  paintPicture: function() { return "Sarah paints!"; }
};

sister.paintPicture();
Returns: "Sarah paints!"
and you can access the name of my sister by accessing the name property:

sister.name
Returns: "Sarah"

-----some things to look out for objects with key and value---
if you have a key with quotes and a number as the first character as you key and output it with the dot notation then you will get a syntax error because js doesnt like a number being as the first character.

ex
--------------------------
var person = {
  "name": "Rohit",
  "1stPet": " Daisy"
};

person.1stPet;

-----------------
the number being the first character in the key concept works in the bracket notation but not the dot notation
-------------------------------------------------------------------------------------------------------------------

-------other objects key rules you should look out for----------------------
the rule is in the key

you cant add  space nor dashin your key names at all for dot notation

if you want to use multi word keys then you camel casing as we learned in the first chapter
                                
ex
-----------------------------
var person = {
  "fire truck" : " red", //wont work for dot notation
  "fire-truck" : " red", //wont work for dot notation
  "fireTruck" : " red" //works for dot notation
};
     
-----udacity summary--
Objects are one of the most important data structures in JavaScript. Get ready to see them everywhere!

They have properties (information about the object) and methods (functions or capabilities the object has). Objects are an incredibly powerful data type and you will see them all over the place when working with JavaScript, or any other object-oriented programming language.

Object literals, methods, and properties
You can define objects using object-literal notation:

var myObj = { 
  color: "orange",
  shape: "sphere",
  type: "food",
  eat: function() { return "yummy" }
};

myObj.eat(); // method
myObj.color; // property
Naming conventions
Feel free to use upper and lowercase numbers and letters, but don't start your property name with a number. You don't need to wrap the string in quotes! If it's a multi-word property, use camel case. Don't use hyphens in your property names

var richard = {
  "1stSon": true;
  "loves-snow": true;
};

richard.1stSon // error
richard.loves-snow // error


-------------quiz menu items---------
Directions:
Create a breakfast object to represent the following menu item:

The Lumberjack - $9.95
eggs, sausage, toast, hashbrowns, pancakes
The object should contain properties for the name, price, and ingredients.


--code---
/*
 * Programming Quiz: Menu Items (7-2)
 */

// your code goes here
var breakfast = {
    name: "The Lumberjack",
    price: "$9.95",
    ingredients: ["eggs", "sausage", "toast", "hashbrowns", "pancakes"]
};

//man I gotta look out for every character damn
                                
------------quiz bank accounts---
Directions:
Using the given object:

var savingsAccount = {
  balance: 1000,
  interestRatePercent: 1,
  deposit: function addMoney(amount) {
    if (amount > 0) {
      savingsAccount.balance += amount;
    }
  },
  withdraw: function removeMoney(amount) {
    var verifyBalance = savingsAccount.balance - amount;
    if (amount > 0 && verifyBalance >= 0) {
      savingsAccount.balance -= amount;
    }
  }
};
add a printAccountSummary() method that returns the following account message:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

------------------------------------------------Code---
/*
 * Programming Quiz: Bank Accounts 1 (7-3)
 */

var savingsAccount = {
    balance: 1000,
    interestRatePercent: 1,
    deposit: function addMoney(amount) {
        if (amount > 0) {
            savingsAccount.balance += amount;
        }
    },
    withdraw: function removeMoney(amount) {
        var verifyBalance = savingsAccount.balance - amount;
        if (amount > 0 && verifyBalance >= 0) {
            savingsAccount.balance -= amount;
        }
    },
    // your code goes here
    printAccountSummary : function(){
        return "Welcome!\nYour balance is currently $1000 and your interest rate is 1%.";
    }
};

console.log(savingsAccount.printAccountSummary());


---return output of above example code--

savingsAccount.balance;
savingsAccount["balance"];
savingsAccount.withdraw(50);
------------------------------------------------------------------------
[this] key word referes to replacing the [original variable] name for more effcient code

an perfect example would be the above example where the var savingAccount.

inside the object we see

var verifyBalance = savingsAccount.balance - amount;

rather than putting the full var name we can use the [this] keyword to make programmers lives easier by doing this

var verifyBalance = this.balance - amount;

this keyword saves time and headache when for example you have multiple vars with similar names like car 1 and car 2

also if your var gets an error your function doesnt break because you had the this method applied 

-----------------------------my unfinshed code example--------------
/*
 * Programming Quiz: Facebook Friends (7-5)
 */

// your code goes here
var facebookProfile = {
    name: "Rohit",
    friends: 132,
    messages: ["Hi", "bye", "shy"],
    
    postMessage: function (message){
        if(messages > 0){
            messages.push(message);
        }
    },
    
    deleteMessage: function (index){
        this.messages.splice(index,1);
        return this.messages;
    },
    
    addFriend: function(){
        for(var i = 0; i <= 132; i++){
            facebookProfile[i].friends ++;
        }
    },
    
    
    
};

-------------------code example-----------------
 * Programming Quiz: Facebook Friends (7-5)


// your code goes here
var facebookProfile = {
    name: "Rohit",
    friends: 100,
    messages: ["Hi", "bye", "shy"],
    
    postMessage: function (message){
        this.messages.push(message);
        return this.messages;
    },
    
    deleteMessage: function (index){
        this.messages.splice(index,1);
        return this.messages;
    },
    
    addFriend: function(){
       this.friends ++;
       return this.friends;
        
    },
    
    removeFriend: function(){
        this.friends --;
        return this.friends;
    }
};
---------------------------------------------------
var snapchat = {
  snapName : "120ti",
  snapStory: ["today I was hungover"],
  snapFriend: [],
  
  addSnapStory: function(snap){
    this.snapStory.push(snap);
    return this.SnapStory;
  },
  
  sendSnapToFriend: function(snapFriend){
    this.snapFriend.push(snapFriend);
    return this.snapFriend;
  }
};

snapchat.addSnapStory("today I felt different, my neuro plastiscity grew stronger");
snapchat.sendSnapToFriend("Initial D is a old school classic!");

------quiz donuts revisited------
the donuts var has a array of donuts with the type and cost price labled 
print it in the sense of console.log form or print the object function with the proper call function
i mean call the object variables

------------------------------------------------------------------------------------------
/*
 * Programming Quiz: Donuts Revisited (7-6)
 */

var donuts = [
    { type: "Jelly", cost: 1.22 },
    { type: "Chocolate", cost: 2.45 },
    { type: "Cider", cost: 1.59 },
    { type: "Boston Cream", cost: 5.99 }
];
  
//your code  
var printOut = function() {
    donuts.forEach(function(donut) {
        var str = `${donut.type} donuts cost $${donut.cost} each`;
        console.log(str);
    });
};

printOut();

Comments