Skip to content

Instantly share code, notes, and snippets.

@jkaihsu
Created May 9, 2013 09:48
Show Gist options
  • Save jkaihsu/5546612 to your computer and use it in GitHub Desktop.
Save jkaihsu/5546612 to your computer and use it in GitHub Desktop.

JavaScript CodeAcademy

Date: May 8, 2013


1. Intro to Javascript

confirm("I understand the terms")

- Window Popup with okay confirmation
var age = prompt("How old are you?");

- Make age equal to the answer you promp

2. Introducing Functions

Syntax

3 var divideByThree = function (number) {
4    var val = number / 3;
5    console.log(val);
6 };
7 divideByThree(6);

- Line 3 declares the function and gives it a name
- line 4 and line 5. The code within the curly brackets { } is the code we want to use again 
- Line 4 declares a variable called val. 
- Line 5 prints the value of that variable.
- line 7 Call the function

  1. Declare the function using var, and then give it a name.
  2. Then you must use the function keyword to tell the computer that you are making a function.
  3. The bit in the parentheses is called the parameter. Think of it as a placeholder word that we give a specific value when we call the function. See the hint for more.
  4. Then write your block of reusable code between { }. Every line of code in this block must end with a ;.

Return keyword

The return keyword simply gives the programmer back the value that comes out of the function. So the function runs, and when the return keyword is used, the function will immediately stop running and return the value.

Scope

Scope can be global or local

Global

Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global.

Local

Variables defined within a function are local variables. They cannot be accessed outside of the function.

Reassigning Variables

var userChoice = prompt("Do You choose rock, paper or scissors?");
var computerChoice = Math.random();

console.log(computerChoice);


if (computerChoice >0 && computerChoice <= 0.33) {
    computerChoice =  "rock";
} else if (computerChoice > 0.33 && computerChoice <= 0.66) {
     computerChoice =  "paper";       
} else {
     computerChoice =  "scissors";   
}

/

/*jshint multistr:true */

You can ignore the /*jshint... line for now. All that does is tell the console to stop worrying about our use of backslash characters for wrapping long lines of text.

Loops

for loop

for (var counter = 1; counter < 11; counter++) {
  console.log(counter);
}

Example for loop

var text = "How are you today Jkai";
var myName = "Jkai";
var hits = [];


for(var i = 0; i < text.length; i++) {
    if (text[i] == "J") {
		for(var j = i; j < (myName.length + i); j++) {
			hits.push(text[j]);
		}
	}
}
- In the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array.

while loop

As long as the condition evaluates to true, the loop will continue to run. As soon as it's false, it'll stop. (When you use a number in a condition, as we did earlier, JavaScript understands 1 to mean true and 0 to mean false.)

Syntax

var bool = true;
while(bool){
    //Do something
}

var bool = true;
while(bool){
    //Do something
}

Example 1 while loop

var understand = true;

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

Example 2 while loop

var loop = function(x){
	while(x){
        console.log("I'm looping!");
		x--;
	}
};

loop(3);

do/while loop

Example 1 do/while loop

loopCondition = false;

do {
	console.log("I'm gonna stop looping 'cause my condition is " + String(loopCondition) + "!");	
} while (loopCondition);

JavaScript Methods

Split String

var str = "How are you doing today?";
var n = str.split(" ");
> n = ["How", "are", "you", "doing", "today?"]

isNan()

Checks to see if that thing is not a number

isNaN('berry') // => true
isNaN(NaN) // => true
isNaN(undefined) // => true
isNaN(42);  // => false
isNaN("unicorns"); // => true

switch

Example 1 switch

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?");
}

logical operator

and (&&)
or (||)
not (!)

And

true && true // => true
true && false // => false
false && true // => false
false && false // => false

Or

true || true // => true
true || false // => true
false || true // => true
false || false // => false

Not

!true // => false
!false // => true

Example 1 Logical Operation

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.");
}

Objects

Object literal notation

Literal notation is just creating an object with curly braces

Objects are just collections of information (keys and values) between curly braces, like this:

var myObject = {
    key: value,
    key: value,
    key: value
};

Example 1

The key name the value 'Oxnard Montalvo' and the key number the value '(555) 555-5555'. An object is like an array in this way, except its keys can be variables and strings, not just numbers.

var phonebookEntry = {};

phonebookEntry.name = 'Oxnard Montalvo';
phonebookEntry.number = '(555) 555-5555';
phonebookEntry.phone = function() {
  console.log('Calling ' + this.name + ' at ' + this.number + '...');
};

phonebookEntry.phone();

Example 2

Create an object, me. It should have a name key with the value of your name (as a string) and an age key with the value of your age (as a number).

var me = {
    name: "Jkai",
    age: 30,
    awesome: function (){
        console.log(this.name + " is awesome!");
    }
}

Object Constructor

When you use the constructor, the syntax looks like this:

var myObj = new Object();

You can add keys to your object after you've created it in two ways:

myObj["name"] = "Charlie";
myObj.name = "Charlie";

Recreate your me object in the editor, but this time, use the object constructor.

var me = new Object();

me.age = 30;
me.name = "jkai";
me.awesome = function(){
    console.log(me.name + "is awesome");
};

Objects I

Properties

Each piece of information we include in an object is known as a property. Think of a property like a category label that belongs to some object.

When creating an object, each property has a name, followed by : and then the value of that property. 

Accessing Properties

Example

var bob = {
  name: "Bob Smith",
  age: 30
};

// here we save Bob's information
var name1 = bob.name;
var age1 = bob.age;

--or--

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

var species = dog["species"];
var weight = dog["weight"];
var age = dog["age"];

Method

We can think of properties as variables associated with an object. A method is just like a function associated with an object.

We call a method like a function, but we use ObjectName.methodName().

// here is bob again, with his usual properties
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;

// this time we have added a method, setAge
bob.setAge = function (newAge){
  bob.age = newAge;
};

bob.getYearOfBirth = function () {
  return 2012 - bob.age;
};

// here we set bob's age to 40
bob.setAge(40);

// bob's feeling old.  Use our method to set bob's age to 20
bob.setAge(20);

this

It turns out we can make a method work for many objects using a new keyword, this.** The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used.**

Example 1

When we say bob.setAge = setAge, it means

  1. when we type bob.setAge( )
  2. this.age in the setAge method will refer to bob.age.
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
  this.age = newAge;
};

// now we make bob
var bob = new Object();
bob.age = 30;

// and down here we just use the method we already made
bob.setAge = setAge;
  
// change bob's age to 50 here
bob.setAge(50);

Example 2

// here we define our method using "this", before we even introduce bob
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 = new Object();
susan.age = 25;
susan.setAge = setAge;

// here, update Susan's age to 35 using the method
susan.setAge(35);

Example 3

Note we have used the keyword this. this is still a placeholder, but in this scenario, this can only ever refer to rectangle because we defined setLength to be explicitly part of rectangle by defining it as rectangle.setLength.

var rectangle = new Object();
rectangle.length = 3;
rectangle.width = 4;

// here is our method to set the length
rectangle.setLength = function (newLength) {
  this.length = newLength;
};

// help by finishing this method
rectangle.setWidth = function (newWidth) {
    this.width = newWidth;
};
  
// here change the width to 8 and length to 6 using our new methods
rectangle.setWidth(8);
rectangle.setLength(6);

Example 4

var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
  return this.sideLength * 4;
};
// help us define an area method here
square.calcArea = function() {
    return this.sideLength * this.sideLength;
};


var p = square.calcPerimeter();
var a = square.calcArea();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment