// 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();
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!
Introduction and Fundamentals
Getting set up Data types, operators, conditionals, and variables
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
1 + 2
// 3 Computer does the brain parts for you!
x + y
What is JavaScript?
---
"JavaScript can be connected to the objects of its environment (client or server) to provide programmatic control over them."
Let's write your first JavaScript program!
alert('Hello World!');
What action resulted?
---
Ask questions!
Variables represent information
x = 1
x + 2 =
var
var x = 1
var a; // declared but undefined
var a = "Aardvark"; // declared and initialized
var b;
b = "Bonobo"; // var isn't needed a second time
$
, or _
$
is used by the jQuery library_
is used by the underscore.js libraryvar thisIsMyVariable;
Once you have declared a variable, you can use it in your code. Just type the name of the variable.
var numberOfKittens = 5;
numberOfKittens;
var
).
numberOfKittens = 13;
numberOfKittens;
Next, try this one:
var kittenTitle = 'Admiral';
var kittenName = kittenTitle + ' Snuggles';
kittenName;
Those aren't numbers! What did you get?
You're so fancy
// The kitten got a demotion :-( Set his title to "Captain"
kittenName;
// What is the output of kittenName now? Why?
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! |
+ | Addition |
---|---|
- | Subtraction |
++ | Increment (+1) |
-- | Decrement (-1) |
* | Multiplication |
/ | Division |
% | Modulus (remainder) |
! | Is Not |
---|---|
== | Equality |
!= | Inequality |
=== | Identity/strictly equal |
!== | Non-identity |
> | Greater than |
>= | Greater or equal |
< | Less than |
<= | Less or equal |
Experiment with Data Types,
Operators and Comparators
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?
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 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";
// 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");
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);
arrays
, objects
, loops
, and functions
.Remember:
Every question is important!
Working with JavaScript
Arrays, Objects, FunctionsDid you find anything interesting about JS since last time?
== vs ===
var students = "Javascript stars!";
var arrayOfThings = [thing0, thing1, thing2, thing3];
[]
value
of arrayOfThings
at index 0
is thing0
"
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"]];
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);
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);
Questions?
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
}
};
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'];
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';
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
Create objects for your other two cats.
Try displaying some information about your cats.
function helloWorld(){} // Declared, now it exists!
// Another way of writing it
var helloWorld = function(){}; // Stored as a variable
function
name
()
{}
function name(argument1, argument2){
statement;
statement;
statement;
} // No ending semi-colon!
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!
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!
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}
}
function addNumbers(a,b) {
document.write(a + b);
}
addNumbers(5,7); //outputs 12
addNumbers(9,12); //outputs 21
// 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);
return
produces a value at the end of 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?!
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));
Writing multiple lines in your console gets tough, so let's use Codepen.io
sayMyName
firstName
and lastName
alert
or document.write
) a string that joins firstName
and lastName
strings
function scope
, loops
, and control flow
Remember:
Every question is important!
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
?
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);
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!";
}
}
}
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?
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!");
}
Write a function
weatherWear
that tells you what to wear outside:
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
. |
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');
}
Process a set of data by iterating through the set
and performing an action to each item
while
loopsfor
loopsRepeats 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!Make sure something changes in the loop, or your loop will go on forever...
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);
}
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;
}
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]);
}
Write a function that loops through the numbers 1-100 and meets the following conditions:
console.log("Girl")
;
console.log("Develop")
;
console.log("Girl Develop It!")
;
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
working with the DOM
.Remember:
Every question is important!
<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>
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
};
There are a variety of events. Some of the most common:
How do you make an event trigger some code?
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 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!');
}
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.
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();
};
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.
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>
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.
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);
}
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.
document.createElement()
to create a list element (ol
or ul
).object.appendChild()
to add your list to the div
on the page.li
with the text from your input
document.createTextNode("text");
Congratulations junior programmers!