On Github Devbootcamp / intro-to-javascript
Brought to you by Dev Bootcamp
Some "rules" for today:
Let's get to know each other!
A web browser with great JavaScript development tools.
A powerful but user-friendly text editor.
A JavaScript library that makes it easier for us to interact with webpages.
Google search and autocomplete will quickly become your best friend
Your ultimate goal is a super fast feedback loop.
Scan through the Google search results and work out which look most relevant to your issue.
Cmd+Click (Mac) or Ctrl+Click a link to open it in a new tab. Open what you think are the three most promising results.
In my experience, I've found the following resources to be particularly helpful:
A quick note on Stack Overflow...
Always remember that the section right at the top of the page is the question, not the answer!
A bunch of jargon:
What does it all mean!?
A variable is a way of naming things so we have a reference to them later.
Think of variables as a label we can write on and apply to different things.
Let's come back to variables once we learn about a few different data types we can label.
A string is simply a sequence of characters. In fact, this sentence itself could be a string. This is what it would look like in JavaScript:
"In fact, this sentence itself could be a string."
Strings can vary greatly in length, from entire novels...
"Well, Prince, so Genoa and Lucca are now just family estates of the Buonapartes. But I warn you, if you don't tell me that this means war, if you still try to defend the infamies and horrors perpetrated by that Antichrist—I really believe he is Antichrist—I will have nothing more to do with you and you are no longer my friend, no longer my 'faithful slave,' as you call yourself! But how do you do? I see I have frightened you—sit down and tell me all the news..."
...to single words...
"hello"
...to nothing at all.
""
(this is known as an empty string)
Strings can contain numbers and don't have to make sense at all:
"9m52bqu4239wl"
The syntax for creating strings in JavaScript is to wrap any number of characters in single or double quotes.
"This is a string." 'This is also a string.'
Open up your handy dandy JavaScript console by pressing Cmd+Opt+J on Mac or Ctrl+Shift+J on other systems.
If you want to clear out the cruft in the console press Cmd+K (Mac) or Ctrl+L (PC). What happens when you type in a string with quote marks and press enter? What happens if you type those same characters in without quote marks and press enter? What happens when you add two strings together with the plus symbol?Strings are one of the most common data types in every programming language. Get used to seeing, using and manipulating strings!
Numbers are another common data type that you will see and use in the wild.
The syntax for numbers in JavaScript is fairly intuitive.
42 3.14 100 10000
You can perform simple arithmetic on numbers using:
Addition + Subtraction - Multiplication * Division / Modulus % Increment ++ Decrement --You can also perform simple comparison operations on numbers using:
Equality === Inequality !== Greater than > Greater than or equal to >= Less than < Less than or equal to <=Open up your handy dandy JavaScript console by pressing Cmd+Opt+J on Mac or Ctrl+Shift+J on other systems.
What happens if you try to add a number to a string? What does the modulus operator do?Every time you press enter in the JavaScript console, you see the return value of expression you evaluated.
What data type did JavaScript return when you used a comparison operator?
Comparison operators will always return a
Boolean
true or false
Now we know how to create a few data types, let's save them for later in some variables.
The syntax for declaring a variable in JavaScript is like this:
var magicNumber = 42;
var // is a reserved word used to declare a local variable magicNumber // is the variable name = // is the assignment operator 42 // is the value assigned to the variable ; // signifies the end of a statement in JavaScript
Naming variables in camelCase is a JavaScript convention.
You can directly assign values to variables...
var seenIt = "...like we've already seen";
...or store return values of expressions in variables
var num = 3; var otherNum = 4; var multiplier = 6; var answerToTheUltimateQuestion = (num + otherNum) * multiplier;What value is stored in answerToTheUltimateQuestion?
Let's look at two more data structures:
For the following data structures, we are going to learn how to create, or instantiate, them and then learn the following operations:
Just like a variable holds a single value, an array holds a collection of values.
Think of an array as a bunch of buckets, each of which stores a value.
If we were to put the first eight characters of the alphabet into these buckets, it would look like this in JavaScript:
var letters = ["a","b","c","d","e","f","g","h"];
An array of the characters "a" through "h" is now stored in the variable `letters`. This is an array of strings.
Every element in an array is stored in a specific position known as an index. Arrays are indexed starting at 0 and incrementing by 1 for each position.
0 1 2 3 4 5 6 7 "a" "b" "c" "d" "e" "f" "g" "h"You refer to each element by its index.
var letters = ["a","b","c","d","e","f","g","h"]; letters[0] // -> "a" letters[7] // -> "h"
var letters = ["a","b","c","d","e","f","g","h"]; letters[0] = "apples" // -> "apples" letters[1] = "oranges" // -> "oranges" letters // -> ["apples","oranges","c","d","e","f","g","h"]
var letters = ["a","b","c","d"]; letters.push("elephant") // -> "elephant" letters // -> ["a","b","c","d","elephant"]
The push function adds an element to the end of an array.
var letters = ["a","b","c","d", "elephant"]; letters.unshift("zebra") // -> "zebra" letters // -> ["zebra","a","b","c","d", "elephant"]
The unshift function adds an element to the start of an array.
What element is in index zero of the array now?var letters = ["a","b","c","d"]; var char = letters.pop() // -> "d" letters // -> ["a","b","c"]
The pop function removes an element from the end of an array.
What element is in index zero of the array now?var letters = ["a","b","c","d"]; var char = letters.shift() // -> "a" letters // -> ["b","c", "d"]
The shift function removes an element from the start of an array.
What element is in index zero of the array now?All data types in JavaScript come with some built in behavior called functions. We've already seen a few array functions with push, pop, shift and unshift.
var letters = ["a","b","c"]; letters.push("d"); // -------------------------- letters // the array that we're calling our function on . // the dot to signify we're about to call a function push // the name of the function ("d") // the actual calling of the function with a string argument
We call a function with a dot, followed by the function name, followed by a set of parentheses. Sometimes we put other data inside the parens, known as arguments; other times functions don't require arguments.
Things in JavaScript can also have properties. You access and modify properties similarly to functions, except you do not include the parentheses.
var fruits = ["apple","banana","carrot"]; fruits.length // -> 3 fruits[2].length // -> 6 fruits.push("d"); fruits.length // -> 4
length is a good example of a property on both arrays and strings. Note how properties don't need parentheses after them.
It can be very confusing to know whether something is a function or an property when you start out with JavaScript. It's something you'll get used to.
Remember you always have the Web to look things up!
Objects in JavaScript are similar to arrays in that they contain a collection of values.
However, unlike array values which are accessed and ordered by index, the values in objects are known as properties are accessed via property names
In our metaphor we give each bucket a name. This is the property name. The item inside the bucket is its value. So, a JavaScript object is a collection of named properties which work like key value pairs.
If this collection of buckets was an object, what do you think it would represent?Let's instantiate an object in JavaScript:
var person = {name: "Sam", age: 28, sex: "male"};
This object contains three properties and the object is stored in the variable `person`.
What data types are the values in this object?var person = {name: "Sam", age: 28, sex: "male"}; person.name // -> "Sam" person["name"] // -> "Sam"
var person = {name: "Sam", age: 28, sex: "male"}; person.age = 29 // -> 29 person // now contains {name: "Sam", age: 29, sex: "male"} person.age // -> 29
var person = {name: "Sam", age: 28, sex: "male"}; person.gender = "cis male" // -> "cis male" person // now contains {name: "Sam", age: 28, sex: "male", gender: "cis male"}
var person = {name: "Sam", age: 28, sex: "male", gender: "cis male"} delete person.sex // -> true person // now contains {name: "Sam", age: 28, gender: "cis male"} person.sex // -> undefined
The delete operator removes a key value pair from an object.
Why did I not call `delete` a function? It's relatively rare to use `delete`. Most often you are reading or accessing data. Second most, adding or inserting data. Third most, updating data. Rarely, deleting or removing data.We've been using dot notation when working with objects.
var person = {name: "Sam", age: 28, gender: "cis male"} person.name person.age person.gender
What type of thing does that suggest `name`, `age`, and `gender` are?
properties
So what we generically call keys are specifically called properties in JavaScript objects.
Also, these things we call objects in JavaScript can be called dictionaries, hashes, hash tables, or maps in other languages.
With your neighbor, model the following using the data types and structures you just learned:
What is the best way to do this?
Enter your data structure into the console and work through any errors.
Doing certain things over and over and over and over is a very common thing when coding
We will look at the syntax for two JavaScript loops:
This is the syntax for a while loop.
var counter = 1; while (counter <= 10) { console.log("I'm counting in multiples of five!"); console.log("Here's what's next: " + counter * 5) counter++ }
Here's the same operation using a for loop.
for (var counter = 1; counter <= 10; counter++) { console.log("I'm counting in multiples of five!"); console.log("Here's what's next: " + counter * 5) }
Compare the two:
var counter = 1; while (counter <= 10) { console.log("I'm counting in multiples of five!"); console.log("Here's what's next: " + counter * 5) counter++ } // ------------------------------------------------- for (var counter = 1; counter <= 10; counter++) { console.log("I'm counting in multiples of five!"); console.log("Here's what's next: " + counter * 5) }
Be careful not to code a loop that will never end. It will cause your browser to freeze and crash!
// Don't run the following code! var counter = 1; while (counter <= 10) { console.log("I'm counting in multiples of five!"); console.log("Here's what's next: " + counter * 5) }
This is called an infinite loop. Can you see why it never ends?
Here's a fun game with a while loop.
var secretPhrase = "bananas" var userInput while (userInput !== secretPhrase) { userInput = prompt("Haha! You will continue to get this annoying\ pop up until you guess the secret phrase!") } alert("Drat! You guessed it!")
The most common use of loops is to loop over collections. We loop over collections when we want to do something with every element in a collection.
Here's a for loop looping over and printing out every element in our letters array:
var letters = ["a","b","c","d","e","f","g","h"]; for (var i = 0; i < letters.length; i++) { console.log(letters[i]); }
There's a lot going on here. So let's talk through it.
Open up your handy dandy JavaScript console by pressing Cmd+Opt+J on Mac or Ctrl+Shift+J on other systems.
Try looping over the list of people you made in our last breakout sesssion and printing out everyone's name AND their age... You can paste your data structure into the console, or you can write your loop in the file on your desktop.Sometimes you want your code to do different things depending on different inputs. This is called control flow.
Maybe you need to check someone's age before you let them use your program:
var age = prompt("How old are you?"); if (age >= 18) { alert("Welcome to this program!") } else { alert("Sorry, you must be 18 or over to use this program.") }
if // reserved word to start a condtional (age >= 18) // the "condition" {} // the "code block" to run if the condition is true else // reserved word at the end of a conditional {} // the code block to run if all conditions are false
A function is a selection of code that you can save and run later, potentially multiple times.
We define a function like this:
var createGreeting = function(name) { return "Welcome to my website, " + name; }
The code is now stored in the variable `createGreeting`. Now we can call this the createGreeting function.
We call a function by typing its name, followed by parentheses.
var createGreeting = function(name) { return "Welcome to my website, " + name; } createGreeting("Sam") // -> "Welcome to my website, Sam" createGreeting("Debbie") // -> "Welcome to my website, Debbie" createGreeting("Britney") // -> "Welcome to my website, Britney" alert(createGreeting("Stranger"))
Functions allow us to input some data and output other data.
The input that we give to functions are called arguments.
var sum = function(num1, num2) {}
`num1` and `num2` are the parameters in this function that show us that we can pass it two arguments.
The output from a function is its return value.
var sum = function(num1, num2) { var result = num1 + num2; return result; }
Usually we manipulate our input in some useful way and then return that data.
Note as in this example, a function can have multiple parameters. These parameters act as variables within the function and any arguments you pass to this function when you call it will be accessible inside those variables/parameters.Functions don't actually need parameters or a return statement. Here's an example:
var woohoo = function() { alert("WOOHOO!"); }
Open up your handy dandy JavaScript console by pressing Cmd+Opt+J on Mac or Ctrl+Shift+J on other systems.
Build a "triangle checker" function in your console.A JavaScript library that makes it easier for us to interact with webpages.
In the index.html file, you'll see a <script> element linking to a copy of the jQuery in the same folder. This is one way to include jQuery on your page.
You'll also see a <script> element that is commented out. This is another way of including jQuery: by linking to an external source.
We are going to be playing with the HTML elements on our page. To do that, we first need to select those elements using jQuery.
The syntax for selecting elements with jQuery is:
$("div")
This will select all of the div elements on the page.
You can use any CSS selection syntax with jQuery:
// to select all paragraph elements: $("p") // to select all elements with the class 'shadow': $(".shadow") // to select the element with the id 'main-container': $("#main-container")
Just remember to wrap your selector in quote marks to make it a string.
Once we have selected elements, we can call jQuery functions on those elements:
$("p").css("background-color", "aqua");
This selects all paragraphs and then turns their background colors aqua!
Open up your handy dandy JavaScript console by pressing Cmd+Opt+J on Mac or Ctrl+Shift+J on other systems.
Make sure you open it up on the index.html page that has jQuery loaded!
Interacting with a website through clicks and keystrokes really brings JavaScript (and websites) to life!
Let's learn how to tell certain elements on our page to listen for a click event.
First we need to select an element. Let's select our button:
$("#load-tweets-button")
Now we need to bind a click event to our button:
$("#load-tweets-button").click(function() { alert("Button clicked!"); })
What this says is: 'whenever this thing I have selected is clicked, run the code in this function'.
One very common thing to do when a button is clicked is to update something else on the page.
$("#load-tweets-button").click(function() { // your code here that updates something else on the page, maybe: $("p").css("background-color", "aqua"); })
Now whenever you click the button, all the paragraphs will turn aqua!
Here's one more super helpful jQuery function called `append`:
$("#main-container").append("
A friendly paragraph!
")The append function will append whatever HTML string you pass it as an argument to the element(s) you originally selected.
Remember, you can add things to strings like this:
var dataFromSomewhere = "A friendly paragraph!" $("#main-container").append("
" + dataFromSomewhere + "
")This is called string concatenation.
You now have all the tools to dynamically create a webpage! It might strain your brain, but it's time to put everything we learnt into practice.
Task: when you click the button all of the tweets will appear in new paragraphs on the page.
You will need to use: