Variables – Data Types – Conditionals - If/Else



Variables – Data Types – Conditionals - If/Else

1 0


JSProgrammingFundamentals

Coding & Cocktails Kansas City Programming Fundamentals in JavaScript course

On Github KansasCityWomeninTechnology / JSProgrammingFundamentals

Programming Fundamentals

Slides available at: http://bit.ly/CNCJSPF

Powered By:

Our Hosts

The Nerdery

Mentors

Photo by #WOCinTech Chat

What we'll cover

  • Review (Variables, Functions, etc)
  • Building Blocks (Data Types, Operators, etc)

Variables

Placeholder to store values

<div id="name"></div>
var firstName = "Jane";
document.getElementById("name").innerHTML = firstName;
<div id="name">Jane</div>
We use camelCase for variable and function naming. This is where the first word starts with a lower case letter and each subsequent word starts with a capital letter.

Variable Scope

  • Global
    • declared outside a function
    • accessible throughout script
  • Local
    • declared inside a function
    • accessible only within function
var globalVar = "I am globally scoped";

function scoping () {
    var localVar = "I am locally scoped to the function";

    console.log(localVar); // "I am locally scoped to the function"
    console.log(globalVar); // "I am globally scoped"
}

console.log(localVar); // undefined
console.log(globalVar); // "I am globally scoped"

Functions

  • Reusable blocks of code
  • Take input (parameters)
  • Process the input
  • Return output
  • When are they utilized?
    • In response to an event (button click, etc)
    • From other code
    • Automatically (self-invoked)
use functions to to reuse code multiple times instead of having the same code in multiple places throughout your files

Functions

function cocktailIngredients () {
    var firstIngredient = "Plantation Dark Rum";
    var secondIngredient = "Smoked Pineapple";
    var thirdIngredient = "Cinnamon Bark Syrup";
    var fourthIngredient = "Lime";
    var recipe;

    recipe = firstIngredient + ", " + secondIngredient + ", " 
        + thirdIngredient + ", " + fourthIngredient;

    return recipe;
}

cocktailIngredients();

Functions

function cocktailIngredients (firstIngredient, secondIngredient, 
                                                thirdIngredient, fourthIngredient) {
    var recipe;

    recipe = firstIngredient + ", " + secondIngredient + ", " 
        + thirdIngredient + ", " + fourthIngredient;

    return recipe;
}

cocktailIngredients("Plantation Dark Rum", "Smoked Pineapple", 
    "Cinnamon Bark Syrup", "Lime");

**Programming Nugget!**

Don't Repeat Yourself - DRY Programming

Reduce Complexity & Repetition

Bad:

var newElement = document.createElement('div');
newElement.className = 'navbar';

var anotherElement = document.createElement('ul');
anotherElement.className = 'menu';

var moreElements = document.createElement('li');
moreElements.className = 'menu-nav-item';

var fourthElement = document.createElement('li');
fourthElement.className = 'menu-nav-item';
                        

Good:

function createElement(tagName, className) {
    var element = document.createElement(tagName);
    element.className = className;
    return element;
}

var newElement = createElement('div','navbar');
var anotherElement = createElement('ul','menu');
var moreElements = createElement('li','menu-nav-item');

Comments

  • Add notes about your code
  • Make code maintenance easier
// This is a single line comment

/* This is a multi-line comment
I can keep writing comments on more lines
until I tell it that I'm done */

**Programming Nugget**

// TODO: is a typical comment to remind yourself to come back & do something

//TODO: Add examples to comment section

Console.log()

Add to code for debugging help

var shoeBrand = "Jimmy Choo";
console.log(shoeBrand); // Jimmy Choo

var addOne = function (x) { return x + 1 }
console.log(addOne) // function (x) { return x + 1 }

var name = "Jane";
var cocktail = "Old Fashioned";
console.log(name); // Jane
console.log(name , " wants a(n) ", cocktail, ".") 
    // Jane wants a(n) Old Fashioned.

Data Types

  • String
    • "Hello World"
    • "45"
    • 'Lucky number 7'
  • Boolean
    • True
    • False
  • Numbers
    • 19
    • 135.2
    • 3.14159

**Programming Nugget**

A number wrapped in quotes is a string!

"45" is not the same as 45

Operators

Math

  • Addition +
var age = 28 + 10; // 38
Subtraction -
var ageITellPeople = 38 – 9; // 29
Multiplication *
var myDogsAge = 6 * 7; // 42
Division /
var ozWineBottleSplitFourWays = 25.4 / 4; // 6.35

Operators

Math

  • Modulus %
    var cookiesLeftAfterThreeKidsSplitEqually = 25 % 3; // 1

(As if this is a true scenario)

Increment ++
var tenPlusOne = 10++; // 11
Decrement --
var tenMinusOne = 10--; // 9

Operators

Adding Strings & Numbers

  • Adding two numbers gives you a total
var twentyOne = 10 + 11; // 21
Adding strings and numbers gives you a string
var textAndNumberString = ‘happy ’ + 21 + ‘ birthday’;
// happy 21 birthday
Gotcha!
var gotcha = '10' + 24 // 1024

**Programming Nugget**

Adding strings is called concatenation!

Operators

Comparing things - So many equal signs!

  • = Single Equal
    • Used for assignment
var olive = "Spanish";
== Loose Equals/Double Equals
  • Checks for equal values of different data types
42 == "42" //true
=== Strict Equal/Triple Equal
  • Checks for both value and data type equality
var meaningOfLife = 42;

meaningOfLife === "42" //false
meaningOfLife === 42 //true

Operators

Comparing things

  • != not equal
  • !== not equal value or not equal type
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to
  • ? ternary
var age = 62;
var drink = (age > 21) ? "Wine" : "Grape Juice"; //Wine
Compare object types

Conditionals - If/Else

Sometimes you want to run some code only when a condition is true or false

var usersName = ‘Heidi’;
if (usersName.length > 0) {
  submitDrinkOrder();
}
else {
  alert(‘Please enter your name before submitting your 
    drink order.’);
}

**Programming Nugget**

Else is optional!

It is possible to use an If statement by itself!

var flower = "Sweet Pea"

if (flower === "Sweet Pea") {
    addToBouquet();
}

Let's get to it!

Tonight's Worksheet

Loops

  • Multiple Loop Types
    • For Loops
    • While Loops
    • Do ... While
    • For ... In
    • More
  • Repeat code as long as the condition is true

For Loop

for (var i = 0; i < 5; i++) {
  notifyDrinkIsReady(i);
}
i is a common reference for incrementer. watch out for infinite loops!

Data Sets

We could have a whole separate session on data sets and how you can use & manipulate them. They’ll be covered more when we get into Single Page Applications & REST, but here’s some basic info. Every data set is going to be made up of strings, booleans & numbers. Sometimes you need data that is grouped & that’s when you’ll want a data structure like arrays & objects.

Arrays

  • Use when you need a list of items
  • Creation
var myArray = new Array();
var anotherArray = [];
Zero-based index
  • the first item in an array is at index 0, not index 1
var myArray = ["first","second","third"]

var firstArrayItem = myArray[0] // first
var secondArrayItem = myArray[1] // second
var last = myArray[myArray.length – 1]; // third

Arrays

  • Loop through list items
  • Add items
  • Remove items
  • More
var cocktails = [‘Code on the Beach’, ‘jQuery Sour’];

// Loop
for (var i = 0; i < cocktails.length; i++) {
    console.log(cocktails[i]);
}

// Add item
cocktails.push('Tom Collins'); // [‘Code on the Beach’, ‘jQuery Sour’, 'Tom Collins']

// Remove
cocktails.splice(2,1); //[‘Code on the Beach’, ‘jQuery Sour’]

Objects

  • More complex data structure
  • Creation
    • var myObject = new Object();
    • var anotherObject = {};

Objects

JSON - JavaScript Object Notation

  • Key: Value pairs
  • Most APIs return data in this format
  • Lodash & Underscore libraries

Object Example

var myObject = {
  "keyWrappedInQuotes": *,
  "valueCanBeAString": "string",
  "valueCanBeANumber": 3,
  "valueCanBeABoolean": true,
  "valueCanBeAnArray": ["Red","White","Sangria"],
  "valueCanBeAnObject": {
    "keyInsideChildObject": "is this inception?"
  }
  "valueCanBeAFunction": function() {
    shutTheFrontDoor();
  }
}

Objects

JSON - JavaScript Object Notation

Using object data

myObject.valueCanBeAnArray // ["Red","White","Sangria"]

DOM Selectors

Different than jQuery

document.getElementById('cocktail');
document.getElementsByClassName('red');
different browsers support different DOM Selectors. This is getting better with today’s modern browsers, but if you have to support older browser versions, like IE9, libraries like jQuery will be your BFF.

Events

Image from University of Washington Web Programming Lecture

Like DOM Selectors, events can also have varied support across browsers in plain JavaScript. For the sake of our sanity and time, we’re going to continue to use jQuery, but you can look into vanilla JS events in the Mozilla JavaScript resources.

Further Learning

Google it!

  • Object-Oriented Programming vs. Functional Programming
  • Regular Expressions - Crossword Learning Game
  • Scope
  • this - Search for "The this keyword" on the page
  • Hoisting
  • Dates - use a library like MomentJS to make life easier!
  • ES2015/ES6

Review

  • Variables
  • Functions
  • Comments
  • Data Types
  • Operators
  • Conditionals
  • Loops
  • Data Sets

Questions?

?

Thank You!

Keep in touch!

#LadyDevs

#KCWiT

#CodingAndCocktailsKC

Click here to join us next month!