JavaScript Codecademy Notes
Introduction: getting started with programming
Editor
- Simple calculation:
"Carol".length
= 5 - Math:
2*3
;"Carol".length * 4
- Comments: lines begin with
//
- Good for:
- Explaining tricky parts of codes
- Leaving yourself reminders
- Disabling lines of codes temporarily
- Good for:
JavaScript uses:
- Make websites respond to user interaction
- Build apps and games
- Access information on the Internet
- Organize and present data (e.g., automate spreadsheet work; data visualization)
Interactive JavaScript
- console.log() will take whatever is inside the parentheses and log it to the console below your code. This is commonly called printing out. Examples:
console.log(2 * 5)
;console.log("Hello")
. If we just returned the outcome from our code, the console would only print the very last outcome. Using console.log lets us print more than one line. - Confirm and prompt:
- Simple Cancel/OK message box:
confirm("I am ready to go.");
- Simple OK message box:
alert("You need to pay attention now.")
; - Textarea with Cancel/OK buttons:
prompt("Are you OK?")
- Debugging: finding and fixing mistakes in the code.
- Simple Cancel/OK message box:
Variables
- A variable is a way of saving a value by giving it a specific, case-sensitive name. When you declare a variable (create it), you can then call up that value by typing the variable name.
- Examples:
var myName = "Carol";
var myAge = 59;
var isOdd = true;
- Examples of using variables:
var myName = "Steve Jobs"
;myName.substring(0,5) // = Steve
var myAge = 120; console.log(myAge % 12); // = 0
myName = myName.substring(0,5) // = Steve
Data types
There are five basic data types: number, string, Boolean, undefined, and null. These are often referred to as primitive data types.
Numbers data type
- Examples of the numbers data type are 4.3 and 134.
- Operations describes an action performed on basic values, e.g., addition and multiplication. The order of precedence in number operations follows that in math: brackets, exponents, multiplication, division, addition, and subtraction. (Note: This isn't really correct. It doesn't explain that precedence for multiplication and division is equal and so is addition and subtraction. When there's a tie for these, the precedence goes from left to right.)
- Most symbols for manipulating numbers are very familiar: + for addition, - for subtraction, * for multiplication, and / for division.
- The
modulo
symbol is %. When themodulo
is placed between two numbers, the computer will divide the first number by the second, and then return the remainder of that division. Themodulo
is useful for testing divisibility.- Example:
23 % 10
returns 3 (the remainder).
- Example:
String data type
- Strings contain text between quotes, e.g., "dogs go woof!", "JavaScript expert". An individual string is also known as a string literal.
- String operations can be applied to string values, e.g.,
"My dog's name is " + "Pearl."
Strings that have been put together like this are known as concatenated strings. - You can also combine strings and values, e.g.,
"I think the cost will be " + myEstimatedCost + "."
. - Strings can also be compared with each other. Note that JavaScript is case sensitive, so
"Hi"
does not equal"hi".
- A
substring
enables you to manipulate part of a string.- Example:
"some word".substring(x, y)
where x is where you begin the manipulation and y is the number of the last character you want to manipulate. Note: For x, the first character in the string is counted as 0. For y, the first character in the string is counted as 1. To get the first two characters in Hello, the code is"Hello".substring(0, 2);
- More examples:
- To get the "Jan" in "January":
"January".substring(0,3)
- To get the "Melbourne is" in "Melbourne is Great":
"Melbourne is great".substring(0,12)
- To get "burgers" in "Hamburgers:
"Hamburgers".substring(3,10)
- To get the "Jan" in "January":
- Example:
Boolean data type
- Booleans are either
true
orfalse
. Booleans are the result of comparisons. - There are six comparison operators:
>
Greater than<
Less than<=
Less than or equal to>=
Greater than or equal to===
Equal to (with three equals, the type must also agree; with two equals, the type doesn't have to agree, e.g.,1 == "1"
would be true).!==
Not equal to (with two equals, the type must also agree; with one equal, the type doesn't have to agree)
- Multiple comparison operators can be combined with the or (
||
)operator and the and (&&
) operator. See the or operator section and the and operator section for more information. !
is the not operator and acts on one value to its right. It flips the Boolean value of the value given to it. For example, the statement!(2 + 2 === 4)
would result in false because the!
has flipped the Boolean value of the condition.
Undefined data type
- Represents an undefined value. Haven't gotten to this data type yet.
Null data type
- Represents a null, or nonexistent value. Haven't gotten to this data type yet.
Typeof
- To determine the data type of a variable, use
typeof
.- Example:
var manyThings = ["peanut butter", 1972, "Teletubby", 13.2, true];
var someThing = manyThings[1];
console.log(typeof someThing); // returns "number"
- Example:
Conditional statements (if else, ternary, else if & switch)
Syntax
- When you must use a semicolon:
- At the end of any statement that starts with
var
. - Any time you finish a row of code inside curly brackets. Note: JavaScript Crash Course disagrees with this.
- When setting up a for loop, e.g.,
for (i=0; i<5; i++)
.
- At the end of any statement that starts with
- Do not use a semicolon:
- After the closing curly brackets in if statements or if else statements.
- After the closing curly brackets in for loops and while loops.
If else statements
- If statement or conditional statement determines whether a block of code should run.
- Syntax for if else, else if statements
- Example 1:
if ( condition ) { code; } else { code; }
- Example 2:
If (this condition is true) {
// do this code
}
else // "otherwise" {// do this code instead
}
- Example 1:
Ternary operators
- Ternary operators provide a shortcut way to do simple if else statements.
- Example 1:
result = x > y ? "good job" : 20;
Replaces:
var x =
vary y =
if (x > y) {result = "good job";
}
else {
result = 20;
}
- Syntax:
[variable we are assigning value to] = [if condition] ? [if true] : [else true];
or
condition ? result1 : result2;
- Example 2:
var myAge = prompt("How old are you?")
answer = myAge >= 18 ? "adult" : "non-adult";
- Example 1:
Else if statements
- Else if statements let us check for more than two conditions.
- Example:
if (gender === "male") {
result = "His name is " + yourName;
}
else if (gender === "female" {result = "Her name is " + yourName;
}
else {
result = "Hi " + yourName;
}
- Example:
Switch statements
- Switch statements are especially useful if you are testing for many different cases.
- Example 1:
function getReview(movie) {
var result;
switch(movie) {case "Matrix" :
result = "good trip out";
return result;case "Princess Bride" :
result = "awesome date night movie";
return result;case "Welcome to America" :
result = "Amjad's favorite";
return result;case "Remember the Titans" :
result = "love the sports";
return result;case "Why do I look like I'm 12?" :
result = "The Ryan and Zach story";
return result;case "Fighting Kangaroos in the wild" :
result = "Token Australian movie for Leng";
return result;default :
result = "I don't know!";
return result;}
}
getReview("Matrix");
- Example 2:
var jacketColor = "";
var result;
switch (jacketColor) {case "black":
result = "Pay $300";
break;case "brown":
result = "Pay $200";
break;
default:
result = "This color does not match my eyes!";
}
- Example 1:
- Note: Common practice is to put the default last, although the order doesn't matter.
Nesting conditional statements
- Nesting conditional statements happens when you place one or more conditional statements within another conditional statement.
- Example:
if (yourName.length > 0 && gender.length > 0) {
if (gender === "male" || gender === "female") {
result = "Thanks";
}
else {
result = "Please enter male or female for gender";
}
}
else {
result = "Please tell us both your name and gender.";
}
- Example:
Or operator in conditional statements
- The or operator checks if one or another condition matches. This is written by using
||
between two or more conditions.- Example 1:
variable 1 === 1 || variable1 === 2
- Example 2:
if (gender === "male" || gender === "female" ) {
- Example 1:
And operator in conditional statements
- The and operator checks if one condition and another condition meet requirements. This is written by using
&&
between two or more conditions.- Example 1:
variable 1 === 1 && variable1 === 2
- Example 2:
if (yourName.length > 0 && gender.length > 0) {
- Example 1:
Looping
For loop
- The
for loop
consists of two main parts: thefor statement
and the codeblock
.- The
for statement
on the first line specifies when to start, what to do next, and when to stop. - The code
block
is the part in the curly braces ({}
). It gets repeated each time the for statement meets the criteria in the first line. - Example
for loop
:for (var counter = 1; counter <=5; counter = counter + 1)
{console.log(counter);
}
console.log("All done with the loop");
- The
- The for loop is really useful if you want to go through a set number of things and do something to each one. You could use it to capitalize everyone's name in a list, apply tax to every shoe in someone's shopping cart, or check the away status of each person in your buddy list.
- The for statement has three parts:
- Where to start (
var counter =
1) - Where to stop (
counter<=
5) - Increment counter (how much to change each time) (
counter = counter + 1
)
- Where to start (
- The variable
counter
counts how many times we've gone through the loop. Once we've gone through the loop past the stopping point, we exit the loop and go to the next line. - The letter
i
is often used as a counter variable. There are four counter variable shortcuts.- Instead of writing
i = i + 1
, you can writei++
which increments i after the loop has run. - You can also write ++i, which increments i before the loop has run.
- Instead of writing
i = i - 1
, you can writei--
, which decrements i before the loop has run. - You can also write --i, which decrements i before the loop has run.
- Instead of writing
- You can nest loops within loops.
- Example: Prints out 1 to 5 on separate lines 3 times
for (count = 1; count <= 3; count++) {
for (i = 1; i <= 5; i++) {
console.log(i);
}
i = 1;}
- Example: Prints out 1 to 5 on separate lines 3 times
While loop
- The increment counter is embedded in the while loop.
- Example:
var i = 0;
while (i === 0) {console.log("Hello");
i++;}
- Example:
Recursive loops
- Recursive loops imitate while loops by having a function repeatedly call itself until it sees a reason to stop doing so. When making loops this way — called recursion — consider three things:
- What actions happen on all steps of the loop but the last? This is called the recursive case.
- What is the last step of the loop? For this step, the function will do the step action and, by not calling itself, end. This is called the base case. Tip: if the code doesn't reach the base case, the loop will run forever and crash the browser. Note: The
break
statement does not work in recursive loops. - How is data passed from one step to the next? Recursive functions use argements and return values for this.
- Example:
function countUp(current) {
// Recursive case
if (current < 5) {
console.log(current);
countUp(current + 1);}
// Base case
if (current === 5){console.log(current);
}
}
// We start the loop by calling the function.
countUp(1);
- Example:
For-in loop
- For information on the for-in loop, see the for-in bullet on listing an object's properties and the for-in bullet on listing the values of an object's properties, both in the Objects section.
Functions
Defining functions
- Functions store blocks of code that can be called upon any time to avoid repetition.
- To define a function, we use
var
like we did with declaring a variable. Example:var hello = function()
. - Syntax for calling a function
- Example 1 (one line):
var myFunction = function( parameter ) { code ; } ;
- Example 2 (multiple lines):
var myFunction = function (parameter ) {
code code code;
code code code;};
- Example 1 (one line):
Variables in functions
- Functions can make use of any variable declared before the function is called.
- Variables defined outside a function are global variables and they're accessible anywhere in your program once they have been declared. Global variables have global scope, meaning they are accessible anywhere. (Accessible refers to where the variable can be used.)
- Variables defined (or redefined) inside a function are local variables. Local variables are only accessible within the function they were declared in and hence have local scope.
- If a global variable is redefined inside a function (e.g.,
var area = 36;
has been defined as a global variable andarea = 6
has been defined within a function as a local variable); the local and global values change. - If global and local variables exist (e.g.,
var area = 36;
has been defined as a global variable andvar area = 6
has been defined within a function as a local variable); the global variable value is not changed by the local variable value. - Best practice is to use different naming conventions for local and global variables, e.g., all uppercase for global variables and all lowercase for local variables.
- If a global variable is redefined inside a function (e.g.,
- To run, a function must be called. Example:
hello();.
- The code within a function is contained within a pair of curly brackets.
- Example function.
var hello = function () {
// Prints "i am saying hello twice"
for (var i+1; i <=2; i++ )
{console.log("i am saying hello");
}
}
- Another example function:
var fullName = "";
var name;
var firstLetter;
var fixName = function() {for (i = 1; i <= 2; i++) {
if (i === 1) {
name = prompt("Enter your first name (all in lower case):");
}
if (i === 2) {
name = prompt("Enter your last name (all in lower case):");
}
firstLetter = name.substring(0,1);
name = firstLetter.toUpperCase() + name.substring(1);
fullName = fullName + " " + name;}
console.log("And your full name is:" + fullName);
};
fixName();
- Example function.
Passing parameters to a function
- Functions may include a list of parameters, contained within the parentheses after the function name. Parameters can be thought of as the input to the function. They act as local variables to the function body. When a parameter is passed to a function, it's called an argument. In the example below, Amjad is being passed to the function sayHelloTo as the variable
name
.var sayHelloTo = function (name) {
console.log("Hello " + name);
};
sayHelloTo("Amjad");
- You don't need to specify a type when defining a function. However, if your function only works with numbers, you may be strange results when it is called with a string parameter.
- Example:
var cube = function(x) {
return x * x * x;
}
console.log(cube("test")); // will return NaN
- Example of checking for non-number string using typeof() and number and returning something else if the parameter that's passed is not a number:
var cube = function(x) {
if (typeof(x) != 'number') return 0;
return x * x * x;
}
console.log(cube("test")); // will return 0
- Example:
Return and branching in functions
- Functions are often part of a process that receives inputs and use it to compute an output. Functions usually use their arguments to compute a value which will become the result from the function call. The
return
keyword is used in a function to return a value when the function is called. - The
return
keyword provides a way of exiting at any point in the function's code. Branching is when there are more than one uses ofreturn
in a function. The two uses ofreturn
in the example below illustrate branching.- Example 1:
var isEven = function (n) {
if (n % 2 === 0) {
return true;
}
else {
return false:
}
};
- Example 1:
Calling a function within code
- You can call a function in your code and then use the returned results.
- Example:
function canIDrive(myAge, legalDrivingAge) {
if (myAge >= legalDrivingAge) {
return true;
}
else {
return false;
}
}
var myAge = prompt("How old are you?")
var legalDrivingAge = 16;if (canIDrive(myAge, legalDrivingAge) === true) {
console.log("You can legally drive!");
}
else {
console.log("You'll have to wait a few more years!")
}
- Example:
Recursion (calling a function within that function)
- See recursive loops section for more information.
Return values
- When a function is called, the return value can be used just like any other value in JavaScript.
- Example:
var quarter = function(n) {
n = n / 4;
if (n === 1) {
console.log("The statement is true.");
return true; // return must come after console.log
}
else {
console.log("The statement is false.");
return false;
}
};
quarter(4);
- Example 2, where a function calls another function:
var cube = function (x) {
var y = x;
y = square(y);
x = y * x;
return x;};
var square = function (y) {
return y * y;
};
cube(3);
- Example 3, a function calls another function using the not operator
var isOdd = function(n) {
if (n % 2 !== 0) {
return true;
}
else {
return false;
}
};
var isEven = function(n) {
return !isOdd(n);
};
console.log(isEven(1));
console.log(isEven(2));
console.log(isEven(999));
Multiple parameters
- You can pass multiple parameters to a function.
- Example 1:
var area = function (w , l) {
// return the product of w and l
return w * l;
};
console.log(area(8, 6));
- Example 2 (is x evenly divisible by y):
var isDivisible = function (x, y) {
if (x % y !== 0) {
return false;
}
else {
return true;
};
console.log(isDivisible(10,3));
console.log(isDivisible(10,2)); - Example 3 (to the power of):
var power = function (base, exponent) {
var result = 1;
for (var i = 0; i < exponent; i++) {result = result * base;
return result;
};
console.log(power(2,2));
- Example 4: Test results with test cases. To example 3, add some test cases that compare actual results with expected results:
console.log(power(2,2) === 4);
console.log(power(4,3) === 64);
console.log(power(3,3) === 27);
- Example 1:
Arrays
- Arrays:
- Store lists of data.
- Store different data types at the same time.
- Are ordered so the position of each datum is fixed.
- Array syntax is
var arrayName = [datum, datum, datum];
. Any time you see data surrounded by[]
, it is an array. - Examples:
var names = ["Mao", "Ghandi", "Mandela"];
var sizes = [4, 6, 3, 2, 1, 9];
var mixed = [34, "candy", "blue", 11]
- To access the data inside the array, use its position, starting from 0. Examples:
- First element in the array:
junkData[0]
- Third element in the array:
junkData[2]
- First element in the array:
- To access array properties, you can:
- Create variables using dot notation, that is, ObjectName.PropertyName, e.g.,
var name1 = Spencer.age;
. - Create variables using bracket notation, that is, ObjectName["PropertyName'], e.g.,
var name1 = Spencer["age"];
. An advantage of bracket notation is that you are not restricted to just using strings in the brackets
- Create variables using dot notation, that is, ObjectName.PropertyName, e.g.,
- The length property calculates the number of values in an array, e.g.:
var lost = [4, 8, 15, 16, 23, 42];
var count = lost.length; // = 6
- Tip: when looping through an array, creating a variable that's equivalent to the length of the array (e.g., count = lost.length) instead of
array.length
(e.g.,lost.length
) creates code that's faster because the length only needs to be calculated once.Array.length
has to be recalculated every time the loop is executed.
Using a function with an array
- Example 1: function that returns
true
ifn
is in the array;false
if it is not.var lost = [4, 8, 15, 16, 23, 42];
var count = lost.length;
var isLost = function (n) {
for (var i = 0; i < count; i++) {
if ( n === lost[i]) {
return true;
}
}
return false;
};
isLost(16); // will return true
- Example 2: using a function to print arrays within an array (subarrays) like table cells. The contents of each row in the table array are printed to the console with two spaces between each value. To refer to a subarray value within an array, use the syntax
array[index][subarray_index]
, e.g.,table[i][rowPlace]
.- Example:
var table = [
["Person", "Age", "City"],
["Sue", 22, "San Francisco"],
["Joe", 45, "Halifax"]];
var count = table.length;
for (i = 0; i < count; i++) {var rowCount = table[i].length;
for (rowPlace = 0; rowPlace < rowCount; rowPlace++) {var rowContent = rowContent + table[i][rowPlace] + " ";
}
console.log(rowContent);
rowContent = "";}
- Example:
Objects & methods
Objects
- By storing all relevant information in one place, objects allow us to represent real world things and entities (such as a person or a bank account) in code.
- One way to create an object is to declare it with
var
followed by the name of the object, an equals sign, and a pair of curly brackets with information inside. The information inside the brackets is in the format property: value, property: value. Creating a new object with curly brackets and defining properties within the brackets uses literal notation.- Syntax:
var myObject = {property: value, another_property: another_value };
- Example 1:
var Spencer = {age: 22, country: "United States" };
- Example 2:
var Spencer = {
age: 22,
country: "United States"}
- Syntax:
- Another way to create objects without using the curly brackets is to use the keyword
new
. A constructor is a way to create an object using the keywordnew
; the syntax for this is known as constructor notation. - The most basic constructor is the Object constructor, which will make an object with no properties or methods.
- Example of an Object constructor:
var objectName = new Object();
- Example of an Object constructor:
- You can also create objects and put in whatever properties and methods you want.
- Example:
var Spencer = new Object();
Spencer.age = 22;
Spencer.country = "United States"
;
- Example:
- Another way to create an object is by passing its name and parameters to a function.
- Example 1:
function Person(name,age) {
this.name = name;
this.age = age;
};
var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 25);
- Example 2:
var Hello = {
Name: function(nameVal){
console.log("Hello " + nameVal);
}
};
// To access the function
Hello.Name("Carol");
// or
var myName = "Carol";
Hello.Name(myName);
- Example 1:
- To change a property's value, you can just declare it, e.g.,
james.job = "super programmer"
;. - You can access properties through dot notation or bracket notation.
- Example of bracket notation:
var james = {
job: "programmer",
married: false};
// set to the first property name of "james"
var aProperty = "job";
// print the value of the first property of "james"
// using the variable "aProperty"
console.log(james[aProperty]);
- Example of bracket notation:
- To find out if an object has a particular property, use hasOwnProperty, e.g.,
console.log
will return(myObj.hasOwnProperty ('nickname')); true
if the object has a nickname property, even if the property has no value.- Example of finding out if an object has a property and, if not, creating and populating it:
var suitcase = {
shirt: "Hawaiian"
};
if (suitcase.hasOwnProperty('shorts') === true) {
console.log(suitcase.shorts);
}
else {suitcase.shorts = "red";
console.log(suitcase.shorts);}
- Example of finding out if an object has a property and, if not, creating and populating it:
- To list all the properties an object has, use a for-in loop.
- Example:
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5};
for (var propertyList in nyc) {console.log(propertyList);
}
This returns the list of properties (fullName, mayor, population, boroughs), with each property on a separate line.
- Example:
- You can also use the for-in loop to print the values of all an object's properties.
- Example 1: printing all the property values
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5};
for (var propertyList in nyc) {
console.log(nyc[propertyList]);
}
This returns New York City, Michael Bloomberg, 8000000, and 5, with each value on a separate line.
- Example 2: printing only property values that are strings, using typeof
var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"};
for (var propertyList in languages) {
if (typeof languages[propertyList] === "string") {
console.log(languages[propertyList]);
}
}
- Example 3: printing both properties and property values.
var person = {
name: "Morgan Jones",
telephone: "(650) 777 - 7777",
email: "morgan.jones@example.com"};
for (var propertyName in person) {
console.log(propertyName + ": " + person[propertyName]);
}
- Example 1: printing all the property values
String objects
- You can use the String class constructor or literal notation to create a string literal. String literals get their properties and methods from the
String
class. String is a JavaScript built-in object.- Examples:
var str1 = new String("Hello world!");
var str2 = "Hello again!";
- Examples:
str.indexOf(otherStr)
returns the position in the variablestr
that the textotherStr
first occurs. IfotherStr
does not occur withinstr
, -1 is returned.- Example: for
var str1 = new String("Hello world!");
str1.indexOf("world")
returns 7
str1.indexOf("Hellow")
returns -1
- Example: for
str.replace(findMe,replacement)
will return a new string withfindMe
repaced withreplacement
in the variablestr
.- Example: for var str1 = new String("Hello world!");
str1.replace("world","universe");
changesstr1
to "Hello universe!".
- Example: for var str1 = new String("Hello world!");
- Use
String.prototype.methodname
andthis.toString
to extend theString
prototype as shown in the example.- Example:
var str1 = "It was the best of times";
var str2 = "It was the worst of times";String.prototype.futureDickens = function() {
var currentStr = this.toString();
return currentStr.replace("was","will be");};
console.log( str1.futureDickens() );
console.log( str2.futureDickens() );
- Example:
Methods
- A method is like a function that's associated with an object. Methods can be used to change object property values and to make calculations based on object properties.
- Calling a method is like calling a function. The syntax is ObjectName.methodName(), e.g.,
bob.setAge = function(newAge) { bob.age = newAge; };
. This method sets the propertyage
of the objectbob
to whatever is passed as a parameter.- Example 1: setting an object property value
var bob = new Object();
bob.age = 30;
bob.setAge = function(newAge) {
bob.age = newAge;
};
- Example 2: making calculations based on object properties
var bob = new Object();
bob.age = 30;
bob.getYearOfBirth = function() {
return 2012 - bob.age;
}
console.log(bob.getYearOfBirth());
- Example 3: making calculations based on object properties and methods (running total).
Note: When you call a function from within a function, use the syntaxthis.functionBeingCalled()
becausethis
refers to the object which contains the function. Thus, it can only be used from within an object. When you call a function within an object from outside of that object, always useObjectName.functionBeingCalled()
.function staffMember(name,discountPercent) {
this.name = name;
this.discountPercent = discountPercent;
}
var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);
var sally = new StaffMember("Sally",5);
var me = new StaffMember("Carol",20);
var cashRegister = {
total:0,
add : function(itemCost, quantity) {lastTransactionAmount = itemCost;
this.total += itemCost;},
scan: function(item) {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(itemCost) {
this.total -= lastTransactionAmount;
}
,
applyStaffDiscount : function(employee) {
this.total -= (this.total * (employee.discountPercenter/100));
}
};
//Scan 4 of each items
cashRegister.scan("eggs", 4);
cashRegister.scan("milk", 4);
cashRegister.scan("magazine", 4);
cashRegister.scan("chocolate", 4);//Void last transaction & scan 3 instead of 4
cashRegister.voidLastTransaction();
cashRegister.scan("chocolate", 4);
//Apply your discount
cashRegister.applyStaffDiscount(me);
//Show the total bill
console.log('Your bill is '+cashRegister.total);
- Example 1: setting an object property value
- A method can work for many objects by referring to the current object with the
this
keyword. The keywordthis
acts as a placeholder, and will refer to whichever object called that method when the method is actually used.- Example 1, changing a property's value:
var setAge = function(newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
bob.setAge(50);
- Example 2, return a value for a variable:
var square = new Object();
square.sidelength = 6;
square.calcPerimeter = function() {
return this.sideLength * 4;
};
var p = square.calcPerimeter();
- Example 3, using a function to create and populate objects (note how species is treated)
function Person(name, age) {
this.name = name;
this.age = age;
this.species = "Home Sapiens";
}
var sally = new Person("Sally Bowles", 39);
var holden = new Person ("Holden Caulfield", 16);
console.log(sally.name + " species is " + sally.species + " and " + sally.name + " is " + sally.age + " years old.");
- Example 4, creating objects with both properties and methods and then populating variables
function Rectangle(length, width) {
this.length = length;
this.width = width;
this.calcArea = function() {
return this.length * this.width:
};
this.calcPerimeter = function() {
return (this.length * 2) + (this.width * 2);
};
}
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();
- Example:
var comedy = {
schadenfreude : function() {
var evilWished = prompt("Whose misfortune would make you happy?");
return evilWished;},
schadenfreudeWhy : function() {var reasonWhy = prompt("Why do you ill wish that person?");
return reasonWhy;},
irony : function() {myEvilWished = this.schadenfreude();
myReasonWhy = this.schadenfreudeWhy();}
};
comedy.irony();
console.log("I notice that you and " + myEvilWished + " share something in common: " + myReasonWhy + ".");
- Example 1, changing a property's value:
- Objects can be used as parameters for functions as well. These functions can take advantage of the methods and properties that an individual object type provides.
- Example:
function Person (name, age) {
this.name = name;
this.age = age;
}
var ageDifference = function(person1, person2) {
return person1.age = person2.age;
}
var alice = new Person("Alice", 30);
var billy = new Person ("Billy", 25);
var diff = ageDifference(alice, billy);
- Example:
- We can add methods (functions associated with objects) to objects using constructor or literal notation. Methods defined in both constructors and literal notation can take parameters, just like normal functions.
- Example 1: constructor notation
var james = {
job: "programmer",
married: false,
sayJob: function() {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";
// james' second job
james.sayJob(); - Example 2: literal notation
var james = {
job: "programmer",
married: false,
speak: function(text) {if (text === "great") {
console.log("Hello, I am feeling great");
}
else if (text === "just okay") {console.log("Hello, I am feeling just okay");
}
else {}}
};
james.speak("great");
james.speak("just okay");
- Example 1: constructor notation
Using objects with an array
- An object is just another data type, like a string or a number but more complex. Just as we can make arrays of numbers and strings, we can make arrays of objects.
- Example 1: creating an array called family from Person objects
function Person (name, age) {
this.name = name
;this.age = age;
}
var family = new Array();
family[0] = new Person ("Alice", 40);
family[1] = new Person ("Bob", 42);
family[2] = new Person ("Michelle", 8);
family[3] = new Person ("Timmy", 6);
- Example 2: using a for loop to display each family member's name from example 1.
var count = family.length;
for (var i = 0; i < count; i++) {
console.log(family[i].name);
}
NoUte: functions that display a specific property of an object are often called accessor functions or getter functions.
- Example 1: creating an array called family from Person objects
- To add an object to the end of an existing array, you can use the fact that array's length equals the index number of the new object. (Remember the index number of the first object in an array is 0, so the index number of the last object is the array length - 1. The index number of the new object is then the length - 1 + 1, or just the length.)
- Example:
contacts[contacts.length] = new Object(firstName, lastName, email, telephone);
- Example:
Object-oriented programming
- Object-oriented programming, often abbreviated OOP, is a widely-used programming paradigm that uses a series of interactions with objects to execute a program. Each object contains data and a set of methods that let us use that data. The objects themselves are created from classes, which are like templates for objects. Encapsulation is the grouping of an object's data together with its methods.
Classes
- When you use a constructor, e.g.,
var bob = new Person("Bob Smith", 30)
andvar susan = new Person("Susan Jordan", 35);
, you are actually defining a new class. A class can be thought of as a type, or a category of objects with certain properties and methods. Classes give us helpful information about objects and you can think of an object as a particular instance of a class. - Often classes are called by the same name as the constructor used to create them, e.g., the variables
Bob
andSusan
are part of the classPerson
(function Person(name,age) { this.name = name; this.age = age; };
). - JavaScript automatically defines the prototype for a class with a constructor. The parameters that are passed (e.g., name and age) are the basis for the object's properties.
- Methods can be associated with classes too by being called in the constructor, e.g., the Dog.prototype.bark method used below.
- Syntax for adding a method to a class so that all members of the class can use it:
className.prototype.newMethod = function() {
statements;
};
- Example 1: using a prototype that will work for any member in the class
function Dog (breed) {
this.breed = breed;
}
;var buddy = new Dog("Golden Retriever");
Dog.prototype.bark = function() {console.log("Woof");
};
buddy.bark();var snoopy = new Dog("Beagle");
snoopy.bark();
- Example 2: referencing an object's property in the prototype
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
var penguin = new Animal("Captain Cook",2);
penguin.sayName();
- Syntax for adding a method to a class so that all members of the class can use it:
Inheritance in OOP
- In OOP, inheritance allows one class to see and use the methods and properties of another class. You can think of it as a child being able to use his or her parent's money because the child inherits the money.
- Inheritance supports the DRY principal of programming: Don't Repeat Yourself.
- Example: The Penguin class inherits the Animal class but the number of legs doesn't have to be sent via a parameter and sayName can be used by Penguin.
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;}
Animal.prototype.sayName = function() {console.log("Hi my name is "+this.name);
};
function Penguin(name) {
this.name = name;
this.numLegs = 2;}
Penguin.prototype = new Animal();var penguin = new Penguin("Percy");
penguin.sayName();
- Example: The Penguin class inherits the Animal class but the number of legs doesn't have to be sent via a parameter and sayName can be used by Penguin.
- If JavaScript encounters something 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.
- Example: showing variable myEmperor's inheritance and ways to use inheritance
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";}
Penguin.prototype = new Animal();
Emperor.prototype = new Penguin();var myEmperor = new Emperor("Jules");
console.log(myEmperor.saying); // prints "Waddle waddle"
console.log(myEmperor.numLegs); // prints 2
console.log(myEmperor.numLegs < 3); // prints true
- Example: showing variable myEmperor's inheritance and ways to use inheritance
- The top of the chain is the Object.prototype — by default, all classes inherit directly from Object, unless you change the class's prototype.
- Use the
instanceof
keyword to test if an object is an instance of a particular class, that is, inherits its data and methods. Theinstanceof
keyword will return true or false.- Example: myElectricCar is an instance of the ElectricCar class, which inherits from the Car class. In the example below,
true
will be returned.console.log(myElectricCar instanceof Car);
- Example: myElectricCar is an instance of the ElectricCar class, which inherits from the Car class. In the example below,
Public & private properties & methods of objects
- In JavaScript, all properties of an object are automatically public, meaning that they can be accessed outside the class. Think of these properties as information a class is willing to share.
- Just as functions can have local variables which can only be accessed from within that function, objects can have private variables. Private variables, declared with
var
=, are pieces of information you do not want to publicly share, and they can only be directly accessed from within the class.- Example: in the example below, firstname, lastname, and age are public properties and bankBalance is a private variable.
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;}
- Example: in the example below, firstname, lastname, and age are public properties and bankBalance is a private variable.
- Although we can't directly access private variables from outside the class, we can get around that by defining a public method (using
this.method
instead ofvar =
) that returns the value of a private variable.- Example:
getBalance
returns the private variablebankBalance
to themyBalance
variable.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);
var myBalance = john.getBalance();
console.log(myBalance);
- Example:
- A private method is private within a class and inaccessible outside of the class. To access a private method, create a public method for the class that returns the 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;
};
}
var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);
- Example:
- Blackjack example:
function Card(s,n) {
var suit = s;
var number = n;
this.getSuit = function() {return suit;
};
this.getNumber = function() {return number;
};
this.getValue = function() {if (number >= 10) {
cardValue = 10;
return cardValue;}
else if (number === 1) {cardValue = 11;
return cardValue;}
else {cardValue = number;
return cardValue;}
};
}
// Make a deal function here. It should return a new card with a suit
// that is a random number from 1 to 4, and a number that is a random
// number between 1 and 13
var deal = function() {s = Math.floor(Math.random() * 4 + 1);
n = Math.floor(Math.random() * 13 + 1);
return new Card(s,n);};
function Hand() {
this.card1 = deal();
this.card2 = deal();
this.score = function() {return this.card1.getValue() + this.card2.getValue();
};
}
Hand();
var myHand = new Hand(); var yourHand = new Hand();console.log("I scored a "+myHand.score()+" and you scored a "+ yourHand.score());
if(yourHand.score() > myHand.score()) console.log("you win!");
else if(yourHand.score() < myHand.score()) console.log("I win!");
else console.log("We tied!");
Miscellaneous
- To generate a random integer >=1 and <=6:
- Example:
var die = Math.floor(Math.random()*6 + 1);
Math.random()
generates a number >= 0 and <= .999 soMath.random()*6 + 1
generates a number between 1 and 6.994.Math.floor()
rounds the calculated number down to the nearest integer, so the result is an integer between 1 and 6, inclusive.
- Example:
Math.pow(num1, num2)
takesnum1
to thenum2
-th power and returns the result of the exponentiation.Math.max(num1, num2, num3)
takes two or more numbers and returns the one with the largest value.