Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

JavaScript

confirm(); -всплывающее окно подтверждения


Пример

prompt(); - всплывающее окно, запрашивающее информацию

Variables
// Here is an example of using the greater than (>) operator.
console.log(15 > 4); // 15 > 4 evaluates to true, so true is printed.

// Fill in with >, <, === so that the following print out true:
console.log("Xiao Hui".length < 122);
console.log("Goody Donaldson".length >= 8);
console.log(8*2 === 16);
Output
true
true
true
true
Decisions, decisions
if statement
if( "myName".length >= 7 ) {
console.log("You have a long name!");
}

if-else statement
if( "myName".length >= 7 ) {
console.log("You have a long name!");
}
else {
console.log("You have a short name!");
Substrings
"some word".substring(x, y)
x is where you start chopping
y is where you finish chopping
Example
“hello”.substring(0,2);
0 1 2 3 4
| | | | |
h e l l o
The letter h is in position 0, the letter e is in position 1, and so on.
Output
he
Example
“Batman”.substring(0,3); - first 3 letters
Output
Bat
“laptop”.substring(3,6); - from 4th to 6th letter
Output
top
Javascript
Lection1. Change variable values
String length: “Emily”.length

Code your own adventure game


confirm(“I am ready to play”); //true

var feedback = prompt("Please rate our game");


if(feedback>8){
console.log("Thank you! We should race at the next concert!");
}
else{
console.log("I\'ll keep practicing coding and racing.");
}

Introduction to functions in JS
Introducing functions
var divideByThree = function (number) {//this line declares a new function and gives it a name (devideByThree)
var val = number / 3;//instructions of function
console.log(val);//can be reused
};
// On line 12, we call the function by name
// Here, it is called 'dividebythree'
// We tell the computer what the number input is (i.e. 6)
// The computer then runs the code inside the function!
divideByThree(6);//6 is the input
Function syntax
Example of function
var sayHello = function(name){// var declares a function, sayHello – name of function; keyword function tells that we make
a function; name – parameter of function
console.log(‘Hello ’+ name);//block of reusable code within {}
};//good practice to put ‘;’ after a block of function
sayHello(“Emily”);//Output: Hello Emily
Example of function

Semi-colon acts like a period in a sentence. It helps the computer know where there are stopping points in the code.

The DRY(Don’t Repeat Yourself) principle


Parameter is a small part, that is might be modified, to use a function
Example
var orangeCost = function(cost){
console.log(cost*5);
}
orangeCost(5);
Output
25

Keyword return
Return keyword gives back the value that comes out of the function. The function runs and when the keyword “return” is
used, function will immediately stop running and return the value, that can be used just like any other value in JS.
Example
// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
return number * 2;//returns a new value multiplied by 2
};

// Call timesTwo here!


var newNumber = timesTwo(17);//calls the function and get a number multiplied by 2
console.log(newNumber);
Output
34

Example
// Define quarter here.
var quarter = function(number){
return number/4;
}

if (quarter(36) % 3 === 0 ) {
console.log("The statement is true");
} else {
console.log("The statement is false");
}
Output
The statement is true

Functions with two parameters


example
var areaBox = function(length,width){
return length*width;
};

example
var perimeterBox = function(length,width){
return length+length+width+width;
};
perimeterBox(3,15);
Output
36

Global and local variables


Scope(область действия, масштаб)
a) global. Variables declared outside a function are accessible anywhere once they have been declared.
Example
var globalVar = “Hello”;//globalVar can be accessed anywhere (also inside the function foo)
var foo = function(){
console.log(globalVar);
};

b) local. Variables defined inside the function, cannot be accessed outside the function
Example
var bar = function(){
var localVar = “Howdy”;//exists only inside the function bar
};
console.log(localVar);//error

Var keyword creates a variable in the current scope, if var is used outside the function, the variable has global scope.
Inside the function – local scope.

Example of code
var my_number = 7; //this has global scope

var timesTwo = function(number) {


var my_number = number * 2;//without keyword var my_number refers to the global variable that has been already
declared over, now var declares new local variable
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")


console.log(my_number);
Output
Inside the function my_number is:
14
Outside the function my_number is:
7

Functions recap
Example of code
var nameString = function (name) {
return "Hi, I am"+" "+name;

};
console.log(nameString("Jenya"));
Output
Hi, I am Jenya

Functions& if/else
Example
var sleepCheck = function(numHours){
if(numHours>=8) return "You\'re getting plenty of sleep! Maybe even too much!";
else return "Get some more shut eye!";
};
console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));
Output
You're getting plenty of sleep! Maybe even too much!
Get some more shut eye!
You're getting plenty of sleep! Maybe even too much!

Game Rock, Paper, Scissors


3 phases of the game
a) user makes a choice
b)computer makes a choice
c)a compare function will determine who wins
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
//console.log("Computer: " + computerChoice);
var compare = function(choice1, choice2){
if(choice1===choice2) return "The result is a tie!";
else if(choice1==="rock"){
if(choice2==="scissors") return "rock wins";
else return "paper wins";
}
else if(choice1==="paper"){
if(choice2==="rock") return "paper wins";
else return "scissors wins";
}
else if(choice1==="scissors"){
if(choice2==="rock") return "rock wins";
else return "scissors wins";
}
};
compare(userChoice, computerChoice);
Output
"The result is a tie!"

Introduction in “For” loops in JS


Example
for(var counter=1;counter<6;counter++){
console.log(counter);
}
Ex 2:
for (var i = 5; i <= 50; i+=5) {
console.log(i);
}
Output
1

50
Ex 3:
for (var i = 10; i >= 0; i--) {
console.log(i);
}
Output
10

0

Arrays and Loops


Arrays store
a.lists of data
b.can store different data types at the same time
c.are ordered so the position of each piece of data is fixed

Examples
var names = [“Mao”, “Gandhi”, “Mandela”];

var sizes = [4,6,3,2,1,9];

var mixed = [34, “candy”, “blue”, 11];

Syntax var arrayName = [data, data, data];

Example of code
var junk = ["Jenya", 'Sveta', 25, 23];
console.log(junk);
Output
[ 'Jenya', 'Sveta', 25, 23 ]

Array positions and access to the data inside the array


The position of things inside the array is fixed.
First element in the array: junkData[0]
Third element: junkData[2]
Example of code
var junkData = ["Eddie Murphy", 49, "peanuts", 31];
console.log(junkData[3]);
Output
31

Loops and arrays


Example of code
var cities = [“Melbourne”, “Amman”, “Helsinki”, “NYC”];//declaring of the array

for(var i=0;i<cities.length;i++){//runs until i<4(4 is the length of array)


console.log(“I would like to visit ”+cities[i]);
}

Search Text for your Name


A program that checks a short block of text for your name; it will check the text for the first letter of the name, then push
(add) the number of characters equal to your name’s length to an array. By inspecting the array, you’ll be able to see if your
name was mentioned.
Example of code
text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";//creating of a text

var myName = "Eric";//name to find


var hits = [];//array

// Look for "E" in the text


for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {
// If we find it, add characters up to
// the length of my name to the array
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

*var text = “Hey, how are you \ // ‘\’ is used when the text is too long, it makes string wrap to the next line
doing? My name is Emily”;
*push() – adds an element to an array

My code
var text = "My name is Jenya, my sister's name is Sveta,\
but Jenya is cooler! Tsss... don't tell it to Sveta=)";
var myName = "Sveta";
var hits = [];
for(var i=0;i<text.length;i++){
if(text[i]==="J"){
for(var j=i;j<(i+myName.length);j++){
hits.push(text[j]);
}
}
}
if(hits.length===0){
console.log("Your name wasn't found!");
}
else{
console.log(hits);
}
Output
[ 'J', 'e', 'n', 'y', 'a', 'J', 'e', 'n', 'y', 'a' ]

Introduction to “While” loops in JS


Example
var coinFace = Math.floor(Math.random() * 2);//создается новая переменная coinFace, равная случайному числу в
диапазоне от 0 до 2 и округленному до целой части
while(coinFace === 0){//пока coinFace равна 0
console.log("Heads! Flipping again...");//на консоль выводится фраза
var coinFace = Math.floor(Math.random() * 2);//переменной снова присваивается случайное число от 0 до

округленное до целой части
}
console.log("Tails! Done flipping.");

General syntax
while(condition){
//do something
}
In JS
1 – true
0 – false
Example 2
var understand = true;

while(understand ){
console.log("I'm learning while loops!");
understand = false;
}
Output
I'm learning while loops!
false

Example 3
var count = 0;
var loop = function(){
while(count<3){
console.log("I'm looping!");
count++;
}
};

loop();
Output
I’m looping!
I’m looping!
I’m looping!
Example 4
var soloLoop = function(){
//Your code goes here!
while(true){
console.log("Looped once!");
break;
}
};

soloLoop();
Output
Looped once!

Example
var call = function(){
while(true){
var name = prompt("What is your name?");
if(name==="Jenya"){
var age = prompt("What is the age?");
if(age===25){
break;
}
else{break;}
}
else if(name === "Sveta"){
var ageSveta = prompt("What is the age?");
if(age===24){break;}
else{break;}
}
else {
break;
}
}
};
for(var i = 0; i<2;i++){
call();
}

Do-while loop
General syntax
do{
//do something
}while(condition);
Example
var loopCondition = false;

do {
console.log("I'm gonna stop looping 'cause my condition is " + loopCondition + "!");//runs at least once
} while (loopCondition);//checks the condition
Output
I'm gonna stop looping 'cause my condition is false!

Example
var getToDaChoppa = function(){
// Write your do/while loop here!
var count = 0;
do{
console.log("Jenya");
count++;
}while(count<3);
};

getToDaChoppa();
Output
Jenya
Jenya
Jenya

Dragon Slayer
Example
var slaying = true;//creating the variable
// A bit of new math magic to calculate the odds
// of hitting the dragon. We'll cover this soon!
var youHit = Math.floor(Math.random() * 2);//choose random number from 0 to 2(2 isn’t included) and floor it, it will be
stored as youHit
var damageThisRound = Math.floor(Math.random() * 5 + 1);//choose random number from 0 to 5, add 1 and floor it, it will
be stored as damageThisRound (from 1 to 5)
var totalDamage = 0;//new variable totalDamage = 0

while (slaying) {
if (youHit) {//if youHit===1
console.log("You hit the dragon and did " + damageThisRound + " damage!");
totalDamage += damageThisRound;//add new damage by each round to the total damage

if (totalDamage >= 4) {
console.log("You did it! You slew the dragon!");
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);//choose again new value for youHit
}
} else {
console.log("The dragon burninates you! You're toast.");
slaying = false;
}
}
Output
You hit the dragon and did 4 damage!
You did it! You slew the dragon!
false

MyGame
var slaying = true;
var youHit = Math.floor(Math.random()*2);
var damageThisRound = Math.floor(Math.random()*5+1);
var totalDamage=0;
while(slaying){
if(youHit){
console.log("Congratulations! You hit the dragon");
totalDamage+=damageThisRound;
if(totalDamage>=4){
console.log("You slew the dragon!");
slaying = false;
}
else{
console.log("Again...");
youHit = Math.floor(Math.random()*2);
}
}
else{
console.log("The Dragon won!");
slaying = false;
}
}
Congratulations! You hit the dragon
Again...
Congratulations! You hit the dragon
Again...
The Dragon won!
false 

More on Control Flow in JS


General condition
if(condition){//do smth}
else if(condition){//do smth}
else{//do smth}

Example
var isEven = function(number) {
// Your code goes here!
if(number%2==0){
return true;
}
else{return false;}
};
isEven(2);
Output
true

More on control flow in JS


NaN – not a number
for example: function isNaN() – defines whether argument is NaN
isNaN(“berry”);//true
isNaN(NaN);//true
isNaN(undefined);//true
isNaN(42);//false
var isEven = function(number) {
// Your code goes here!
if(number%2===0){
return true;
}
else if(isNaN(number)){return "Your argument is not a number at all!"}
else{return false;}
};
console.log(isEven(2));
console.log(isEven("Jenya"));
console.log(isEven("21"));//converts automatically into 21 (number)
Output
true
Your argument is not a number at all!
false

For or while
Example
var call = function(count){
while(count>4)
{
console.log("Count is "+ count);
count--;
}
};
for(var i=0;i<3;i++){
call(i+1);
}

Sneak preview: the switch statement


Example
var lunch = prompt("What do you want for lunch?","Type your lunch choice here");

switch(lunch){
case 'sandwich':
console.log("Sure thing! One sandwich, coming up.");
break;
case 'soup':
console.log("Got it! Tomato's my favorite.");
break;
case 'salad':
console.log("Sounds good! How about a caesar salad?");
break;
case 'pie':
console.log("Pie's not a meal!");
break;
default:
console.log("Huh! I'm not sure what " + lunch + " is. How does a sandwich sound?");
}

General syntax of switch


switch(/*Some expression*/){
case ‘option1’:
//do smth
break;
case ‘option2’:
//do smth
break;
case ‘option3’:
//do smth
break;
default:
//do smth
}

Example
var color = prompt("What's your favorite primary color?","Type your favorite color here");

switch(color) {
case 'red':
console.log("Red's a good color!");
break;
case 'blue':
console.log("That's my favorite color, too!");
break;
//Add your case here!
case 'yellow':
console.log("Yellow is very joyous color!");
break;
default:
console.log("I don't think that's a primary color!");
}
Output
Yellow is very joyous color!

Example 2
var candy = prompt("What's your favorite candy?","Type your favorite candy here.");

switch(candy) {
case 'licorice':
console.log("Gross!");
break;
case 'gum':
console.log("I like gum!");
break;
case 'beets':
console.log("...is that even a candy?");
break;
// Add your code here!
default: console.log("I don't remember such candy");
}

Example 3
var answer = prompt("Add your question here!");

switch(answer) {
case 'What\'s your name?':
console.log("My name is Jenya");
break;
case "How old are you?":
console.log("I am 25");
break;
default: console.log('You ask too many questions!');
// Add your code here!

My Example
var call = function(number){
if(!isNaN(number)){
switch(number){
case 7:
console.log("Calling Kazakstan...");
break;
case 495:
console.lo("Calling Russia...");
break;
case 3:
console.log("Calling France...");
break;
case 48: console.log("Calling Poland...");
break;
default: console.log("Calling somewhere else...");
}
}
else{
console.log("Dialed number doesnt'exist");
}
};
call(48);
call(7);
Output
Calling Poland…
Calling Kazakhstan…

Logical Operators
Example
var iLoveJavaScript = true;
var iLoveLearning = true;

if(iLoveJavaScript && iLoveLearning) {


// if iLoveJavaScript AND iLoveLearning:
console.log("Awesome! Let's keep learning!");
} else if(!(iLoveJavaScript || iLoveLearning)) {
// if NOT iLoveJavaScript OR iLoveLearning:
console.log("Let's see if we can change your mind.");
} else {
console.log("You only like one but not the other? We'll work on it.");
}
Output
Awesome! Let's keep learning!

Example 2
var hungry = true;
var foodHere = true;

var eat = function() {


// Add your if/else statement here!
if(hungry&&foodHere){
return true;
}
else{
return false;
}
};

Example 3
var hungry = true;
var foodHere = true;

var eat = function() {


// Add your if/else statement here!
if(hungry&&foodHere){
return true;
}
else{
return false;
}
};

Example 4
var programming = false;

var happy = function() {


// Add your if/else statement here!
if(!programming){return true;}
else{return false;}
};

Code your own Adventure 2

var troll = prompt("You're walking through the forest, minding your own business, and you run into a troll! Do you FIGHT
him, PAY him, or RUN?").toUpperCase();

switch(troll) {
case 'FIGHT':
var strong = prompt("How courageous! Are you strong (YES or NO)?").toUpperCase();
var smart = prompt("Are you smart?").toUpperCase();
if(strong === 'YES' || smart === 'YES') {
console.log("You only need one of the two! You beat the troll--nice work!");
} else {
console.log("You're not strong OR smart? Well, if you were smarter, you probably wouldn't have tried to fight a troll. You
lose!");
}
break;
case 'PAY':
var money = prompt("All right, we'll pay the troll. Do you have any money (YES or NO)?").toUpperCase();
var dollars = prompt("Is your money in Troll Dollars?").toUpperCase();
if(money === 'YES' && dollars === 'YES') {
console.log("Great! You pay the troll and continue on your merry way.");
} else {
console.log("Dang! This troll only takes Troll Dollars. You get whomped!");
}
break;
case 'RUN':
var fast = prompt("Let's book it! Are you fast (YES or NO)?").toUpperCase();
var headStart = prompt("Did you get a head start?").toUpperCase();
if(fast === 'YES' || headStart === 'YES') {
console.log("You got away--barely! You live to stroll through the forest another day.");
} else {
console.log("You're not fast and you didn't get a head start? You never had a chance! The troll eats you.");
}
break;
default:
console.log("I didn't understand your choice. Hit Run and try again, this time picking FIGHT, PAY, or RUN!");
}

MyExample
ar user = prompt("You are in the office and you're meeting your chef, who is very unpleased. What would you like to
do?","Choose: GREET, HUGG or KISS").toUpperCase();
switch(user){
case'GREET':
var friendly = prompt("Are you friendly?", "Yes/No").toUpperCase();
var cheerful = prompt("Is your greeting cheerful?", "Yes/No").toUpperCase();
if(friendly==="YES"||cheerful==="YES"){console.log("It's enough. Your chef is pleased with your greeting");}
else{console.log("Your chef is confounded, he didn't understand your greeting. Try again!");}
break;
case 'HUGG':
var strong = prompt("Are yout huggs strong?", "Yes/No").toUpperCase();
var goodIntenions = prompt("Are your huggs in all sincerity?", "Yes/No").toUpperCase();
if(strong==="NO"&&goodIntentions==="NO"){
console.log("Your chef is wondered");
}
else{console.log("Your chef is indignant at your impertinent gesture!");}
break;
case 'KISS':
var sick = prompt("Do you have fiber?", "Yes/No").toUpperCase();
if(sick==="Yes"){console.log("Your gesture is excusable, because you're sick, but don't be so bold next time");}
else{console.log("Are you crazy?! Now you must expect to be discharged!!!");}
break;
default:
console.log("Pity! Yo could do something to lighten the mood of your chef");
}

Arrays&Objects in JS
Example
var languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"];
console.log(languages[2]);
console.log(languages.length);
Output
JavaScript
5

var languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"];


for(var i=0;i<languages.length;i++){
console.log(languages[i]);
}
Output
HTML
CSS
JavaScript
Python
Ruby

Arrays of arrays (twoDimensional Arrays)


Example
var twoDimensional = [[1,1],[1,1]];//nesting one array inside other, this array contains 2 rows that each contain two items
MyArray
var newArray = [[25,"Jenya",27],[24,"Sveta",01],[47,"Mama", 16]];

Jagged Arrays
Arrays can contain 3 elements at the 1st row, 1 element at the 2nd row, 2 elements at the 3rd row. They are called jagged
arrays.
Example
var jagged = [["Jenya", "Sveta", 25,24],["Mama", 16,1970],["Papa", "Bordeaux", true], 27];

Objects&functions
Objects(like data: strings, numbers, values or combinations of key-value pairs like arrays (their keys might not only contain
numbers, but also strings or variables)). Using objects we can put our information and the functions that use that
information in the same place.
Example: Object ‘phonebookEntry’ handled data: key name = value “Oxnard Montalvo”, key number = value (555)555-5555
var phonebookEntry = {};//creating of object
phonebookEntry.name = 'Oxnard Montalvo';//naming of object (name is the field of object ‘phonebookEntry’)
phonebookEntry.number = '(555) 555-5555';//field number of object
phonebookEntry.phone = function() {//function of the object phonebookEntry
console.log('Calling ' + this.name + ' at ' + this.number + '...');
};

phonebookEntry.phone();
Output
Calling Oxnard Montalvo at (555) 555-5555...

Object syntax
Object are just collections of information(keys and values) between curly braces.
Example
var myObject={
key: value,
key: value,
key: value
};
My Example
var me = {
name: "Jenya",
age: 25
};
2 ways of creating objects
1) Object literal notations (with curly braces)
Ex:
var myObj = {
type: ‘fancy’;
disposition: ‘sunny’
};
2) Object constructor
var myObj = new Object();
myObj.name = “Charlie”;//adding key to the object (1st way)
myObj[“name”] = “Charlie”;//adding ket to the object (2nd way)
My example
var me = new Object();
me["name"] = "Jenya";
me.age = 25;

My example
var object1 = new Object();
var object2 = new Object();
object1.name = "Jenya";
object1.age = 25;
object2["name"] = "Sveta";
object2["object1"] = object1;
var object3 = {
name: 'Marina',
array: [object1, object2]
};
Output
{"name":"Jenya","age":25}

Heterogeneous arrays
var myArray = [25, true, "Jenya", new Object()];

Multidimensional arrays
Example 1
var aList = [[1,4,7],[2]];

Example 2
var object = {
contry: "Poland",
city: 'Warsaw'
};
var newArray = [["Jenya", "Sveta"],["Mama", 47, 25,24, object]];//2D array (contains 2rows)

Example 3
var myObject = {
name: 'Eduardo',
type: 'Most excellent',
// Add your code here!
interests: ["Football", "JavaScript", 'Programming']
};

Example 4
var myOwnObject = {
name: "Jenya",
age: 25,
city: 'Warsaw'
};
myOwnObject.profession = 'Software developer';
myOwnObject["salary"] = "100000 $";
console.log(myOwnObject);
Output
{ name: 'Jenya',
age: 25,
city: 'Warsaw',
profession: 'Software developer',
salary: '100000 $' }

Contact List
Code of application
var friends = {};//creating of new object
friends.bill = {//adding new key to the object ‘friends’
firstName: "Bill",//this field’s value contains other keys (value is like object)
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {//new key with new value like object
firstName: "Steve",
lastName: "Jobs",
number: "(408) 555-5555",
address: ['1 Infinite Loop','Cupertino','CA','95014']
};

var list = function(obj) {//creating new function with argument obj


for(var prop in obj) {//for all variables prop in obj
console.log(prop);//printing this variable prop (keys of friends)
}
};

var search = function(name) {//new function with argument name


for(var prop in friends) {//for all variables prop in friends
if(friends[prop].firstName === name) {//if the firstName of this variable prop is equal to name
console.log(friends[prop]);//printing this prop
return friends[prop];
}
}
};

list(friends);//bill, steve
search("Steve");
Output
bill
steve
{ firstName: 'Steve',
lastName: 'Jobs',
number: '(408) 555-5555',
address: [ '1 Infinite Loop', 'Cupertino', 'CA', '95014' ] }
{"firstName":"Steve","lastName":"Jobs","number":"(408) 555-5555","address":["1 Infinite Loop","Cupertino","CA","95014"]}

Syntax of for/in loops


for(var key in object){//key may be any placeholder name, it’s sort of like when you put a placeholder parameter name in a
function that takes argument
//access that key’s value
//with object[key]
}
My Example
var friends = new Object();
friends.bill = {
firstName: "Sveta",
lastName: "Lee",
number: +7747086547,
address: ["Poland","Warsaw"]
};
friends.steve = {
firstName: "Marina",
lastName: "Li",
number: "+7(7252)310795",
address: ["Kazakhstan","Shymkent"]
};
var list = function(obj){
for(var key in obj){
console.log(key);
}
};
var search = function(name){
for(var key in friends){
if(friends[key].firstName===name){
console.log(friends[key]);
return friends[key];
}
}
};
list(friends);
search("Sveta");
search("Marina");
Output
bill//result of the list function
steve//result of the list function
{ firstName: 'Sveta',//result of the search function(“Sveta”)
lastName: 'Lee',
number: 7747086547,
address: [ 'Poland', 'Warsaw' ] }
{ firstName: 'Marina',//result of the search(“Marina”) function
lastName: 'Li',
number: '+7(7252)310795',
address: [ 'Kazakhstan', 'Shymkent' ] }
{"firstName":"Marina","lastName":"Li","number":"+7(7252)310795","address":["Kazakhstan","Shymkent"]}

Introduction to objects I
Example
for(var i=1;i<21;i++){
if(i%15===0) console.log("FizzBuzz");
else if(i%3===0) console.log("Fizz");
else if(i%5===0) console.log("Buzz");
else console.log(i);
}
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

var getReview = function (movie) {


switch(movie){
case "Toy Story 2": return "Great story. Mean prospector.";
break;
case 'Finding Nemo': return "Cool animation, and funny turtles."
break;
case "The Lion King": return 'Great songs.';
break;
}
};
getReview("Finding Nemo");
Output
Cool animation, and funny turtles.

Introduction to objects I
Declaration of the object (literal notation):
var obj = {
//information inside (each information is known as property)
};

Properties (like category label that belongs to some object).


When creating an object, each property has a name, followed by : and then the value.
More than one properties are separated with commas, the last property doesn’t end with comma.
Ex:
var Spencer = {
age:22,
country: “United States”
};

Example 2
var bob = {
name: “Bob Smith”,
age: 30
};

var susan = {
name: “Susan Jordan”,
age: 25
};

var name1 = bob.name;//saving of bob’s name (“Bob Smith”) into the global variable name1
var age1 = bob.age; //dot notation
Dot notation syntax
1st way to access a property
ObjectName.PropertyName (ex. bob.name)
Bracket notation
2nd way to access a property
ObjectName[“PropertyName”]
Ex. var name1 = bob[“name”];

Example of the code


var dog = {
species: “greyhound”,
weight: 60,
age:4
};

var species = dog[“species”];//accessing a property by the bracket notation

Creating an object with keyword new and constructor.


Syntax of constructor notation
var obj = new Object();
Filling this object with properties and labels
obj.name = “property”;

Example
var susan1 = {
name: “Susan Jordan”,
age: 24
};

var susan2 = new Object();


susan2.name = susan1.name;
susan2.age = 24;

Ex:
//literal notation
var snoopy = {
species: "beagle",
age:10
};
//constructor notation
var buddy = new Object();
buddy.species = "golden retriever";
buddy.age = 5;

Example
var bicycle = {
speed: 0,
gear: 1,
frame_material: "carbon fiber"
};

Function review
Example
// Accepts a number x as input and returns its square
var square = function (x) {
return x * x;
};

// Write the function multiply below


// It should take two parameters and return the product
var multiply = function(x,y){
return x*y;
};
multiply(10,4);
Output 40

Methods is like a function associated with a object.


Purposes of the methods
1) To change properties of the object
2) To make calculations based on the objects’ properties
Example
var bob = new Object();
bob.name = “Bob Smith”;
bob.age = 30;
bob.setAge = function(newAge){//defining a method
bob.age = newAge;
};
bob.setAge(40);//calling the function
Syntax of the method calling
ObjectName.methodName()
Example: using of the methods to update properties of the object and make calculatios
var bob = new Object();
bob.name = “Bob Smith”;
bob.age = 30;
bob.setAge = function(newAge){
bob.age = newAge;
};
bob.getYearOfBirth = function(){
return 2014 – bob.age;
};
console.log(bob.getYearOfBirth());
Output
1997

The keyword “this”


Makes a method work for many other objects (not only his own object).
The keyword this acts as a placeholder and refers to whichever object called this method. It is not limited to a single object,
thus we can reuse the same method for many objects.
Example
var setAge = function(newAge){
this.age = newAge;//will change the age of any object that calls it
};
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;//use the method that was already declared above, it means, whenever we type bob.setAge(),
this.age in the setAge will refer to bob.age.
bob.setAge(50);
var natasha = {
age: 25,
name: "Natasha"
};
natasha.age = setAge;//we can access a function setAge to the method of the object with any name
console.log(bob.age);
natasha.age(20);//we can also name a method of the object the same as a variable
console.log(natasha.age);
Output
50
20

Example2
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;

// make susan here, and first give her an age of 25


var susan = {
age:25,
setAge : setAge//accessing a function setAge to the method setAge of the object susan
};
susan.setAge(35);

Example3
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
rectangle.setHeight = function(newHeight){
this.height = newHeight;//updates rectangle’s height to the given parameter,
but in this case this placeholder refers only to rectangle
};
rectangle.setWidth = function(newWidth){
this.(rectangle.)width = newWidth;
};
rectangle.setWidth(8);
console.log(rectangle.width);//Output 8
rectangle.setWidth(8);
rectangle.setHeight(6);

Example 4
var square = new Object();
square.sideLength =6;
square.calcPerimeter = function(){//new method
return this.sideLength*4;
};
square.calcArea = function(){
if(this.sideLength!==0)
return Math.pow(this.sideLength,2);
else
return 0;
};

var p = square.calcPerimeter();
var a = square.calcArea();
console.log(p);
console.log(a);
Output
24
36

The Object Constructor


var bob = new Object();//using built-in constructor called Object (already define by JS and makes object without
properties&methods)
bob.name = “Bob Smith”;
bob.age = 20;

Custom Constructor
(Creation own constructor, setting properties for an object right when it is created)
Example
function Person(name,age){//constructor with its already created properties
this.name = name;//this constructor is used to create Person objects
this.age = age;
}
var bob = new Person(“Bob Smith”,30);//creation new object (Person)
var susan = new Person(“Susan Jordan”, 25);//with ready properties
var George = new Person(“George Washington”, 275);

Example: creation own constructors


function Cat(age, color) {
this.age = age;
this.color = color;
}

// make a Dog constructor here


function Dog(age,name,breed){
this.age = age;
this.name = name;
this.breed = breed;
}
Example: we don’t need to define all properties using parameters
function Person (name,age){
this.name = name;
this.age = age;
this.species = “Homo Sapiens”;//by creating any Person, his species will be “Homo Sapiens”
}

var sally = new Person("Sally Bowles");


var holden = new Person("Holden Caulfield");
console.log("sally's species is " + sally.species + " and she is " + sally.age );
console.log("holden's species is " + holden.species + " and he is " );
Output
sally's species is Homo Sapiens and she is undefined
holden's species is Homo Sapiens and he is

Constructors with methods


Constructor can have defining properties and methods
Example
function Rectangle(height, width) {
this.height = height;
this.width = width;
this.calcArea = function() {
return this.height * this.width;
};
// put our perimeter function here!
this.calcPerimeter = function(){
return 2*(height+width);
}
}

var rex = new Rectangle(7,3);


var area = rex.calcArea();
var perimeter = rex.calcPerimeter();
console.log(area);
console.log(perimeter);
Output
21
20

Example
function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}

// now we can easily make all of our rabbits


var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");
rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();
Output
I am a fluffy rabbit
I am a happy rabbit
I am a sleepy rabbit

Arrays of Objects
Example
// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}

// Now we can make an array of people


var family = new Array();//creating an empty array
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
// add the last family member, "timmy", who is 6 years old
family[3] = new Person("timmy",6);

Loop through an array of objects


// Our Person constructor
function Person(age,name){
this.age = age;
this.name = name;
}

// Now we can make an array of people


var family = [new Person(25,"Jenya"), new Person(24,"Sveta"), new Person(47, "Marina")];
console.log(family[0].name);
Output
Jenya

Example
// Our Person constructor
function Person(name,age){
this.age = age;
this.name = name;
}

// Now we can make an array of people


var family = new Array();
var alice = new Person("alice", 40);
family[0]=alice;
var bob = new Person("bob",42);
family[1]=bob;
var michelle = new Person("michelle",8);
family[2]=michelle;
family[3]=new Person("timmy",6);
// loop through our new array
for(var i=0;i<4;i++){
console.log(family[i].name);
}
Output
alice
bob
michelle
timmy

Passing Objects into Functions


Using objects as parameters for function
Example
// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}

// We can make a function which takes persons as arguments


// This one computes the difference in ages between two people
var ageDifference = function(person1, person2) {//takes advantage of methods and properties that a certain object type
provides
return person1.age - person2.age;
}

var alice = new Person("Alice", 30);


var billy = new Person("Billy", 25);
// get the difference in age between alice and billy using our function
var diff = ageDifference(alice,billy);//we could not pass anything but Person objects into the method
console.log(diff);
Output
5

Example
// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}

// We can make a function which takes persons as arguments


// This one computes the difference in ages between two people
var ageDifference = function(person1, person2) {
return person1.age - person2.age;
};

// Make a new function, olderAge, to return the age of


// the older of two people
var olderAge = function(person1,person2){
var age1 = person1.age;
var age2 = person2.age;
if(age1>age2) return age1;
return age2;
};

// Let's bring back alice and billy to test our new function
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);

console.log("The older person is " + olderAge(alice, billy));


Output
The older person is 30
Literal & Constructor Notation of the object
var spencer = {
age: 22,
country: "United States"
};

// make spencer2 here with constructor notation


var spencer2 = new Object();
spencer2.age = spencer.age;
spencer2.country = "United States";

Properties
Properties are like variables that belong to the object and are used to hold pieces of information. Properties’ accessing in 2
ways:
1) Dot notation
ObjectName.propertyName
2) Bracket notation
ObjectName[“PropertyName”]

Example
var snoopy = new Object();
snoopy.species = "beagle";
snoopy.age = 10;

// save Snoopy's age and species into variables


// use dot notation for snoopy's species
var species = snoopy.species;

// use bracket notation for snoopy's age


var age = snoopy["age"];

Example: customizing constructor


// 3 lines required to make harry_potter
var harry_potter = new Object();
harry_potter.pages = 350;
harry_potter.author = "J.K. Rowling";

// A custom constructor for book


function Book (pages, author) {
this.pages = pages;
this.author = author;
}

var the_hobbit = new Book(320,"J.R.R. Tolkien");


// Use our new constructor to make the_hobbit in one line

Methods(like functions but associated with object)


Useful to update the object properties, calculate something based on an object’s properties
Example
function Circle (radius) {
this.radius = radius;
this.area = function () {
return Math.PI * this.radius * this.radius;

};
// define a perimeter method here
this.perimeter = function(){
return 2*Math.PI*this.radius;
};
}

Building an address book


var bob = {//information stored in an associative array
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-777",
email: "bob.jones@example.com"
};

console.log(bob.firstName);
console.log(bob.lastName);
console.log(bob.email);
Output
Bob
Jones
bob.jones@example.com

Example
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

var contacts = new Array();


contacts[0] = bob;
contacts[1] = mary;
console.log(contacts[1].phoneNumber);
Output
(650) 888-8888

Constructor syntax
function constructorName(parameters){
this.parameter = parameter;
}

Function syntax
var functionName = function(argument){
//do smth
};

Example
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

// printPerson added here


var printPerson = function(person){
console.log(person.firstName+" "+person.lastName);
};

function list(){
var contactsLength = contacts.length;
for(var i=0;i<contactsLength;i++){
printPerson(contacts[i]);
}
Output
Bob Jones
Mary Johnson

Example: Searching someone special with “linear search”


var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}

/*Create a search function


then call it passing "Jones"*/
function search(lastName){
var contactsLength = contacts.length;
for(var i=0;i<contactsLength;i++){
if(contacts[i].lastName===lastName){
printPerson(contacts[i]);
}
}
}
search("Jones");
Output
Bob Jones

//adding new object to array in a succinct way without direct naming


contacts[contacts.length] = {
lastName: “lastName”,
firstName: “firstName”,
phoneNumber: “phoneNumber”,
email: “email”
};

Final code
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}

/*Create a search function


then call it passing "Jones"*/
function search(lastName){
var contactsLength = contacts.length;
for(var i=0;i<contactsLength;i++){
if(contacts[i].lastName===lastName){
printPerson(contacts[i]);
}
}
}
search("Jones");

function add(firstName, lastName, phoneNumber, email){


contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
};
}
add("Jenya","Li","310795","jenya@example.com");
list();
Output
Bob Jones
Bob Jones
Mary Johnson
Jenya Li
Introduction to Objects II
Object review
Example: literal and constructor notation
var james = {
// add properties to this object!
job: "programmer",
married: false
};

function Person(job, married) {


this.job = job;
this.married = married;
}

// create a "gabby" object using the Person constructor!


var gabby = new Person("student", true);

Functions and methods(functions associated with objects) review


Syntax of method declared in constructor
function nameOfSomeObject(){
this.nameOfSomeMethod = function(){};
}

Example
function Person(job, married) {
this.job = job;
this.married = married;
// add a "speak" method to Person!
this.speak = function (){//adding method to object via constructor notation
console.log("Hello!");
};
}

var user = new Person("Codecademy Student",false);


user.speak();
Output
Hello!

Literally Speaking
Literal notation of the method for object
Syntax
var nameOfSomeObj = {
aPropert: value,
nameOfSomeMethod: function(some, params){ }
};

Example
var jones = {//declaring of a new object
job: “programmer”,
married: false,
speak: function(word) {
console.log("Hello, I am feeling "+word);
}
};

james.speak(“great”);//calling the function


james.speak(“just okay”);

Output
Hello, I am feeling great
Hello, I am feeling just okay

Example: taking references of the object inside the method


var james = {
job: "programmer",
married: false,
sayJob: function() {
// complete this method
console.log("Hi, I work as a "+ this.job);
}
};

// james' first job


james.sayJob();

// change james' job to "super programmer" here


james.job = "super programmer";//accessing new property to an object

// james' second job


james.sayJob();
Output
Hi, I work as a programmer
Hi, I work as a super programmer

Property notation
Dot notation
someObj.someProperty
Bracket notation
someObj[“someProperty”]//we’re not restricted to just using strings in the brackets but also variables, whose values are
property names
Example
var someObj={//creating new Object
propName: someValue
};

var myProperty = “someProperty”;//creating new variable with value


someObj[myProperty];//accesing new property (declared above variable) to someObj, the same as
someObj[“someProperty”];

Properties by bracket notation


var james = {//creating an object by literal notation
job: "programmer",
married: false
};

// set to the first property name of "james"


var aProperty = 'hisJob';//creating a variable with value that is name of the property (aProperty is only the key!!! the name
of property is ‘hisJob’!!!)

// print the value of the first property of "james"


// using the variable "aProperty"
james[aProperty] = james.job;//accessing a value to variable, that contains the name of the property (hisJob)
console.log(james.hisJob);//logging the value of the property by using ‘hisJob’ – name of the property
Output
programmer

Type of the objects


Syntax
var someObject = {someProperty:someValue};//creating an object by literal notation
console.log(typeof someObj);//Output: object
Example
// complete these definitions so that they will have
// the appropriate types
var anObj = { job: "I'm an object!" };
var aNumber = 42;
var aString = "I'm a string!";

console.log( typeof anObj ); // should print "object"


console.log( typeof aNumber ); // should print "number"
console.log( typeof anObj.job ); // should print "string"

Method
hasOwnProperty(someProperty) – lets to know if an object has a particular property (returns true/false)
Example 1
var myObj = {
// finish myObj
name:'Jenya',
};

console.log( myObj.hasOwnProperty('name') ); // should print true


console.log( myObj.hasOwnProperty('nickname') ); // should print false
Output
true
false
Example 2
var suitcase = {
shirt: "Hawaiian"
};

//console.log(suitcase.shorts);
if(suitcase.hasOwnProperty('shorts')){//checking whether an object contains a ‘shorts’ property
console.log(suitcase.shorts);
}
else{//if not
suitcase.shorts = 'Red shorts';//creating a property and accessing a value to it
console.log(suitcase.shorts);//printing this property
}
Output
Red shorts

Working with properties of the object


Example
var dog = {
species: “bulldog”,
age: 3,
color: brown
};

for(var property in dog){//for all properties in the object ‘dog’


console.log(property);//printing them all (only keys!!! not values)
}

Output
species
age
color
Example
var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};
for(var p in nyc){
console.log(p);
}
Output
fullName
mayor
population
boroughs
Example: running through values of the object
var dog = {
species: “bulldog”,
age: 3,
color: brown
};
//dog.species = dog[“species”] = “bulldog”;
//var x = “species”;//by assigning a property name to variable
//dog[x]= “bulldog”;//we can use the variable name in bracket notation to get the property’s value
//to get values of dog object we use for-in loop and bracket notation
for(var p in dog){
console.log(dog[p]);
}
Output
bulldog
3
brown
Example
var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

// write a for-in loop to print the value of nyc's properties


for(var p in nyc){
console.log(nyc[p]);
}
New York City
Bill de Blasio
8000000
5

Class is in Session (basics of OOP – object oriented programming)


Constructor is not only the way to make objects, but also actually defining a new class. A class can be thought as a type or a
category of objects – kind of like how Number or String are types in Javascript
Example
function Person(name,age){//creating new class with constructor
this.name = name;
this.age = age;
}
var bob = new Person(“Bob Smith”, 30);//two new objects of Person type
var susan = new Person(“Susan Jordan”, 35);//two separate objects
// make your own class here
function Circle(radius){//new class may contain certain properties and methods
this.radius = radius;
}

Prototype
Prototype keeps a track of what a given class can or can’t do, or what a class has or doesn’t have. JS defines automatically
the prototype of class with constructor
Как правило, свойство prototype используется для предоставления базового набора функциональных
возможностей классу объектов. Новые экземпляры объекта "наследуют" поведение прототипа,
присвоенного этому объекту.
Example
function Dog(breed){//Dog constructor ensures that the Dog prototype has a breed property
this.breed = breed;
}

var buddy = new Dog(“Golden Retriever”);


buddy.bark = function(){//adding a new method to buddy
console.log(“Woof!”);
}
buddy.bark();//Woof!

//another object
var snoopy = new Dog(“Beagle”);
snoopy.bark();//causes an error, because only buddy has a method bark()!
Output
Woof
TypeError: snoopy.bark is not a function
//but if we assign a new function to snoopy
snoopy.bark = buddy.bark; or snoopy.bark = buddy[“bark”];
Output
Woof
Woof
Example
function Person(name,age) {
this.name = name;
this.age = age;
}
// a function that prints the name of any given person
var printPersonName = function (p) {
console.log(p.name);
};

var bob = new Person("Bob Smith", 30);


printPersonName(bob);
// make a person called me with your name and age
// then use printPersonName to print your name
var me = new Person("Jenya", 25);
printPersonName(me);
Output
Bob Smith
Jenya

Adding method to a class(to all objects of a class)


Example
Syntax
SomeClass.prototype.someMethod= function(){};

function Dog (breed) {


this.breed = breed;
};

// here we make buddy and teach him how to bark


var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() {//now both objects of Dog class: buddy and snoopy know this method
console.log("Woof");
};
buddy.bark();
// here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();
Example: Prototype Practice
function Cat(name, breed) {
this.name = name;
this.breed = breed;
}

// let's make some cats!


var cheshire = new Cat("Cheshire Cat", "British Shorthair");
var gary = new Cat("Gary", "Domestic Shorthair");

// add a method "meow" to the Cat class that will allow


// all cats to print "Meow!" to the console
Cat.prototype.meow = function(){console.log("Meow!");};
cheshire.meow();
gary.meow();
Output
Meow!
Meow!

Inheritance in JS
Inheritance allows one class to see and use methods and properties of another class
Example

// create your Animal class here


function Animal(name,numLegs){
this.name = name;
this.numLegs = numLegs;
}

// create the sayName method for Animal


Animal.prototype.sayName = function(){
console.log("Hi my name is "+this.name);
};

// provided code to test above constructor and method


var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

Output
Hi my name is Captain Cook

Example: creating a new class


function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};

// create a Penguin constructor here


function Penguin(name,numLegs){
this.name = name;
this.numLegs = numLegs;
}

// create a sayName method for Penguins here


Penguin.prototype.sayName = function(){
console.log("Hi my name is "+ this.name);
};

// our test code


var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();
Output
Hi my name is Captain Cook

* DRY principle of programming – Don’t Repeat Yourself


Example: setting Penguin’s prototype be an Animal (inheritance)
Syntax
inheritedClass.prototype = new parentClass();
Example
// the original Animal class and sayName method
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};

// define a Penguin class


function Penguin(name){
this.name = name;
this.numLegs = 2;
}

// set its prototype to be a new instance of Animal


Penguin.prototype = new Animal();//this means a Penguin inherits an Animal
var penguin = new Penguin("Rokki");
penguin.sayName();//now Penguin class know also a method sayName
Output
Hi my name is Den
 

Example
function Penguin(name) {
this.name = name;
this.numLegs = 2;
}

// create your Emperor class here and make it inherit from Penguin
function Emperor(name){
this.name = name;
}
Emperor.prototype = new Penguin();//inherits all methods and properties including numLegs
// create an "emperor" object and print the number of legs it has
var king = new Emperor("Leo");
console.log(king.numLegs);
Output
2

Prototype chain
Penguin is animal, emperor is penguin->emperor is an animal
If JS encounters smth, it can’t find in the current class’s methods or properties, it looks up the prototype chain to see if
it’s defined in a class that it inherits from. This keeps going upwards until it stops all the way at the top: the mighty
Object.prototype (more on this later). By default all classes inherit from Object unless we change a class’s prototype.
Example
// original classes
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
this.isAlive = true;
}
function Penguin(name) {
this.name = name;
this.numLegs = 2;
}
function Emperor(name) {
this.name = name;
this.saying = "Waddle waddle";
}

// set up the prototype chain


Penguin.prototype = new Animal();//inherits from Animal
Emperor.prototype = new Penguin();//inherits from Penguin and the same time from Animal

var myEmperor = new Emperor("Jules");

console.log(myEmperor.saying); // should print "Waddle waddle"


console.log(myEmperor.numLegs); // should print 2, myEmperor doesn’t have a property numLegs, therefore JS looks for it
in parent class, e.g. Penguin class
console.log(myEmperor.isAlive); // should print true, JS looks for in parent class of parent class of Emperor class, e.g.
Animal class
Output
Waddle waddle
2
true

Modificators
Public variables
All properties are automatically public (can be accessed outside the class).
Example
function Person(first,last,age) {
this.firstName = first;//3 public properties
this.lastName = last;
this.age = age;
}

var john = new Person('John','Smith',30);


var myFirst = john.firstName;//therefore we can assign values of public properties to these variables
var myLast = john.lastName;
var myAge = john.age;

Private variables
Functions have local variables that can be accessed within that function, also objects can have private properties. They can
be accessed only within the class. Declaration within a constructor but without a keyword this!
Example
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;//looks like usual property, but instead this we use var, that makes it private
}
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
this.getBalance = function(){
return bankBalance;
};
}

// create your Person


var john = new Person("John","Smith",25);

// try to print his bankBalance


console.log(john.bankBalance);
console.log(Person.bankBalance);
console.log(john.getBalance());
Output
undefined
undefined
7500

Accessing private variables


By defining a public method that returns the value of private variable
Example
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;

this.getBalance = function() {
return bankBalance;

};
}

var john = new Person('John','Smith',30);


console.log(john.bankBalance);

// create a new variable myBalance that calls getBalance()


var myBalance = john.getBalance();
console.log(myBalance);
Output
undefined
7500

Private methods
An object’s private variable can be accessed only by other methods that are part of the same object.
Methods can be also private and inaccessible outside the class.
Declaration: var getBalance = function(){//come code};//without a keyword this
To access a private method we create a public method to return a private method
Example
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;

var returnBalance = function() {


return bankBalance;
};

this.askTeller = function(){
return returnBalance;//return the returnBalance method, and NOT the result of calling this method, so we don’t need
() after returnBalance
};

var john = new Person('John','Smith',30);


console.log(john.returnBalance);//inaccessible, as private
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();//assign a function to myBalance
console.log(myBalance);
Output
undefined
7500

Passing arguments
Example
nction Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;

this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
else return "Wrong password.";
};
}

var john = new Person('John','Smith',30);


/* the variable myBalance should access askTeller()
with a password as an argument */
var myBalance = john.askTeller(1234);
console.log(myBalance);
//var wrongBalance = askTeller(5);
console.log(john.askTeller(6))
Output
7500
Wrong password.
Example: use of for-in loop and typeof
var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"
};

// print hello in the 3 different languages


for(var x in languages){
if(typeof languages[x] === 'string')
console.log(languages[x]);
}
Output
Hello!
Bonjour!
Hola!
Advantage of a prototype
We can define a method of a class and each instance of a class(object created using that class’s constructor) has this
method.
Example
function Dog (breed) {
this.breed = breed;
};

// add the sayHello method to the Dog class


// so all dogs now can say hello
Dog.prototype.sayHello = function(){
console.log("Hello this is a "+this.breed+" dog");//a keyword this is obligatory
};

var yourDog = new Dog("golden retriever");


yourDog.sayHello();

var myDog = new Dog("dachshund");


myDog.sayHello();

hasOwnProperty is part of baggage that is available to all objects


If we have a plain object(e.g.not created with a constructor), it automatically inherits Object.prototype.
Example
// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype;
console.log(prototypeType);

// now let's examine it!


var hasOwn = Object.prototype.hasOwnProperty('hasOwnProperty');
console.log(hasOwn);
Output
object
true
!But
var hasOwn = prototypeType.hasOwnProperty(‘hasOwnProperty’);//false

Example: final review


function StudentReport() {
this.grade1 = 4;
this.grade2 = 2;
this.grade3 = 1;
this.getGPA = function() {
return (this.grade1 + this.grade2 + this.grade3) / 3;
};
}

var myStudentReport = new StudentReport();

for(var x in myStudentReport) {
if(typeof myStudentReport[x] !== "function") {
console.log("Muahaha! " + myStudentReport[x]);
}
}

console.log("Your overall GPA is " + myStudentReport.getGPA());


Output
Muahaha! 4
Muahaha! 2
Muahaha! 1
Your overall GPA is 2.3333333333333335

Example 2
function StudentReport() {
var grade1 = 4;//now private variables
var grade2 = 2;
var grade3 = 1;
this.getGPA = function() {
return (grade1 + grade2 + grade3) / 3;
};
}

var myStudentReport = new StudentReport();

for(var x in myStudentReport) {
if(typeof myStudentReport[x] !== "function") {
console.log("Muahaha! " + myStudentReport[x]);
}
}

console.log("Your overall GPA is " + myStudentReport.getGPA());


Output
Your overall GPA is 2.3333333333333335

Building a cash register


Example: a cash register
var cashRegister = {
total: 0,
//insert the add method here
add: function(itemCost){
return this.total+=itemCost;
},

scan: function (item) {


switch (item) {
case "eggs":
this.add(0.98);
break;

case "milk":
this.add(1.23);
break;

//Add other 2 items here


case "magazine":
this.add(4.99);
break;
case "chocolate":
this.add(0.45);
break;

}
return true;
}
};

//Scan 2 eggs and 3 magazines


cashRegister.scan("eggs");
cashRegister.scan("eggs");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
//Show the total bill
console.log('Your bill is '+cashRegister.total);
Output
Your bill is 16.93

var cashRegister = {
total:0,
add: function(itemCost){
this.total += itemCost;
},
scan: function(item,count) {
switch (item) {
case "eggs": this.add(0.98*count); break;
case "milk": this.add(1.23*count); break;
case "magazine": this.add(4.99*count); break;
case "chocolate": this.add(0.45*count); break;
}
}
};

// scan each item 4 times


cashRegister.scan("eggs",4);
cashRegister.scan("milk",4);
cashRegister.scan("magazine",4);
cashRegister.scan("chocolate",4);

//Show the total bill


console.log('Your bill is '+cashRegister.total);
Output
Your bill is 8.55

Example: discounts
// create a constructor for the StaffMember class
function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}

var sally = new StaffMember("Sally",5);


var bob = new StaffMember("Bob",10);

//Create a StaffMember for yourself called me


var me = new StaffMember("Jenya",20);

Example: Final code, cash register with discounts


function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}

var sally = new StaffMember("Sally",5);


var bob = new StaffMember("Bob",10);

// Create yourself again as 'me' with a staff discount of 20%


var me = new StaffMember("Jenya",20);

var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount: function(employee){
this.total-=(this.total*employee.discountPercent/100);
},

};

cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object
// to applyStaffDiscount
cashRegister.applyStaffDiscount(me);

// Show the total bill


console.log('Your bill is '+cashRegister.total.toFixed(2));
Output
Your bill is 13.74

You might also like