Javascript Programming Gems
Javascript Programming Gems
Source File - This is a document written in a programming language that tells the
computer what you want it to do.
Compiler - This translates a programming language that you can understand into a
language the computer can understand, you can call it Computerese.
Library - A collection of useful code that has already been translated into
Computerese that you can use in the programs you write.
.NET Platform - A large collection of tools, languages and libraries for writing
programs with a heavy emphasis on productivity.
Sure, there's a lot more to it than that. You could tell them about IL and JIT
compiling or garbage collection but these details aren't very relevant to a non-
programmer.
***********************************************************************************
***********************************************************************************
*********************
*******************************************************************************
JAVASCRIPT
***********************************************************************************
********
***********************************************************************************
***********************************************************************************
*********************
For loop = When you know when to stop looping.
While loop = When you dont know when to stop looping. Used with true or false
instead of numbers. Condition to be checked should be defined outside the loop.
After reaching true, condition should be set to false to avoid infinite loop.
increment is done inside the loop.
As we mentioned, for loops are great for doing the same task over and over when you
know ahead of time how many times you'll have to repeat the loop. On the other
hand, while loops are ideal when you have to loop, but you don't know ahead of time
how many times you'll need to loop. However, you can combine a while loop with a
counter variable to do the same kind of work a for loop does. In these cases, it's
often a matter of preference.
// FOR loop
console.log(i);
// WHILE loop
var i = 0;
while (i<6) {
console.log(i);
i++;
// DO WHILE loop
i = 99;
do {
console.log(i)
} while (condition);
DO WHILE
Sometimes you want to make sure your loop runs at least one time no matter what.
When this is the case, you want a modified while loop called a 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.
**************************************************************
Let's go back to the analogy of computer languages being like regular spoken
languages. In English, you have nouns (which you can think of as "things") and
verbs (which you can think of as "actions"). Until now, our nouns (data, such as
numbers, strings, or variables) and verbs (functions) have been separate.
No longer!
Using objects, we can put our information and the functions that use that
information in the same place.
You can also think of objects as combinations of key-value pairs (like arrays),
only their keys don't have to be numbers like 0, 1, or 2: they can be strings and
variables.
An object is like an array in this way, except its keys can be variables and
strings, not just numbers.
Objects are just collections of information (keys and values) between curly braces,
like this:
var myObject = {
key: value,
key: value,
key: value
};
Objects allow us to represent in code real world things and entities (such as a
person or bank account). We do this by storing all relevant information in one
place�an object.
How do we create an object? Like declaring a variable, or defining a function, we
use var, followed by the name of the object and an equals sign. Each object then:
starts with {
has information inside
ends with };
age is the property, and 34 is the value of this property. When we have more than
one property, they are separated by commas. The last property does not end with a
comma.
----------------
There are two ways to create an object: using object literal notation (which is
what you just did) and using the object constructor.
Literal notation is just creating an object with curly braces, like this:
When you use the constructor, the syntax looks like this:
This tells JavaScript: "I want you to make me a new thing, and I want that thing to
be an Object.
You can add keys to your object after you've created it in two ways:
myObj["name"] = "Charlie";
myObj.name = "Charlie";
Both are correct, and the second is shorthand for the first. See how this is sort
of similar to arrays?
http://stackoverflow.com/questions/4859800/should-i-be-using-object-literals-or-
constructor-functions
OBJECTS: LITERAL NOTATION vs CONSTRUCTOR?
- Literal = Single instance
- Constructor = Multiple instances
The method we've used to create objects uses object literal notation�that is,
creating a new object with { } and defining properties within the brackets.
Another way of creating objects without using the curly brackets { } is to use the
keyword new. This is known as creating an object using a constructor.
The new keyword creates an empty object when followed by Object(). The general
syntax is:
-----------------
In the last section, we discussed properties. We can think of properties as
variables associated with an object. Similarly, a method is just like a function
associated with an object.
They can be used to change object property values. The method setAge on line 4
allows us to update bob.age.
They can be used to make calculations based on object properties. Functions can
only use parameters as an input, but methods can make calculations with object
properties.
function Person(name,age) {
this.name = name;
this.age = age;
this.species = "Homo Sapiens";
}
this.calcArea = function() {
return this.height * this.width;
};
// put our perimeter function here!
this.calcPerimeter = function() {
return 2*this.height + 2*this.width;
};
console.log(area);
console.log(perimeter);
------------------------------------------------------------------
ANOTHER CUSTOM CONSTRUCTOR WITH METHODS
function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}
rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();
------------------------------------------------------------------
console.log(family.length);
------------------------------------------------------------------
**** In addition to making arrays of Objects, we can use objects as parameters for
functions as well.
// get the difference in age between alice and billy using our function
var diff = ageDifference(alice, billy);
console.log(diff);
------------------------------------------------------------------
// Our person constructor
function Person (name, age) {
this.name = name;
this.age = age;
}
// Let's bring back alice and billy to test our new function
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);
// 3 lines required to make harry_potter OBJECT CONSTRUCTOR DOES NOT BELONG TO BOOK
CLASS
var harry_potter = new Object();
harry_potter.pages = 350;
harry_potter.author = "J.K. Rowling";
// Use our new constructor to make the_hobbit in one line BELONGS TO BOOK CLASS
var the_hobbit = new Book(320, "J.R.R. Tolkien");
-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
};
// define a perimeter method here
this.perimeter = function () {
return 2 * Math.PI * this.radius;
}
};
console.log(circle1.area());
console.log(circle1.perimeter());
------------------------------------------------------------------
var friends = {
bill: {},
steve: {}
};
Or with the bracket ([]) or dot(.) notation, like this:
friends[bill] = {};
friends.steve = {};
--------------------------------
var friends = new Object();
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "2222 3333",
address: ["Street", "1"]
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "4444 9999",
address: ["Avenue", "2"]
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "mary.johnson@example.com"
};
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]);
}
}
search("Jones");
list(contacts);
**************************************************************
Introducing Functions
Programming is similar to baking cakes. Seriously! Imagine you are trying to teach
your friend Jane how to bake many different types of cakes.
Each cake takes in different ingredients (ie. inputs). But the 'bake' instructions
are always the same. For example:
It is tedious to have to repeat to Jane the same 'bake' instructions every time.
What if we could just say 'bake' and Jane would know to execute those three steps?
That is exactly what a function is!
**************************************************************
if (number % 2 === 0) {
return true;
else {
return false;
}
};
isEven();
**************************************************************
computerChoice = "rock";
}
else if(computerChoice <= 0.67) {
computerChoice = "paper";
}
else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);
if (choice1 == choice2) {
console.log(compare(userChoice, computerChoice));
***********************************************************************************
************
var card = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"];
var suit = ["s", "c", "h", "d"];
***********************************************************************************
************
}
***********************************************************************************
************
var count = 0;
while(count<3) {
console.log("I'm looping!");
count++;
}
};
loop();
***********************************************************************************
************
How does this code work? Math.floor(Math.random() * 5 + 1);
***********************************************************************************
************
for (i=1; i<21; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
}
else if (i % 5 === 0) {
console.log("Buzz");
}
else if (i % 3 === 0) {
console.log("Fizz");
}
else console.log(i);
}
***********************************************************************************
************
var answer = prompt("Do you like fishsticks?");
switch(answer) {
case "yes":
console.log("You are a gay fish!");
break;
case "no":
console.log("Are you sure?");
break;
case "maybe":
console.log("Yes you do!");
break;
default:
console.log("Only a gay fish can't answer...");
}
***********************************************************************************
************
var movie = prompt("Which movie?");
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;
default: return("I don't know!");
}
};
getReview();
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
***********************************************************************************
*********************
***********************************************************************************
JQUERY
***********************************************************************************
*********
***********************************************************************************
***********************************************************************************
*********************
***********************************************************************************
************
Next, we'll need to start up our jQuery magic using the $(document).ready(); syntax
you've seen. It works like this:
So,
$(document).ready(something);
says: "when the HTML document is ready, do something!" (We'll show you how to
replace something with an action in the next exercise.)
Note that .ready(); ends with a semicolon. This tells jQuery that you're done
giving it a command.
------------------------------------------------------
Functions are the basic unit of action in jQuery. The main entry point of most
jQuery applications is a block of code that looks like this:
$(document).ready(function() {
Do something
});
Let's go through it bit by bit.
***********************************************************************************
************
BE CAREFUL OF THE NESTING!!! inside .ready() a function is defined function(){}
function() {
jQuery magic;
}
$(document).ready();
$(document).ready(function() {
jQuery magic;
});
***********************************************************************************
************
$p vs $('p')
$p = $ does nothing. The $ sign just says that in this variable $p there is a p
i.e. paragraph HTML selector.
$('p') = $ here is actually a function which gets passed a 'p' parameter which is a
paragraph selector.
***********************************************************************************
************
$(document).ready(function(){
$div = $("div");
$div.fadeIn("slow");
});
***********************************************************************************
************
$(document).ready((function){
$("red","pink").fadeTo("fast",1);
});
// IS THE SAME AS
$(document).ready(
(function){$("red","pink").fadeTo("fast",1);}
);
***********************************************************************************
************
The this keyword refers to the jQuery object you're currently doing something with.
$(document).ready(function() {
$('div').click(function() {
$(this).fadeOut('slow');
});
});
***********************************************************************************
************
$(document).ready(function(){
$(".pull-me").click(function(){
$(".panel").slideToggle("slow");
});
});
$(document).ready(
function(){
$(".pull-me").click(
function(){
$(".panel").slideToggle("slow");
}
);
}
);
***********************************************************************************
************
$(".info").append("<p>Stuff!</p>");
IS THE SAME AS
$('<p>Stuff!</p>').appendTo('.info');
***********************************************************************************
************
$(document).ready(function(){
// THIS IS ALSO VALID
/*-$body = $("body");
$paragraph = "<p>I am a paragraph</p>";
$body.append($paragraph);*/
$("body").append("<p>I am a paragraph</p>");
});
***********************************************************************************
************
.empty() deletes an element's content and all its descendants. For instance, if you
.empty() an 'ol', you'll also remove all its 'li's and their text.
.remove(), not only deletes an element's content, but deletes the element itself.
***********************************************************************************
************
$(document).ready(function(){
$("#text").addClass("highlighted");
});
***********************************************************************************
************
jQuery includes a .toggleClass() function that does exactly this.
If the element it's called on has the class it receives as an input, .toggleClass()
removes that class;
if the target element doesn't have that class, .toggleClass() adds it.
***********************************************************************************
************
$("div").height("100px");
$("div").width("50px");
$("div").css("background-color","#008800");
$(document).ready(function(){
$div = $("div");
$div.height(200);
$div.width(200);
$div.css("border-radius", 10);
});
***********************************************************************************
************
Finally, we can update the contents of our HTML elements�that is, the bit between
the opening and closing tags�using the .html() and .val() functions.
<div>CONTENT</div>
.html() can be used to set the contents of the first element match it finds. For
instance,
$('div').html();
will get the HTML contents of the first div it finds, and
$('input:checkbox:checked').val();
would get the value of the first checked checkbox that jQuery finds.
***********************************************************************************
************
You can set a variable equal to the contents of the input field using .val(), like
so:
1. Our selector finds our specific input using a css selector on our checkListItem
input
2. We call val() to get the value of the field
$(document).ready(function(){
$button = $("#button");
$button.click(function(){
var toAdd = $("input[name=checkListItem]").val();
$list = $(".list");
$appendix = '<div class="item">' + toAdd + '</div>' // ' vs " is important
here; also don't put it in () out of habit.
$list.append($appendix);
});
});
***********************************************************************************
************
Remove What's Been Clicked
Great job! Finally, we want to be able to check items off our list.
$('.item').click(function() {
$(this).remove();
});
and that's not a bad idea. The problem is that it won't work�jQuery looks for all
the .items when the DOM is loaded, so by the time your document is ready, it's
already decided there are no .items to .remove(), and your code won't work.
For this, we'll need a new event handler: .on(). You can think of .on() as a
general handler that takes the event, its selector, and an action as inputs. The
syntax looks like this:
***********************************************************************************
************
$(document).ready(function(){
$("#button").click(function(){
var toAdd = $("input[name=checkListItem]").val();
$(".list").append('<div class="item">' + toAdd + '</div>'); // ' vs " is
important here; also don't put it in () out of habit.
});
$(document).on("click", ".item", function(){ // .on is a custom handler
$(this).remove(); // notice the usage of this here.
});
});
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
************
***********************************************************************************
************