JavaScript

Meet the C&C #LadyDevs

Amy Norris

Amy Norris

Director

Alex Herron

Alex Herron

Co-Director

Julie Batson

Julie Batson

Curriculum Director

Gabi Dombrowski

Gabi Dombrowski

Mentor Director

Kim Watt

Kim Watt

Marketing Director

Vanessa Shultz

Vanessa Shultz

Presentation Director

Anita Golden-Burrell

Anita Golden-Burrell

Technical Materials Director

Our Host this Evening

Dimensional Innovations


DI

Bathrooms...


Behind the wooden wall in the kitchen


stalls

Drink Served

Laura Kozak

Laura Kozak

Join us on...

Slack

Carolyn Westhoff

#generation-x

#tabletop-games

#movies

#cats_and_doggos

Our mentors

Mentors

are super heroes!

Before We Get Started...


This stuff is a challenge!


Don’t be discouraged if you don’t finish each worksheet section before the next presentation section begins.


We cover a lot of difficult material that will take time to understand. We are here (and on Slack after the session) to help!

Tonight's Agenda:
JavaScript


  • Intro to JS

  • Operators

  • Functions

  • Arrays/Loops

  • Events

First, we drink!


girls drinking

Intro to JavaScript, Primitive Values, Variables, & Operations


Octocat Excellent

Introduction to JavaScript


JS aka JavaScript


JScript


ECMAScript

HTML + CSS + JS


HTML + CSS + JS

What Does JavaScript Give Us?



  • Improve user experience

  • Provide dynamic functionality

  • Reduce reliance on server

History



  • Developed in 1995 at Netscape

  • History of names:

    • Mocha
    • LiveScript
    • JavaScript


  • ECMAScript is the official language

  • JS is one implementation of the standard

JavaScript is NOT Java



Octocat Confused

JavaScript versus Java

  • JavaScript: Developed at Netscape
  • Java: Developed at Sun Microsystems

  • JavaScript: Object Oriented Scripting Language
  • Java: Object Oriented Programming Language

  • JavaScript: Primarily Client-Side [Node.js is server-side JS]
  • Java: Server-Side

  • JavaScript: Loosely Typed
  • Java: Strictly Typed

How Do We Actually Use JavaScript



Octocat What

Link JavaScript files to your HTML



  • Usually in <head>, but can also be added before closing </body>

  • Use the <script> tag

  • Use the src attribute to link to the file

  • Use the type attribute to specify the language

Adding JavaScript



  • Add JavaScript directly to files

  • <script type="text/javascript">
        const myJSVariable = "hey ladies!"
    </script>

  • BEST PRACTICE: Link to JS file

  • <script src="assets/js/my-javascript-file.js"></script>

DOM: Document Object Model



  • A webpage is a document

  • Browser parses HTML to create the DOM

  • DOM: Object-oriented representation of the webpage

  • JS can manipulate DOM
DOM Model

JS Manipulates the DOM



  • Changing colors

  • Add/change/remove text

  • Animate HTML elements

Variables

Octocat Build

Variables



  • Placeholder to story values/data

  • const and let : good practice is to always set a variable using one of these keywords

  • var : avoid using this keyword since ES6

const and let



  • let : variable that can be reassigned

  • const : variable that cannot be reassigned
let myName = "John";
myName = "Jane"; // "Jane"


const myName = "John";
myName = "Jane"; // TypeError: Assignment to constant variable.

Variable Naming



  • JavaScript is case-sensitive: use same case you used when creating the variable to reference said variable

  • myVariable is not the same as MyVariable

Variable Name Rules



  • Must start with a letter [upper or lowercase], _, or $

  • Subsequent characters may contain letters, numbers, _, or $

  • Best practice: camelCase

Camel Case



  • First word is lowercase

  • Subsequent words have have their first letter capitalized, followed by all lowercase

  • const myVeryFirstVariable

Coding Example



  • Set a variable

  • const myVariable = 5;
  • Reference that variable by name

  • myVariable;

Primitive Values



Octocat Battle

Basic Data Types in JS



  • Strings

  • Booleans

  • Numbers

  • Undefined

  • Null

Strings



  • Sequence of characters

  • Enclosed in single or double quotes

  • Can concatenate with the + operator

Strings



const double = "Hello World!";


const single = 'Hello World!';


typeof(double); // string

String Concatenation



const hello = "Hello";


const world = "World!";


const helloWorld = hello + " " + world;


// "Hello World!"

Booleans



  • True or False

  • Used in conditional statements

const isTrue = true;
const isFalse = false;
typeof(isTrue); // boolean

Numbers



  • Also commonly called integers

  • Can include decimals

  • Can use arithmetic operators

  • Can use comparison operators

Numbers



const num = 5;


const decimal = 5.5;


typeof(num); // number

Programming Nugget



  • Numbers wrapped in quotes are strings

const num = "5";
typeof(num); // string

Other Primitive Values



  • Undefined

  • Null

Undefined



  • A variable that has been declared, but has no value

  • Can be assigned a value later
let x;
typeof(x); // undefined

null



  • Explicitly set a variable to null, as a representation that the variable has no value
let x = null;
typeof(x); // object

Work Time

Presentation: https://bit.ly/cc-js-slides

Worksheet: https://bit.ly/cc-worksheet



cat typing

Operators



Operators



  • Math (Arithmetic)

  • Comparison

  • Logical

Math Operators



  • Addition (+)

  • const myAge = 21 + 10; // 31
  • Subtraction (-)

  • const agePeopleThinkIAm = 31 - 6; // 25

Math Operators



  • Multiplication (*)

  • const myDogsAge = 38 * 38; // 1444
  • Division (/)

  • const ozWineBottleSplitFourWays = 25.4 / 4; // 6.35

Math Operators



  • Modulus (%)

  • const cookiesLeftAfterThreeKidsSplitCookiesEquallyYeahRight = 16 % 3; // 1
  • Think remainder that you learned with long division

Math Operators



  • Increment (++)

  • let myAge = 21;
    myAge++; // 22

  • Decrement (--)

  • let cookies = 5;
    cookies--; // 4

Adding Strings and Numbers



  • Adding 2 numbers gives you a sum

  • const thirtyFive = 10 + 25; // 35

Adding Strings and Numbers



  • You can add strings together

  • const textString = 'happy' + 'birthday'; // happybirthday

Adding Strings and Numbers



  • If you add a string and a number, the result will be a string

  • const textAndNumberString = 'happy' + 35 + 'birthday'; // happy35birthday
    const numberAndTextString = 'happy' + ' ' + 35 + ' ' + 'birthday'; // happy 35 birthday

Adding Strings and Numbers



    const gotcha = '10' + 25;
    // 1025

Programming Nugget



  • Adding strings is called Concatenation

Comparison Operators



  • Equal to (==)

  • const myAge = 21;
    myAge == 21; // true

  • Strict equal to (===): type specific

  • const cookies = 0;
    const drinks = '0';
    cookies === drinks; // false

Comparison Operators



  • Strict not equal to (!==)

  • const cookies = 0;
    const drinks = '0';
    cookies !== drinks; // true

  • Not equal to (!=)

  • const myAge = 21;
    myAge != 21; // false

Comparison Operators



  • Greater than (>)

  • const myAge = 18;
    myAge > 21; // false

  • Less than (<)

  • const myAge = 18;
    myAge < 21; // true

Comparison Operators



  • Greater than or equal to (>=)

  • Less than or equal to (<=)

Comparison Operators



  • Ternary

  • Condition ? expr1 : expr2;

  • {condition} ? {what happens if true} : {what happens if false} ;

  • const myAge = 18;
    myAge > 21 ? 'You are older than me' : 'You are younger than me'; // You are younger than me

Work Time

Presentation: https://bit.ly/cc-js-slides

Worksheet: https://bit.ly/cc-worksheet



cat typing

Functions, Conditionals, and Debugging


octocat

Functions



  • Aka Methods

  • Takes input [parameters], processes the input and produces output


function

Reusable bits of code



  • Instead of writing the same logic over and over...

  • Place logic in a function and use that function over and over
function sayHello() {
  console.log('Hello!');
}

sayHello(); // Hello!

Programming Nugget



  • DRY programming

  • Don't Repeat Yourself

Function Parameters



  • Functions can pass 0 to many parameters (separated by commas)

Set to a Variable Value



const functionName = function(optional, parameters, here) {
  // function logic here
};

functionName();
functionName('hello');

Example



//with 1 parameter
const orderDrink = function(drinkName) {
  return 'I would like a ' + drinkName + ' please.';
};

orderDrink('gin and tonic');
//'I would like a gin and tonic please.';

Function Declaration



function functionName() {
  //function logic here
}

Function Expression



//without parameters
function orderMyFavoriteDrink() {
  return 'I want a margarita.';
}

orderMyFavoriteDrink();
//'I want a margarita.'

Arrow Functions



  • Arrow functions are a shorter way to write functions

const sayHello = (name) => {
  console.log('Hello ' + name + '!');
}

sayHello('KC Wit'); // Hello KC Wit!

Return Statement is Optional



  • JS engine needs a return to know that the function is done and it can move on to the next bit of code

  • If you don't use a return statement, the function will return undefined

Example



let drink; // declares variable but doesn't set

function setDrink (cocktail) {
  drink = cocktail;
}

setDrink('martini');
//undefined is returned but drink variable is now set to 'martini'

alert('My current drink of choice is a ' + drink);
//alert will display 'My current drink of choice is a martini'

Conditionals



  • JavaScript executes from top to bottom (synchronously)

  • Conditionals allow us to control the flow of our code

  • Sometimes you only want to execute code if something is true or false

  • JavaScript has different types of conditionals with the most common being if/else

if/else



  • Used to execute code if a condition is true or false

  • if/else statements can be nested together to create more complex logic

if (condition) {
  // code to execute if condition is true
} else {
  // code to execute if condition is false
}

Example



const age = 21;

if (age >= 21) {
  console.log('You can drink!');
} else {
  console.log('You can't drink!');
}
// You can drink!

Complex Example



const usersName = 'Heidi';

if (usersName.length > 0) {
  submitDrinkOrder();
} else {
  alert('Please enter your name before submitting your drink order.');
}
// Submits a drink order

Nested Example

const usersName = 'Heidi';
const usersAge = 21;

if (usersName.length > 0) {

    if (usersAge >= 21) {
      submitDrinkOrder();
    } else {
      alert('You must be 21 to submit a drink order.');
    }

} else {

    alert('Please enter your name.');

}

Programming Nugget



  • else is optional

  • if (condition) {
      // code to execute if condition is true
    }

Programming Nugget



  • if else

  • if (condition) {
      // code to execute if condition is true
    } else if (condition) {
      // code to execute if first condition false, but second true
    } else {
      // code to execute if condition is false
    }

Truthy and Falsy



  • Every value in JavaScript has an inherent truthiness or falsiness

  • Truthy values are values that are considered true when encountered in a boolean context

  • Falsy values are values that are considered false when encountered in a boolean context

Values that are 'Truthy'



  • true
  • any number that is not 0
  • any non-empty string (e.g., 'hello')
  • any array
  • any object
  • function
  • '0' (a string containing a single zero)
  • 'false' (a string containing the text “false”)

Values that are 'Falsy'



  • false
  • 0
  • '' (empty string)
  • null
  • undefined
  • NaN

Debugging



  • Process of finding and fixing errors in your code

  • Skill that takes time to develop

Debugging Tools



  • Browser Developer Tools

  • console.log()

  • Debugger

Browser Developer Tools



  • Inspect element

  • Chrome Lighthouse

console.log()



  • Prints output to the console

  • Useful for debugging

  • Can be used to print out the value of variables

console.log() Examples



  • With variable

const name = 'Heidi';
console.log(name);
// Heidi

console.log() Examples



  • With function

const getSquareFeet = (height, width) => {
  return height * width;
}

console.log(getSquareFeet(10, 15));
// 5

console.log() Examples



  • With description

console.log('name', name);
console.log('square feet', getSquareFeet(13, 20);

Debugger



  • Stops the execution of your code

  • Allows you to step through your code line by line

Work Time

Presentation: https://bit.ly/cc-js-slides

Worksheet: https://bit.ly/cc-worksheet



cat typing

Arrays & Loops



confused octocat

Arrays



  • A list of data items

  • Items are separated by commas

  • Items can be accessed by index

Array Examples



const cocktails = ['Code on the Beach', 'jQuery Sour'];


const drinksIveConsumed = [0, 1, 2, 3, 4, 5, 6, 7, 'none of the above'];

Create an Array



  • Use new Array()

  • Initialize with an empty string []

  • const cocktails = new Array();
    const drinksIveConsumed = [];

Zero-based Index



  • Grab items in the array via their index

  • First item in an array is at index 0

  • Second item in an array is at index 1

  • Last item is one less than the length of the array (number of items in the array)

Array Example



const cocktails = ['Code on the Beach', 'jQuery Sour', 'Silicon Valley', 'JS on Rocks'];

console.log(cocktails[0]);
// Code on the Beach

console.log(cocktails[1]);
// jQuery Sour

console.log(cocktails[cocktails.length - 1]);
// JS on Rocks

Things you can do to an Array



  • Loop through an array

  • Add / Remove items from the array

  • And more...

Loops



  • A way to repeat a block of code, as long as specified condition returns true

  • JS supports multiple types of loops, but we'll cover the 'for' loop today

For Loops Structure



  • Increment increases the value set in initialization

  • Eventually condition is false so that...

  • The loop stop executing

  • (Don't get caught in an infinite loop!)

for (initialization; condition; increment) {
  // code to execute while condition is true
}

For Each



  • A loop that iterates through an array

  • An array method that executes a given function once for each array element

Loops Example

const cocktails = ['Code on the Beach', 'jQuery Sour'];

for (let i = 0; i < cocktails.length; i++) {
  console.log(cocktails[i], i);
}

// Code on the Beach 0
// jQuery Sour 1

cocktails.forEach(function(cocktail, index) {
  console.log(cocktail, index);
});

// Code on the Beach 0
// jQuery Sour 1

Add Item to End of Array



Use the push() method


(some array).push(...some item)


const cocktails = ['Code on the Beach', 'jQuery Sour'];

cocktails.push('Silicon Valley');

console.log(cocktails);
// ['Code on the Beach', 'jQuery Sour', 'Silicon Valley']

Remove Item from End of Array



Use the pop() method


(some array).pop()


const cocktails = ['Code on the Beach', 'jQuery Sour', 'Silicon Valley'];

cocktails.pop();

console.log(cocktails);
// ['Code on the Beach', 'jQuery Sour']

Add Item to Beginning of Array



Use the unshift() method


(some array).unshift(...some item)


const cocktails = ['Code on the Beach', 'jQuery Sour'];

cocktails.unshift('Silicon Valley');

console.log(cocktails);
// ['Silicon Valley', 'Code on the Beach', 'jQuery Sour']

Remove from Beginning of Array



Use the shift() method


(some array).shift()


const cocktails = ['Code on the Beach', 'jQuery Sour', 'Silicon Valley'];

cocktails.shift();

console.log(cocktails);
// ['jQuery Sour', 'Silicon Valley']

Work Time

Presentation: https://bit.ly/cc-js-slides

Worksheet: https://bit.ly/cc-worksheet



cat typing

Events



octocat

Events



  • HTML Events: things that happen to HTML elements

  • Event: anytime user or browser interacts with the webpage

  • JS can "react" to these events

Common Events



  • onchange: Webpage finishes loading

  • onclick: User clicks an HTML element (such as button)

  • onmouseover: User hovers over an HTML element

  • onchange: HTML element changed in some way

  • onkeydown: User presses a key

JS Reacting



  • JS can execute code when "events" happen

JS Events Examples



  • Button click => closes window

  • Mouse over text => information box provides more context

  • Button click => validates a form

  • Mouse over picture => picture becomes magnified

JS Event Code Examples

HTML

<button
  id="cocktail-section"
  onclick="clickHandler('Hi there LadyDev!')"
></button>


JS

const clickHandler = function (text) {
  alert(text);
};

Resources

What's Next


Coding & Cocktails

Keep up with us



codingandcocktails.kcwomenintech.org



#LadyDevs       #KCWiT


#CodingAndCocktailsKC