Javascript Basics Flashcards
means to “commented out”
// on the line first line
the “.” is a “full stop” and the length give you the length of the word
“word”.length
This will make a pop up box that you have to click to continue
confirm(‘some sentence here’);
an input the the program needs to take an action
prompt(“What is your name?”);
strings are written with quotes
“what is your name?” or “42”
booleans are used to compare numbers and strings
true or false
this determines if this is string is greater than 10 characters and returns the result “true”
“I’m coding like a champ!”.length > 10;
whatever is in the parentheses is “logged to the console” (sometimes called “printing out”), or displaying what the computer is thinking/doing
console.log(2 * 5)
standard operators
> ,=
equal to
===
Not equal to
!==
If statement that if true, will “log the string in the console”
if ( “Brent”.length < 7 ) {
console.log(“Wonderfully True”);
}
Modulo - When % is placed between two numbers, the computer will divide the first number by the second, and then return the remainder of that division.
%
Substring - x is where you start chopping, and y is where you stop chopping each character is numbered starting at 0
“some word”.substring(x, y)
var varName = data;
once you “declare” a variable name, you can call up that value by declaring the variable nameusing a variable, you don’t put it in parenthesis because it will turn it into a string, rather than using the variable value (which can be a string or a number)
this will ask the user for a response, and store the response as the value of the variable “age”
var age = prompt(“What is your age?”);
Function structure
var divideByThree = function (number) { var val = number / 3; console.log(val); }; divideByThree(12);
Parts of a function
the code between the { } is what is run every time the function is calledInputOutputCallThe code in the (parentheses) is parameterit’s a placeholder word that we give a specific value when we call the function. Parameters go in the parentheses. The computer will look out for it in the code block.
D.R.Y.
don’t repeat yourself.
return structure
var timesTwo = function(number) { return number * 2; }
about return
return saves the number to the machine so that it can be used in other code, like this:
var newNumber = timesTwo(6) { console.log(newNumber); }
note you do not need to define a second variable to do some calculation and then return the variable, it all can be calculated with the return on one line
only valid inside functions!
scope global
Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global
scope local
Variables defined inside a function are local variables. They cannot be accessed outside of that function.
Random number
Math.random()
If we declare a variable and make it equal to Math.random(), that variable will equal a number between 0 and 1.
for loop structure
for (var counter = 1; counter < 11; counter++) { console.log(counter); }
about for loop
- Every for loop makes use of a counting variable.
- When the for loop executes the code in the code block—the bit between { }—it does so by starting off where i = 1.
- the second part of the for loop tells the loop when to stop
- see third section in for loop
3rd section in for loop
i++ i + 1 i-- i - 1 i += x i + x i -= x i - x
In general, a += b; means “add b to a and put the result of that addition back into a. This is also available for the other basic arithmetic functions: -=, *=, and /= do what you expect.
var cashRegister = { total:0, add: function(itemCost){ this.total += itemCost; } };
array structure
var arrayName = [data, data, data]; Any time you see data surrounded by [ ], it is an array.
about array’s
- store lists of data
- store different types of data at the same time
- ordered so each piece of data is fixed
- The position of things in arrays is fixed. The position (or the index) of each bit of data is counted starting from 0, not 1.
print the 4th element of the array “junk”
console.log(junkData[3]);
how to go through a “for” loop and stop the cycling through an array before there becomes an infinite loop
var cities = ["Melbourne", "Amman", "Helsinki", "NYC"]; for (var i = 0; i < cities.length; i++) { console.log("I would like to visit " + cities[i]); the “i < cities.length” is referring to the number of data points there are in the array (in this case four, or i=3 because we start off at i=0)
how to add something to an array
.push()
.push() method that adds the thing between parentheses to the end of the array
what do you use when you don’t know how long you want to do something?
a “while” loop
Structure of a “while” loop
var understand = true; while( ){ console.log("I'm learning while loops!"); understand = false; }
additional features of the “while” loop
- When you use a number in a condition, as we did earlier, JavaScript understands 1 to mean true and 0 to mean false.
- When assigning a variable boolean value of true, you do not have to put “=== true” in the condition, only put the variable and the system will know it is true
- Make sure to set an initial condition outside of the while loop or else it will continue resetting the initial condition every time
do/while loop
This loop says: “Hey! Do this thing one time, then check the condition to see if we should keep looping.” After that, it’s just like a normal while: the loop will continue so long as the condition being evaluated is true.
var loopCondition = false;
do {
console.log(“I’m gonna stop looping ‘cause my condition is “ + loopCondition + “!”);
} while (loopCondition);
Sets a variable to a random number that’s either 0 (false) or 1 (true)
Math.floor(Math.random() * 2)
a function that checks to see if “is not a number”
isNaN
to be used when you don’t want to use a bunch of “else if” statements
Switch statement
you have a series of “cases” that it will run through and then a default case if no scenarios match the cases given
Switch statement structure
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;
default:
console.log(“Huh! I’m not sure what “ + lunch + “ is. How does a sandwich sound?”);
}
Logical Operators
and(&&)
or (||)
not (!)
and(&&)
“logical operator”
It evaluates to true when both expressions are true; if they’re not, it evaluates to false.
or (||)
“logical operator”
It evaluates to true when one or the other or both expressions are true; if they’re not, it evaluates to false.
not (!)
“logical operator”
It makes true expressions false, and vice-versa.
make a prompt all upper case or lower case
prompt().toUpperCase() or prompt().toLowerCase()
if statement structure
if (/* Some condition */) { // Do something } else if (/* Some other condition */) { // Do something else } else { // Otherwise // Do a third thing }
multi-dimensional arrays
each array separated by a , makes a new row
two-Dimensional (multi-dimensional) arrays
var twoDimensional = [[1, 1], [1, 1]];
jagged arrays
may have different numbers of columns in each row
object literal notation
var myObj = { type: 'fancy', disposition: 'sunny' };
var emptyObj = {};
note that the key’s are implicitly assumed to be strings, so you can leave them off if wanted.
object constructor
var myObj = new Object();
object custom constructor format
function AnyObject(name, age){ this.name = name; this.age = age; this.species = "Homo Sapiens"; } NOTICE HOW THE CONSTRUCTORS FIRST LETTER OF THE NAME IS IN CAPS
properties of an object
The key is “name” and “number”
The value is “Oxnard Montalvo” and “(555) 555-5555”;
object dot notation
ObjectName.PropertyName (e.g., bob.name)
object bracket notation
ObjectName[“PropertyName”]
- don’t forget the “” in the brackets unless you have created a var that is equal to the the name of the object property string
var someObj = {propName: someValue}; var myProperty = "propName"; someObj[myProperty];
what is a method
method is just like a function associated with an object.
why are methods helpful
- usefull for Updating the object properties, and Calculating something based on an object’s properties.
- Functions can only use parameters as an input, but methods can make calculations with object properties.
var rectangle = new Object(); rectangle.height = 3; rectangle.setHeight = function (newHeight) { this.height = newHeight; }; rectangle.setHeight(6);
the keyword “this” in a method
var setAge = function (newAge) { this.age = newAge; }; The keyword thisacts as a placeholder, and will refer to whichever object called that method when the method is actually used.
Object constructor
var anObject = new Object() the Object is a constructor (built into JavaScript to create an empty object).
Array constructor
var family = new Array();
for in loop (with a search function example)
var search = function (name) {
for(var key in friends) {
if(friends[key].firstname === name) {
console.log(friends[key]);
return friends[key];
- “friends[key].firstname === name” is how you would reference the key in the Object
- note that the “key” can really be any variable and the loop will assign that variable as the name of each of the object properties
what is returned when comparisons are made? (>, <, !==)
boolean values (true or false)
how can objects be put into arrays?
array[position] = object
To append something to the end of the array, you need to put it in the position one after the last item.
var family = new Array(); family[0] = new Person("alice", 40); family[1] = new Person("bob", 42); family[2] = new Person("michelle", 8);
how to determine what type of thing something is
var someObject = {someProperty: someValue}; console.log( typeof someObject );
lets you know if an object has a particular property
hasOwnProperty
console.log( myObj.hasOwnProperty(‘name’) );
will print true if the object has the property
how to make a class and what a class is
- Constructors can make objects, but you are also defining a new class
- A class can be thought of as a type, or a category of objects—kind of like how Number and String are types in JavaScript.
what defines what a class has or does not have
A prototype. it is basically what a constructor defines the new object to have initially. properties or methods can be added to an object, but they are not part of the prototype
how to use a prototype
Dog.prototype.bark = function() {
console. log(“Woof”);
- This had now changed the prototype for the class Dog. This immediately teaches all current and future Dogs the new method.
className.prototype.newMethod = function() {
statements;
};
Whenever this X is-a Y relationship exists, there’s a good chance that we should be using
inheritance
how to set inheritance
To say that Penguin inherits from Animal, we need to set Penguin's prototype to be Animal. Penguin.prototype = new Animal();
prototype chain
- By default, all classes inherit directly from Object, unless we change the class’s prototype, like we’ve been doing for Penguin and Emperor
- The “prototype chain” in JavaScript knows this as well. 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. This keeps going upwards until it stops all the way at the top: the mighty Object.prototype
properties of an object are automatically (public or private)
public
how to create a private property or method of an object
use a var instead of "this" function Person(first,last,age) { this.firstname = first; this.lastname = last; this.age = age; var bankBalance = 7500; }
how to show a private variable
function Person(first,last,age) { this.firstname = first; this.lastname = last; this.age = age; var bankBalance = 7500;
this.getBalance = function() {
return bankBalance;
};
}
how to display a private method
function Person(first,last,age) { this.firstname = first; this.lastname = last; this.age = age; var bankBalance = 7500;
var returnBalance = function() { return bankBalance; };
// create the new function here 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);
- This means that it returns the method itself and NOT the result of calling that method. So you should NOT have parentheses after returnBalance.
- when referring to a function within a function, use this.method, so that it refers to its own defined method
using a function that has been defined outside of an object as an object method
you need to first set object.method (which is the function) = function
var setAge = function (newAge) { this.age = newAge; }; var bob = new Object(); bob.age = 30;
// and down here we just use the method we already made bob.setAge = setAge;
bob.setAge(50);
creating a variable without current scope
The var keyword creates a new variable in the current scope. That means if var is used outside a function, that variable has a global scope. If var is used inside a function, that variable has a local scope.
pointing to a specific letter in a string
You can use an array on a String
var myName = ‘Eric’;
myName[0]; // equals ‘E’
how do you use a key or value from an object in the object’s method
var james = { job: "programmer", married: false, sayJob: function() { // complete this method console.log("Hi, I work as a " + this.job); } };
(make sure to reference the object.key or this.key or else the variable will be undefined)
where should you put your functions in your script
it is good idea to put your functions at the top of the page
what happens when you hit “return” in the code
the program will stop running immediately
using global variables inside functions
try to avoid accessing or changing global variables within a function - it makes it more error prone and difficult to test
How to remove the First Item from an array
.shift()
var items = ['Hat', 'Ball', 'Shoes']; var firstItem = items.shift(); // firstItem now holds 'Hat' // and items is now ['Ball', 'Shoes']
unshift()
it(“should push and pop”, function() {
var array = [1, 2];
array.push(3);
expect(array).toEqual([1, 2, 3]); var poppedValue = array.pop(); expect(poppedValue).toBe(3); expect(array).toEqual([1,2]); });
Remove the Last Item from an array with
.pop()
var items = ['Hat', 'Ball', 'Shoes']; var lastItem = items.pop(); // lastItem now holds 'Shoes' // and items is now ['Hat', 'Ball']
add all the elements of an array into one string
.join() method
var daysInWeek = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"} var daysString = daysInWeek.join(",")
would return: Mon, Tue, Wed…
you can join the items in an array by anything
add one array to another array
var firstArray = [1,2,3]; var secondArray = [a,b,c];
var bothArrays = firstArray.concat( secondArray);
console.log( bothArrays );
[1,2,3,a,b.c]
it doesn’t change any of the original arrays - but creates a new array and puts the values there
index
look this one up
document method that allows you to replace the content in an html <div></div>
in the html -
<div>
</div>
function print(message){ var outPutDiv = document.getElementByID("output"); outPutDiv.innerHTML = message } the document.getElementByID("output") is an object with reference to a particular part of the page (also called a "node")
the innerHTML is a DOM property, of which you set to what you want to display on in the tag “output”
how to log multiple things to the console with one line of code
separate items by a comma:
console.log(“I want”, “ to “, “go to sleep);
JavaScript Object Notation
JSON - sends a string of text that can be easily passed from server to client. The client will then automatically convert it to object format from the string
for more info:
http: //teamtreehouse.com/library/ajax-basics
http: //teamtreehouse.com/library/ajax-basics/programming-ajax/introducing-json
represents the idea of nothingness, or non-existence
null
you will encounter null when someone or some system is trying to indicate that the item you are looking for definitely doesn’t exist
represents an unknown or undetermined state
undefined
you will encounter undefined when someone or some system is trying to indicate that the item you are looking cannot be found for some reason. an example is when you try to access a value in an object for a key that doesn’t exist.
an expression that ends in a semicolon allows the interpreter to proceed to the next line with a relatively clean slate
expression: console.log(3+2)
statement: console.log(3+2);
(this is known as an expression statement)
variable declaration statement
introducing a new value by using the var keyword. Allows you to assign the initial value. Can be thought of some label or alias that points to some value
variables can refer to values or other variables (T or F)
False. while you can set a var oneVariable = otherVariable, you are not actually setting it equal to the otherVariable, just the value of the otherVariable So if: var result = 5; var otherResult = result; result = 0; console.log(otherResult); ---> 5!!!
key are available to have only letters or number (T or F)
they are allowed to have slashes, spaces or dots
difference between alpha and numeric keys on arrays
alpha properties don’t count towards the array.length and numeric properties do
enumerable properties of an object or array
properties like length on an array that do not get iterated over during a for in loop for example
what is the only difference between regular objects and functions?
functions have the magical ability to be invoked (which means to activate a whatever behavior the function is capable of
Also, functions can have properties just like objects
what do you need to put on the function to run it?
two parenthesis for example: function();
immediate invocation of a function
when you put a trailing () at the end of a definition, without anything in between. example: var two = function() {return 2;} ();
arguments variable
a variable in the function that stores an array of the parameters passed into the function. it automatically holds a new array each time the function gets called and stores the values of the parameters
limitations to the special objects: var obj = null; var obj = undefined;
not allow to set set or access variables of the object, as it is null/undefined. (same thing goes for booleans, strings and numbers)
accessing (with dot or bracket notation) a property of an object that happens to be another object, will evoke the property object (T or F)
False, access a property of an object does not itself run the object;
how to use ? and : to do if/else statements
_.last = function(array, n) {
return n === undefined ? array[array.length - 1] : n > array.length ? array : array.slice(array.length - n)
};
what is scope
part of a program where the binding between a variable and a value is valid
can variables created within blocks like if or while be access outside of the blocks themselves?
Yes, they will be considered in the “global scope” lexicon. Only vars created inside of a function are considered to be in an a different scope lexicon.
how to pass a function and it’s arguments into another function
var result = func.apply(this, arguments);
an example of closure scope: ._once
// Return a function that can be called at most one time. Subsequent calls // should return the previously returned value. _.once = function(func) { // TIP: These variables are stored in a "closure scope" (worth researching), // so that they'll remain available to the newly-generated function every // time it's called. var alreadyCalled = false; var result;
// TIP: We'll return a new function that delegates to the old one, but only // if it hasn't been called before. return function() { if (!alreadyCalled) { // TIP: .apply(this, arguments) is the standard way to pass on all of the // infromation from one function call to another. result = func.apply(this, arguments); alreadyCalled = true; } // The new function always returns the originally computed result. return result; }; };
arguments vs parameters
parameters are the used when constructing the function, arguments are when you pass into a function when calling it (after it has been built)
what happens when you assign a variable (var “b”) to another variable (var “a”) that is a function?
var b will equal to the function var a. (not the result of var a)
what would happen if you ran this? var fun = function(input){ console.log(input); } setTimeout( fun('hi') , 1000);
and how should i change it to call fun after 1 second? Why?
setTimeout( function(){ fun('hi'); } , 1000)
you do this because by wrapping the function within an anonymous function, setTimeout will not run the function fun immediately. if i left it as before, it would run fun immediately because the () are invoking the function.
Array.prototype.slice() var myArray = ["a","b","c","d","e"]; myArray.slice(1,4)
slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3)
returns [“b”, “c”, “d”]
different between changes made to an assigned array, vs a copy of an array
when you use array.slice()
to make a copy of an array, you are creating an entirely separate object. so even though the contents of the original array matches the content of the copy, they are entirely separate objects in memory. So if one array is [1]
and the other is [1]
, the 1s are unrelated to each other
if the arrays contain other objects (including other arrays), then the new arrays (which are still separate) will point to the same objects
this is because array.slice
creates a shallow copy of the original array. arrays contain pointers to other objects, and when an array is copied by slice
the pointer is copied, not the object to which it is pointing
so, if you have [{a: true}]
and copy it with slice, and then you do copy[0][a] = false
, and then call original[0]
you’ll get {a: false}
(edited)
so primitive types (numbers, strings, booleans, etc) are copied entirely, while objects are copied by reference
if i just assign a new var to an existing array, such as: var array = [1,"purple", false, {a: true}]; var assignedArray = array; All items are just a referenced copy (a change to the original array will make a change to the assignedArray
what would you use “in” keyword for in objects
1) to loop over the keys of an object
2) determine if there is a key in an object (returns true or false. So:
var object = {firstName: “brent”, lastName: “colson”}
“firstName” in object –> true
“fullName” in object –> false
shorthand for if/else statements
_.last = function(array, n) {
return n === undefined ? array[array.length - 1] : n > array.length ? array : array.slice(array.length - n)
};