Picture

Hi, I'm Travis Faas.

Teacher.

Functions and Variables

Functions and Variables

Okay, let’s talk about the building blocks of code: functions and variables.

Variables

Variables store values. That is it.

They’re just names that point to a value.

Values

Values can be just about anything. This class is going to be working with these value types, for the most part:

  • Numbers
  • Strings (text)
  • Booleans (true/false)
  • HTML Elements
  • HTML Inputs

Again, a variable is just a way to reference one of these values. Its like a page number in a book, a place to look up the data.

To make a variable

Type the keyword var, the name of the var, and then a variable type.

var myVar;

Putting stuff into variables

Use the equals sign (=)

var something = 'Hello';
something = 'Goodbye';

(In thise case, the final value of the variable something will be ‘Goodbye’)

Variable Types

We’re going to be working with three major variable types, to begin with, but you will quickly see that there is a plethora of variables out in the Real World.

Numbers

These store.. numbers.

var first = 10;

All sorts of numbers

var another = 5.66;
var pewPew = 1000000000000000;
var yougetthepoint = 0.45;

Strings

var another = 'Hello world!';

A note on strings in order to write strings in code you must use either the double quotes “ or single quote ‘, opening and closing the string with the same for the whole string.

Strings made in code like this are called string literals.

(The reason there are two types of quotes? So you can have quotes in quotes:’“Hello!” she said.’ is a valid string)

Booleans

Store true or false.

var isCold = false;
var isWarm = true;

Operands

You can do more with variables than just assign single values. Variable operands let you manipulate the values inside the variables.

var a = 4;
var b = 2;

//addition
var c = a + b; //6

//subtraction
var d = a - b; // 2

//multiplication
var e = a * b; //8

//division
var f = a / b; //2

//modulo
var g = a % b; // 0

Modulo

Also Known As “remainder” The part left over after division

7 % 3 //1
12 % 10 //2

Question

Let’s say I have a variable myVar and I want to subtract 2 from it, and store that value back into the variable?

How do I do that?

Incrementing/Decrementing

var a = 5;

//incrementing
a = a + 1; //a == 6

//decrementing
a = a - 3; //a == 3

//multiplenting? (this and the next are not real words I just thought they were funny)
a = a * 2; //6

//divisiplexing?
a = a / 3; //2

Incrementing/Decrementing/other shorthand

var a = 5;

//incrementing
a += 1; //a == 6

//decrementing
a -= 3; //a == 3

//Multiplication
a *= 2; //6

//Division
a /= 3; //2

String Concatenation

One can also use the plus sign to add strings together. This is called String concatenation.

var first = "Hello";
var last = "World";
var else = first + last; //'HelloWorld';

Question - why no space between the hello and world in the result?

Logging

Logging lets you see the value of variables in the developer console. Here’s an example:

var someVar = "Hello";
console.log(someVar);

If we open up the chrome developer console (our developer console of choice), we will see the string “Hello” on one line of it.

Functions

Functions are a way to package up a block of code to run at a later time. They code inside their curly brackets is not used until they are called, invoked, run (these are all terms I may or may not use in class)

Here is a function

function sayHello() {
	console.log("Hello");
}

This function will, when used, output some text to our lovely developer console.

Here’s how to run that function

sayHello();

If you put it all together, it looks like this

function sayHello() {
	console.log("Hello");
}

sayHello();

This is a good point to write your own, similar function, and call it

Function arguments

  • Functions are machines, and, like some machines, can take inputs (called arguments)
  • Arguments become variables inside of the functions

Argument Example

function sayHelloName(name) {
	//name is now a variable in this function
	//we can do anything we want with it

	//even something boring like say hello to the name
	console.log("Hello " + name + "!");
}

Calling a function with arguments

  • Provide the argument inside of the parenthesis

Using our sayHelloName function

sayHelloName("Todd");

Multiple arguments

  • Functions can take multiple arguments
  • Put a comma between each argument
//the function
function sayHelloSalutation(salutation, name) {
	console.log(salutation + " " + name +"!")
}

//calling the function
sayHelloSalutation("What's up", "Dan");

Function returns

Functions can also return values. Here’s a simple example

function makeHello() {
	var aString = "hello";
	return aString;
}


//use the function
var aHello = makeHello(); //a hello now contains 'hello'
//this would do the same thing as above
var aHello = "Hello";

Complex function usage

//our function
function generateHello(salutation, name) {
	var sal = salutation + " " + name +"!";
	return sal;
}

//use the function

var ourHello = generateHello("Hey there", "Dave");
console.log(ourHello);

Scope

Now that we have functions, we need to start worrying about variable scope

Variables created inside a function (with the var keyword) are not useable outside of that function

But variables created outside of that function are.

function myFunc() {
	var awesomeVariable = "Pretty cool";
}

function myOtherFunction() {
	console.log(awesomeVariable); //won't work
}


console.log(awesomeVariable); //won't work
var awesomeVariable = "Pretty cool";

function myFunc() {
	console.log(awesomeVariable); //will work
}

function myOtherFunction() {
	console.log(awesomeVariable); //will work
}


console.log(awesomeVariable); //will work

Getting Input

Input is great! If only we all spent more time listening and less time talking (and here I am, talking away).

Here’s the most basic way to get input from the user: an input (it actually becomes a textfield but close enough).

<input id="userName" />

(Take note of that ID we’ll be using it soon)

Now let’s make another input tha’s a bit more.. interactive. A button

<input type='button' onclick='getUsername()' />

Okay, great. Let’s finish this up. Assuming we have both of these on the screen we can add this to our javascript file:

function getUsername() {
	var username = document.querySelector('#userName').value;
	console.log(username);
}

Two things here:

document.querySelector will get any HTML tag (an element) on the page that matches its CSS selector

.value will get the value of any input element, if it has one.

You need to use both to get what the user has written inside of the input tag.

Showing output

Add a tag with an ID, like so

<div id='output'></div>

Inside any function, change its innerHTML

var output = document.querySelector('#output');
output.innerHTML = "Hello!";