Intro to JavaScript


	// Tell your computer how to do something
	function helloWorld(){
		var name = "GDI";
		alert("Hello world, it's " + name + "!");
	}

	// Then make it do that thing!
	helloWorld();

Welcome!

Girl Develop It is here to provide affordable programs to learn coding in a judgement-free environment through mentorship and hands-on instruction.

One Rule: Every question is important!

Course Overview

Part 1

Introduction and Fundamentals

Getting set up Data types, operators, conditionals, and variables

Let's Get Introduced!

  • Who are you?
  • What is your favorite children's book?
  • Have you ever taken Algebra?

 Algebra: Using symbols and rules to solve math equations

	x = 1 and y = 3

	x + y = z

	z = ?

x, y, and z are variables

x + y = z is an equation

Program

  • Instructions telling the computer what to do
  • Written in shorthand language = code
  • Computer reads code, interprets it, and follows instructions
  • Computers read left to right, top to bottom
  • Finishes each command before going on to the next

	1 + 2

	// 3 Computer does the brain parts for you!

	x + y

Let's Get Introduced -- to JS!

What is JavaScript?

  • Scripting language Writing commands (x + y) that tell your browser to do actions Versus Declarative language like CSS that describes appearance
  • Computers are a Client-Server relationship Servers store, process, and send information. Scripted Clients display information (Browsers are Clients). Declarative
  • JS was written to fill a need for Browser scripting
  • Called "the language of the web" - for a reason!
  • JS was later adapted to also run on the Server side

---

"JavaScript can be connected to the objects of its environment (client or server) to provide programmatic control over them."

History of JS

  • 1995: At Netscape, Brendan Eich created "Mocha" in only 10 days!
  • That same year, Mocha is renamed "JavaScript"
  • 1997: Standardized by the ECMA as "ECMAScript"
  • 1998-2003: Various battles between browser vendors about adoption! IE boooo
  • 2005-2006: AJAX gets popular, jQuery 1.0 released
  • 2010: Node.JS released. Now it's server-side!
  • 2014-2015: Rise of "Client-side MVC frameworks"- server-side techniques in the browser
  • 2016: Newest ECMAScript spec (ES6) changes a lot! (But more advanced than this class)

Getting Set Up

  1. Introduction to Browser Developer Tools
  2. Running commands in the console

Let's Develop It!

Let's write your first JavaScript program!

  1. Open Browser Dev Tools
  2. Click on the `Console` tab
  3. Type in the following command:

	alert('Hello World!');
					
What action resulted?

---

Ask questions!

Basics of Programming

  • Variables
  • Data Types
  • Commands

Variables

Variables represent information

	x = 1
	x + 2 =
  • Declared (created) using the word var
    	var x = 1
    
  • When first declared, it does not have a value (it is undefined).
  • Once given a starting value, it is no longer undefined. This is called initializing the variable.

	var a; // declared but undefined
	var a = "Aardvark"; // declared and initialized
	var b;
	b = "Bonobo"; // var isn't needed a second time
					

Naming Variables

  • Case-sensitive: ohio != Ohio != OHIO
  • Must be unique
  • Must start with a letter, $, or _
    • $ is used by the jQuery library
    • _ is used by the underscore.js library
    • Best just to start with a letter
  • Best practice for multiple-word variables is to use camelCase:
    • var thisIsMyVariable;
    • Start with lowercase letter, then capitalize other words

Using a Variable

Once you have declared a variable, you can use it in your code. Just type the name of the variable.


	var numberOfKittens = 5;
	numberOfKittens;
					
  • The value of a variable can change (be updated) later (don't need to re-use var).
  • 
    	numberOfKittens = 13;
    	numberOfKittens;
    					

    Let's Develop It!

    1. In your console, create a new variable for the number of puppies.
    2. Create a variable for the total number of pets.
    3. Using variables, set the number of pets equal to the number of kittens plus the number of puppies.

    Next, try this one:

    
    		var kittenTitle = 'Admiral';
    		var kittenName = kittenTitle + ' Snuggles';
    		kittenName;
    						

    Those aren't numbers! What did you get?

    You're so fancy

    Break Time

    
    	// The kitten got a demotion :-( Set his title to "Captain"
    
    	kittenName;
    	// What is the output of kittenName now? Why?
    					

    Data Types

    Numbers
    Integers 0, 1, 2 ... 9
    Floats (decimals) 0.5, 1.618, 3.14
    Strings "GDI", 'rock on', "three"
    Boolean true or false
    Null null
    Undefined undefined
    Arrays Next class!
    Objects Next class!

    Operators

    + Addition
    - Subtraction
    ++ Increment (+1)
    -- Decrement (-1)
    * Multiplication
    / Division
    % Modulus (remainder)

    Comparators

    ! Is Not
    == Equality
    != Inequality
    === Identity/strictly equal
    !== Non-identity
    > Greater than
    >= Greater or equal
    < Less than
    <= Less or equal

    Let's Develop It!

    Experiment with Data Types,
    Operators and Comparators

    • Open Chrome Dev Tools
    • Click on the `Console` tab
    • Play around!
    
    	3.2 - 4
    	"GDI" + "Cbus"
    	6 * "six";
    	( 2 + 3 ) - ( 4 * 12 )
    	9 / 2
    	9 % 2
    	"GDI" == "gdi"
    	14 >= 14
    					

    Try your own! Find any interesting results?

    Writing Basics

    Statements

    Each instruction in JS is called a statement, like:

    1 + 1; // One whole statement

    After each individual statement, you must add a semicolon to end the command.

    
    	1 + 1                   // wrong!
    	"Turtle" + " sadface";  // right
    						
    If it's left off, it's up to the browser to decide what you meant. Could result in broken code.

    Statements

    Statements can take up more than one line

    
    	var rhyme = "Oh, if you’re a bird, be an early bird " +
    							"And catch the worm for your breakfast plate. " +
    							"If you’re a bird, be an early early bird— " +
    							"But if you’re a worm, sleep late. ";
    
    	var poet = "Shel Silverstein";
    					

    Make it talk to you

    
    	// Open a popup box:
    	alert('Hello World!');
    	alert(2015 / 746);
    
    	// Display a message in your console:
    	console.log('Hello World!');
    	console.log(14++);
    
    	// Add something to the page:
    	document.write('Hello World!');
    	document.write("kittens" == "kittens");
    					

    Comments

    You can leave comments in your code that won't be processed in the script.

    
    	// I can wrap long comments
    	// with multiple lines
    	// like this
    	console.log('Hello World!'); // Or short like this
    					

    Comments act as notes that people can read and computers will ignore.

    
    	// This code multiplies puppies by kitties
    	var puppies = 10;
    	var kitties = 11;
    	document.write(puppies * kitties);
    					

    Class 1 Homework

      Review Javascript Fundamentals 1-11 https://javascript.info/first-steps
    • If you want to look ahead, next time we'll be talking about arrays, objects, loops, and functions.
    • Check out some browser-based JS tools like Codepen, jsbin or jsfiddle
    • Bring any questions you think of to next class
    Remember:
    Every question is important!

    Class 2 Slides

    Working with JavaScript

    Arrays, Objects, Functions

    Class 1 Review

    Did you find anything interesting about JS since last time?

    • Data Types - Which can you remember?
    • Operators
    • Comparators
      == vs ===
    • Variables
      var students = "Javascript stars!";

    Arrays

    
     var arrayOfThings = [thing0, thing1, thing2, thing3];
    					
    • Arrays are collections of values saved in order
    • Wrapped by square brackets []
    • Location of a value is called its index
    • 0-based: count starts at 0, not 1
    • "The value of arrayOfThings at index 0 is thing0"
    • You can put different types of data into an array
    
     var colors = ['Red','Orange','Yellow','Green','Blue','Indigo','Violet'];
     var lotteryNumbers = [33, 72, 64, 18, 17, 85];
     var mixOfThings = ['Cheese', 100, 'Sherlock', ["array","in","array"]];
    					

    Using arrays

    Access items in an array by wrapping its possition with "bracket notation" []

    
     var catName = 'Snuggles';
     var catRanks = ['Admiral','Captain','Commander','Lieutenant'];
     catRanks[4] = ?
    					

    Change a particular value by accessing its index also using bracket notation

    
     catRanks[2] = 'Colonel';
     console.log(catNames);
     console.log("My cat was just promoted! He is now " + catRanks[2] + " " + catName);
    					

    Using Arrays

    Get the length of an array with .length

    
     var howManyCats = catNames.length; //Returns 3
    					

    Add something to the end of an array with .push()

    
     var catNames = ['Fluffy','Admiral Snuggles','Fizgig'];
     catNames.push('Miss Havisham'); // arrayName.push(), don't need var
     console.log(catNames);
    					

    Let's Develop It!

    • Create an array of your favorite animals.
    • Add an animal without re-writing your array.
    • Change an animal using bracket notation.
    • Output a few animals onto your screen.

    Break Time

    Questions?

    Objects

    Objects let us store a collection of properties.

    					
    	var objectName = {
    		propertyName: propertyValue,
    		propertyName: propertyValue,
    		propertyName: propertyValue,
    		...
    	};
    				
    					
    	var aboutMe = {
    		hometown: 'Columbus, OH',
    		hair: 'Brunette',
    		likes: ['dogs', 'code', 'ice cream'],
    		birthday: {
    			month: 06,
    			day: 05
    		}
    	};
    				

    Accessing Objects

    You can retrieve values using "dot notation"

    					
    	var aboutMe = {
    		hometown: 'Atlanta, GA',
    		hair: 'Auburn'
    	};
    
    	var myHometown = aboutMe.hometown;
    				

    Or using "bracket notation" (like arrays)

    					
    	var myHair = aboutMe['hair'];
    				

    Changing Objects

    You can use dot or bracket notation to change properties

    var aboutMe = {
    		hometown: 'Atlanta, GA',
    		hair: 'Auburn'
    	};
    	aboutMe.hair = 'blue';

    Add new properties

    aboutMe.gender = 'female';

    Arrays of Objects

    Since arrays can hold any data type, they can also hold objects

    					
    	var myCats = [
    		{name: 'Lizzie', age: 18},
    		{name: 'Daemon', age: 1}
    	];
    
    				

    And objects can hold arrays

    Let's Develop It

    Create objects for your other two cats.

    Try displaying some information about your cats.

    Functions

    • Collection of statements that perform a task or calculation
    • Functions are kinda like algebra equations:
      Define the equation, plug in some values, and get a result
    • Just like variables, declaring a function creates it
    
    			function helloWorld(){} // Declared, now it exists!
    						
    
    			// Another way of writing it
    			var helloWorld = function(){}; // Stored as a variable
    						

    Function Syntax

    • Function definition (or declaration): the entire set of keyword, name, parameters, and statements making up the function
    • Keyword function
    • Function name
    • Parameters: list of arguments the function can use, enclosed with parenthesis ()
    • Statements are enclosed with curly braces {}
    
    	function name(argument1, argument2){
    		statement;
    		statement;
    		statement;
    	} // No ending semi-colon!
    					

    Calling Functions

    • Calling a function means to invoke it, or activate it
    • After it has been defined
    • functionName();
    
    	function helloWorld(){    // Declared function named helloWorld
    		document.write("Hello world!");  // What you want it to do
    	}
    
    	helloWorld(); // Call the function
    					

    Once defined, you can call the function as many times as you want!

    Reusable code!

    Passing Arguments

    • Functions accept input values, called arguments
    
    	function callKitten(kittenName){
    		console.log('Come here, ' + kittenName + '!');
    	}
    	callKitten('Fluffy'); // Outputs 'Come here, Fluffy!'
    	callKitten('Admiral Snuggles'); // Outputs 'Come here, Admiral Snuggles!'
    	callKitten('Fizgig'); // Outputs 'Come here, Fizgig!'
    					

    You can re-use the same function for many different arguments!

    Reusable code!

    Using Objects as Arguments

    Just like other data types, objects can be passed into functions:

    					
    	var lizzieTheCat = {
    		age: 18,
    		furColor: 'grey',
    		likes: ['catnip', 'milk'],
    		birthday: {month: 7, day: 17, year: 1996}
    	}
    

    More on Arguments

    • Pass multiple arguments
    
     function addNumbers(a,b) {
      document.write(a + b);
     }
     addNumbers(5,7); //outputs 12
     addNumbers(9,12); //outputs 21
    					
    • Pass variables as arguments
    
     // Declare variables
     var numberOfKittens = 5;
     var numberOfPuppies = 4;
     var numberOfGoats = 14;
     // Define function
     function addAnimals(puppies,kittens){
      console.log('You now have ' + (puppies + kittens) + ' pets!');
     }
     //Use variables in the function
     addAnimals(numberOfPuppies,numberOfKittens);
     addAnimals(numberOfPuppies,numberOfGoats);
    					

    Function Returns

    • The keyword return produces a value at the end of the function
    • Immediately exits the function
    
    		var numberOfKittens = 5;
    		var numberOfPuppies = 4;
    
    		function addAnimals(puppies,kittens){
    		return (puppies + kittens);
    		console.log(puppies > kittens); //Will never get to this line
    		}
    
    		addAnimals(numberOfPuppies,numberOfKittens); // Has returned 9
    					

    But how do you know?!

    Ways to use Returns

    
    		var numberOfKittens = 5;
    		var numberOfPuppies = 4;
    
    		function addAnimals(puppies,kittens){
    		return (puppies + kittens);
    		}
    
    		// Save the returned value as a variable
    		// then output the variable
    		var myAnimals = addAnimals(numberOfPuppies,numberOfKittens);
    		document.write(myAnimals);
    
    		// Output the returned value directly
    		document.write(addAnimals(numberOfPuppies,numberOfKittens));
    					

    Let's Develop It!

    Writing multiple lines in your console gets tough, so let's use Codepen.io

    • In the JS area, write a function called sayMyName
    • Takes 2 parameters: firstName and lastName
    • Output (either alert or document.write) a string that joins firstName and lastName
    • Call your function by passing it your first and last names as strings

    Class 2 Homework

    • Additional reading on arrays and objects at Eloquent Javascript
    • Additional reading on functions at Javascript.info
    • If you want to look ahead, next time we'll be talking about function scope, loops, and control flow
    • Bring any questions you think of to next class
    Remember:
    Every question is important!

    Class 3 Slides

    Methods

    Functions that are defined within an object are called Object Methods

    
    							var lunchObject = {
    								sandwich: "PB&J",
    								snack: "Oreos",
    								drink: "Fresca",
    								eat: function() {
    									console.log("Nom nom on " + this.sandwich);
    									console.log("Nom nom on " + this.snack);
    									console.log("Glug glug " + this.drink);
    								}
    							}
    
    							lunchObject.eat();
    						

    So what does that tell you about console and document?

    Common Methods

    General

    • console.log()
    • object.length()
    • object.indexOf()
    • event.preventDefault()

    More on Objects

    DOM (Document Object Model)

    • document.write()
    • d.getElementById()
    • d.getElementsByTagName()
    • d.querySelector()⭐️
    • d.querySelectorAll()⭐️
    • d.appendChild()
    • d.addEventListener()

    More DOM methods

    Event Listeners

    Scope

    Variable scope refers to the area of your program that can remember it

    Two types: global and local

    														
    										var outsideHouse = "global scope";
    										var goInside = function() {
    											var insideHouse = "local scope";
    										}
    
    										console.log(outsideHouse);
    										console.log(insideHouse);
    													
    														
    										console.log(goInside);
    														
    													

    Scope

    														
    										var outsideHouse = "global scope";
    
    										var goInside = function() {
    											var insideHouse = "local scope";
    
    											var goIntoBedroom = function() {
    												var insideBedroom = "also local scope";
    
    												var lookInSafe = function() {
    													var insideSafe = "yep, still local!";
    												}
    											}
    										}
    													

    Control Flow

    Use if to decide which lines of code to execute, based on a true condition.

    					
    	if (condition) {
    		// statements to execute
    	}
    				
    					
    	var bananas = 5;
    	if (bananas > 0) {
    		console.log ('You have some bananas!');
    	}
    				

    What if you want multiple options?

    Control Flow

    					
    	if (condition) {
    		// do one thing
    	} else {
    		// do another thing
    	}
    				

    Runs the first true condition it meets

    					
    	var classSize = 15;
    
    	if (classSize > 15) {
    		console.log("Have class at Improving");
    	} else if (classSize > 10) {
    		console.log("Have class at Pillar");
    	} else if (classSize >= 5) {
    		console.log("Have class at Cardinal Solutions");
    	} else {
    		console.log("Aw bummer, we need at least 5 students!");
    	}
    				

    Let's Develop It

    Write a function weatherWear that tells you what to wear outside:

    1. If it is less than 50 degrees, wear a coat.
    2. If it is less than 30 degrees, wear a coat and a hat.
    3. If it is less than 0 degrees, stay inside.
    4. Otherwise, wear whatever you want.

    Logical Operators

    Example Name Result
    a && b AND TRUE if both a and b are TRUE .
    a || b OR TRUE if either a or b is TRUE .
    ! a NOT TRUE if a is not TRUE .

    Using logical operators

    You can use these operators to combine conditions.

    					
    	var bananas = 5;
    
    	if (bananas >=2 && bananas <7) {
    		console.log ('You have a reasonable number of bananas');
    	} else {
    		console.log ('Check your banana supply');
    	}
    				

    Break time!

    Loops

    Process a set of data by iterating through the set
    and performing an action to each item

    • while loops
    • for loops
    • Require:
      • Set of data (a range or an array)
      • Ending condition
    • infinite loops = sadfaces
    • Forgot the ending condition! (Or it's invalid)

    While loops

    Repeats the same code over and over until some condition is met

    
    			var numberOfTacos = 10;
    			while (numberOfTacos > 0) {
    			console.log('OM NOM NOM'); //Eat a taco
    			numberOfTacos =- 1; //Decrement by 1
    			}
    				

    while (numberOfTacos > 0) is the ending condition

    • while (numberOfTacos) = sadface!
    • while (numberOfTacos < 100) = sadface!

    Infinite Loops

    Make sure something changes in the loop, or your loop will go on forever...

    For loops

    For loops are very similar, but you declare a counter in the statement.

    
    			//will count 1 to 10
    			for (var i = 1; i <= 10; i++) {
    			console.log (i);
    			}
    			

    Break

    To exit a loop, use the break statement.

    
    			//Count from 100 to 200
    			for (var i = 100; i <= 200; i++) {
    			console.log('Testing ' + i);
    			break;
    			}
    			

    Iterating through arrays

    Use a for loop to easily process each item in an array.

    
    			var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
    			for (var i = 0; i < rainbowColors.length; i++) {
    			console.log(rainbowColors[i]);
    			}
    					

    Let's Develop It!

    Write a function that loops through the numbers 1-100 and meets the following conditions:

    • If the number is divisible by 3, console.log("Girl");
    • If the number is divisible by 5, console.log("Develop");
    • If the number is divisible by 3 AND 5, console.log("Girl Develop It!");
    • Otherwise, don't do anything!
    Hint: Use a variable that starts at 1 and increments each loop.

    Class 3 Homework

    • Try the examples on this site from the Loops and Conditionals sections. See if you can build on what you know by trying some of the material that we haven't learned, like the ternary operator
    • If you want to look ahead, next time we'll be talking about working with the DOM.
    • Bring any questions you think of to next class
    Remember:
    Every question is important!

    Class 4 Slides

      <html>
    		<head>
    			<link rel="stylesheet" href="css/app.css"> // import CSS
    		</head>
    		<body>
    
    			<style>
    			  // some css
    			</style>
    
    			<script>
    			  // some javascript
    			</script>
    
    			<script src="js/app.js"></script> // import JS
    		</body>
    	</html>
    

    Events

    An 'event' is a type of object that is created when the user interacts with a web page.

    For example, JS creates an event when a user clicks an element.

    
    			element.onclick = function () {
    			  //code to execute when the click happens
    			};
    							

    Types of Events

    There are a variety of events. Some of the most common:

    • onclick: The event occurs when the user clicks on an element
    • onmouseover: The event occurs when the pointer is moved onto an element
    • onkeyup: The event occurs when the user releases a key
    • onload: The event occurs when a document has been loaded
    • onfocus: The event occurs when an element gets focus

    Events and Code

    How do you make an event trigger some code?

    1. Break your code into functions
    2. Associate a function with a JavaScript event

    Calling Functions from HTML

    You can call a function directly from your HTML code:

    
    			// html
    			<button id="clickMe" onclick="sayHi()">Click Me!</button>
    							
    
    			// javascript
    			function sayHi() {
    			    alert ('Hi!');
    			}
    							

    Listening Functions

    Listening functions work like many of the other things we have done. First, find the object:

    
    			var myTarget = document.getElementById('clickMe');
    			                

    Then add an event to that object:

    
    			myTarget.onclick=function(){
    			     alert ('Hi!');
    			}
    			                

    Let's Develop It

    Open a new Codepen

    Add an element (any) in the HTML section

    Make some JavaScript code fire after an onmouseover event. Then try adding a listening function.

    Preventing Defaults

    Elements like buttons and links have default behaviors. However, the event objects has a built-in method to handle that:

    
    			element.onclick = function (event) {
    			  event.preventDefault();
    			};
    
    							

    Let's Develop It

    Add a link element to your HTML:

    
    			<a href="http://girldevelopit.com/" class="gdiLink">Girl Develop It</a>
    							

    When you click the link, the page should display an error message instead of going to the Girl Develop It homepage.

    Forms

    You can collect information from users to use in functions. The most common method is an HTML form:

    
    			<form id="temperatureForm">
    			    <label for="temp">Temperature:</label> <input type="text" id="temp" size="3"/> degrees in
    			    <input type="radio" name="tempFormat" value="F" checked />Fahrenheit
    			    <input type="radio" name="tempFormat" value="C" />Celsius <br />
    			    <label for="submitButton"></label> <input id="tempSubmitButton" type="submit" value="Submit" />
    			</form>
    							

    Retrieving Form Data

    You retrieve the values of form inputs using the value method:

    
    			var thingToDo = document.querySelector('.js-task').value;
    			console.log (thingToDo);
    							

    You can retrieve the value of a form at any time. Try onblur (when a form element loses focus). Type text into the box and then click anywhere else on the page.

    Submit buttons

    If you are going to retrieve form values with the submit button, be sure to prevent the default action!

    
    			var submitButton = document.querySelector('js-submit');
    			submitButton.onclick = function () {
    			    event.preventDefault();
    			    var task = document.querySelector('js-task').value;
    			    console.log (task);
    			}
    			
    							

    Let's Develop It

    Open the following Codepen in your browser: https://codepen.io/jannypie/pen/ZyrpxM

    Collect a value from the input box on the page. Use it inside a function and display the task on the page.

    Let's Develop It

    • Let's make a whole list! Use document.createElement() to create a list element (ol or ul).
    • Use object.appendChild() to add your list to the div on the page.
    • Write a function that listens for the submit event
    • Get the value of the input box
    • Create a list item element li with the text from your input document.createTextNode("text");
    • Append that item to the list on the page Tip: If you have problems, try querying for the list again.

    End of Class!

    Congratulations junior programmers!

    Web Page Key Terms

    Element
    Document
    DOM
    Document Object Model
    Object

    JS Terms

    Client Side
    Server Side
    Object
    JS Object:
    DOM Object:

    References

    ml>