CS 105

Week 2, Part 2

MP1

Your first MP using JavaScript

Available on CS 105 Website
Due: Tuesday, Feb. 10, 8:00pm

Activity 2

Released: Later Today

Due: Monday, Feb. 9, 9:00am

Statements

console.log("Hello, world!");

Variables

var money = 100;
money = money - 60;
console.log(money);

What is written to the console?

A) 100
B) 60
C) 40
D) money

Numbers

If you are using a number (65, -32, 194) and want to do math on it, never use quotes.


Strings

If you are using anything that contains a letter, you must use quotes to represent it as a String.

Numbers

var money = 100;
var tempInAlaska = -32.4;
var todaysMonth = 2;

Strings

var moneyString = "$100.00";
var temp = "32.4 degrees";
var todaysMonthString = "Feb.";

Conditionals

if (money < 100) {
   eatDormFood();
} else {
   eatChipotle();
}

Less Than

if (x < 10)

Greater Than

if (x > 10)

Less Than or Equal

if (x <= 10)

Greater Than or Equal

if (x >= 10)

Equal

if (x == 10)

Not Equal

if (x != 10)

Incorrect

if (x = 10)

A single equals is an assignment. It sets the value of x to 10.

A single equal does not compare two values.

var a = 20;
a = a + 10;
var b = 10;
b = a + b;

if (a > b) { console.log("A"); }
else if (b > a) { console.log("B"); }
else { console.log("AB"); }
A) A
B) B
C) AB
D) (nothing)

Functions

Every time you use a (, you are starting to call a function!

console.log("Hello");

console.log is just a variable!

Defining a Functions

You define a function by creating a variable and assigning it the value of a function.

var printHello = function() {
  console.log("Hello");
}
printHello();

Try it!

Function Parameters

Functions can take in values to use while running the function, called function parameters.

var sum = function(a, b) {
  var c = a + b;
  console.log(c);
}
sum(10, 5);

Try it!

Function Parameters

Functions parameters listed inside of the parenthesis of a function is only time that a var is not needed.

Return Values

Often we want functions to do some work and give us back a result. Functions can return a variable back to the caller by using return.

var sum = function(a, b) {
  var c = a + b;
  return c;
}
var c = sum(10, 5);
var d = sum(c, 10);
console.log(d);
var sum = function(a, b) {
  var c = a + b;
  return c;
}
var c = sum(10, 5);
var d = sum(c, 10);
console.log(d);
A) 10
B) 15
C) 20
D) 25

Plain Text Editor

We will begin to work through files on your computer rather than on the web! To do so, you must use a plain text editor.

As a general rule, if you can make text bold it is not a plain text editor!

NOT Microsoft Word
NOT Writer
NOT TextEdit

Plain Text Editor

Windows: CS 105 recommends Notepad++

OS X: CS 105 recommends TextWrangler

Lecture Download

Download here!

Example #1

Calculate the final price of the item if a 40% discount should be applied to the original price.

Example #2

Calculate the final price of the item if a 40% discount should be applied to the original price only if the item is over $20.00.