Programming is the art of solving very complex problems or processes by breaking each problem into tiny, solvable pieces.
One of the tools that helps us break down problems is the if/else decision structure. Think of the logic behind a simple switch, like a light switch or turning something on or off. In code we can create logic that says,
if one thing happens, do this. Otherwise, do this other thing
In fact, the javascript code for creating these decision structures reads almost like our sentence did:
if(one thing is true) {
do this
} else {
do this other thing
}
Don't mind all those curly brackets and parentheses so much right now, they will become second nature in no time.
Consider what is going on in the following example. The first if statement will create a popup box with the message "I'm running", but the second if statement won't do anything, because the if condition in parentheses must be true in order to run the logic inside.
if(true) {
alert("I'm running!");
}
if(false) {
alert("I'm running");
}
If statements might seem too simple to use in real applications. But take a look at the code below, can you follow what it is doing?
if(credentialsValidator(userId, password) === true) {
alert("Credentials accepted");
}
if(credentialsValidator(userId, password) === false) {
alert("Credentials are not valid");
}
The code above runs a function that takes in a userId and password, and returns whether or not the credentials are valid. It just goes to show how if statements will show up in even very complex programs.
If statements allow us to perform an action only when a certain condition is true. But what if we want to handle more possibilities than that?
If we want to trigger one action when a condition is true, and another when the condition is false, we can use the "else" block:
var a = true;
if(a) {
alert("a is true");
} else {
alert("a is false");
}
Notice that the else block doesn't specify a condition in parentheses like if does. This is because the else is simply what happens if the condition specified in the "if" part is false. You can have an "if" statement by itself, but not an else.
With "if" and "else", we can specify two actions - the first is what should happen if something is true, the second is what should happen if the condition is false. But what if we need a third option?
Here is an example:
var number = 40
if(number > 50) {
console.log("The number is greater than 50")
} else if(number < 50) {
console.log("The number is less than 50")
} else {
console.log("The number is 50")
}
A function is a set of instructions detailing how to do a task. We can use the instructions to build something over and over again, in the same way that one blueprint can be used many times to build many buildings.
This means there is a difference between creating or 'declaring' a function (creating the instructions), and running the function (following the instructions to perform a task). When we 'call' or 'run' a function, it means we go through that set of instructions and do the task.
For example, look at this function declaration:
function name: make_a_sandwich
// 1. Decide on the inner ingredients ( bacon, lettuce, tomato etc...)
// 2. Wrap the inner ingredients in bread
// 3. Put on plate
// 4. Serve sandwich
Great! We have a function. But -- no sandwich. Now, we need to follow our instructions to make a sandwich, all we have to do is say:
make_a_sandwich()
The above is a function 'call'. Notice that we used the same name that we gave when we declared the function. Calling the function by its name will tell the program to run through the steps declared in the make_a_sandwich function, which gets us a sandwich.
This brings us to the important bits about functions. Take a look at the two rules of functions:
Functions often require some information in order to run (in the case of our make_a_sandwich function, it needs to know what kind of sandwhich to make). Pieces of outside information that are used when a function runs are called 'arguments' to that function.
Functions must return something. In other words, a function that does some calculation or other work but never gives you back new information isn't very useful.
Remember that functions have to be very explicit about how to do things, because computers can only follow the instructions.
There are two things that are hard about writing functions. The first thing is deciding exactly what your function needs to do, and the second hard thing is figuring out the code that will make that happen.
Since both of those things are hard in the first place, it is really confusing to try and do both at once. So, it is common practice to write what we call pseudo code, which isn't actually code at all, just normal words.
Writing pseudo code is a really good mental habit to get into, because it breaks up the hard parts about writing functions into two separate stages. It goes like this:
Write out all the logical steps of what you need to do -- no code allowed
Turn those logical steps into actual code
This is great, because it means that while you are thinking up your logic, you aren't distracted by how to write it in code. And conversely, when you are writing code, you aren't also trying to think of what comes next.
This is an example of using pseudo code:
// TODO: Create a function that takes in a number between 1 & 10 (call this number: userNumber) and gives back a new, hard to guess number
// 1. multiply the number by itself
// 2. add 42
// 3. multiply by .3
// 4. return the result
Once we've decided what we need to do, it isn't so hard to create the code that does each of those things, we just tackle them step by step:
function create_a_secret_number(userNumber) {
// 1. multiply the number by itself
var secretNumber = userNumber * userNumber
// 2. add 42
secretNumber = secretNumber + 42
// 3. multiply by .3
secretNumber = secretNumber * .3
// 4. return the result
return secretNumber
}
The only thing to do now is verify that our function actually works! Run all the examples and fix any bugs.
This is another way that pseudo code will really help you out. If you have separated the logic from the code syntax, it is easier to see if the bug you found is a logic problem or a syntax problem.
With the above implementation create_a_secret_number(4)
returns "17.4". Not too bad!! Now that we have it working, we can figure out how to make it better. For instance, we probably want to do something about that decimal number later. How would you make this function better?
Node.js has a command line interface that allows us to run files, and run
code directly from the terminal. Lets create an application that prints
out the current date.
// ./today.js
const today = new Date()
console.log("Today is", today)
Once we save our program, we can use Node.js to run our program
$ node today.js
Today is 2017-01-28T21:28:10.001Z
Now were starting to see how powerful Node.js is, and how we can use it to
build full stack applications. Netflix, the New York Times, PayPal,
LinkedIn, and Uber use Node.js in exactly this same way to run their web
applications, serving millions upon millions of pages each day.
This section shows you some of the operators and syntax of Javascript and their uses.
There are
Primitives
We can perform mathematical calculations with numbers in JavaScript just like we can with pen and paper or a calculator. Some of these operators, like %
might look unfamiliar but are very useful. For example, %
lets us find the remainder of a division operation.
1 -> 1
1.0 -> 1
2+2 -> 4
2-2 -> 0
2*2 -> 4
2/2 -> 1
2%2 -> 0
3%2 -> 1
0.1+0.2 -> 0.300000000004
2/0 -> Infinity
-2/0 -> -Infinity
Infinity + -Infinity -> NaN
We can compare values in JavaScript using the following operators. These operations return either a true
or false
value:
2 > 0 -> true
0 >= 2 -> false
2 != 0 -> true
2 === 0 -> false
Boolean expressions in JavaScript return true
or false
values like the following:
true -> true
false -> false
!true -> false
!false -> true
true === false -> false
true == false -> false
true != false -> true
true != true -> false
!(true === false) -> true
true || false -> true // || is pronounced "or"
false || false -> false
true && false -> false // && is pronouced "and"
true && true -> true
We can make strings in JavaScript by surrounding characters with quotation marks:
"hell" + "o" -> "hello"
"he'" + "ll" -> "he'll"
'he said: "hello"' -> "he said: "hello""
In JavaScript, there are many built-in functions and methods that can be performed on strings to do some pretty cool things:
"hello".charAt(1) -> "e";
"hello".length -> 5
"hello".includes("hell") -> true
JavaScript is a language that does what we call "type coercion", which means if we try to combine data types in an operation it will helpfully try to make sense of the operation anyway. This can lead to strange and unpredictable behavior:
"2" + 2 -> 22
2 + "2" -> 22
parseInt("2") -> 2
parseInt("2") + 2 -> 4
true * 9 -> 9
false * 9 -> 0
Variables allow us to store and reuse information across operations.
Always, always, always use var
; otherwise the identifier becomes a global variable.
var a;
a -> undefined // undefined is the value a variable has before we assign it a value
a + a; -> NaN // using undefined in a calculation does NOT give an error
a = 2;
a; -> 2
3 + a; -> 5
a * a; -> 4
a = "hello"
a + a; -> "hellohello"
a = null; // null is a special value that represents that we do not have a value
a; -> null
a + a; -> 0 // using null in a calculation does NOT give an error
In JavaScript, functions are a way to define and store a set operation once so that we can perform it later without having to retype all of the attached logic:
function addOne(a) { return a+1; }
addOne(1); -> 2
function add(a, b) { return a+b; }
add(1, 2); -> 3
add("1", "2"); -> 12
add(1, add(2,3)); -> 6
function isAdult(age) { return age >= 18; }
isAdult(17); -> false
isAdult(21); -> true
function greet() { return "Hello"; } // defining a function that takes no parameters
greet; -> function greet() { return "Hello"; } // return the function itself
greet(); -> "Hello" // return the result of running the function
We have gone over most of the building blocks that compose a javascript program. No matter how complex a project you work on, the pieces you use to build it will still be the same variables, data types, if statements and functions.
Here are a few exercises for you to practice using variables:
What is your favorite number divided by 2?
Set another variable called someones_favorite equal to 13
Javascript comes with some built in ways to work with Strings. For this exercise, try out some of the string methods for yourself.
Locate
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
What do you get back when you run this indexOf method on a string?
What happens with this method if a word occurs twice in a string?
Can you run this method on data types other than string?
You can call a method on a string by typing str.length (just like we did with indexOf above). Create a variable to hold a string and call .length on it to see what happens.
What is returned by the .length method?
What if there are spaces in the string?
Can you call this method on other data types?
Add, subtract, multiply and divide some numbers (any combination of numbers)
Find the remainder of dividing two numbers using the modulo operator (%)
Divide a number by 0
Write a function named greaterNum that:
Write a function named helloWorld that:
Write a function named assignGrade that:
Write a function named pluralize that:
pluralizer(5, cat)
should return "5 cats"
pluralizer(1, dog)
should return "1 dog" because the number one does not require a plural noun
Today's Tentative Schedule
9:15am - Stand Up
9:30am - Introduction to Javascript: Primatives, Variables, Functions, alert, prompt, console.log followed by challenges
11:30am - Live Coding Demo: User/Password Checker
12:00 noon - Lunch
1pm - Challenge: Password Checker Challenge
4.30pm - Review
5pm - Class Ends