JavaScript from Scratch: Getting Your Feet Wet

Preview:

DESCRIPTION

The first part of an 8 part series covering the basics of the JavaScript language. This presentation covers variables, conditionals, loops and functions.

Citation preview

JavaScript From Scratch“Getting Your Feet Wet”

Agenda

• Variables

• Conditionals

• Loops

• Functions

Variables are...

• Storage Containers for Data

• Someone’s name

• A username/password

• The current time

• ... or anything else your application needs

var password = ‘mike is awesome’;

var name = ‘Mike G’;var age = 25;var isCool = true;

Conditionals are...

• A way to execute code conditionally

• If something is true, do this

• Otherwise, do that

var age = 25;

if (age < 21) { alert(‘Go home’);}

var age = 25;

if (age < 21) { alert(‘Go home’);}else { alert(‘Two drink minimum’);}

Loops

• Loops allow code to run repeatedly

• Over and over and over...

• But only upon a condition

var start = 10;var stop = 20;var counter = start;

while (counter <= stop) { alert(counter); counter = counter + 1;}

About those operators

=var foo = 100;

About those operators

==(foo == 100)

About those operators

<(age < 21)

About those operators

>(calories > 2000)

About those operators

<=(age <= 21)

About those operators

>=(calories >= 2000)

About those operators

&&(age >= 25 && age <= 50)

About those operators

||(name == ‘mike’ || name == ‘joe’)

Functions

• Store “blocks” of code so they can be reused later

• Are one of the most powerful features of the JavaScript language

function add () { alert(2 + 2);}

add();

function add (num1, num2) { alert(num1 + num2);}

add(2, 2);add(42, 10);add(123, 0);

function add (num1, num2) { return num1 + num2;}

var sum1 = add(2, 2);var sum2 = add(42, 10);var sum3 = add(123, 0);

Review

• Variables...

• Store data

• Begin with a var

• Are given names

• Are assigned values with =

Review

• Conditionals...

• Fork code execution based on a condition

• Begin with an if

• Condition enclosed in (parenthesis)

• Blocks are enclosed in {curly braces}

Review

• Conditionals...

• Can use else to catch a failed conditional

Review

• Loops...

• Repeatedly execute blocks of code

• Execute conditionally

• Come in many flavors:

• while, for, for in, do while

Review

• Functions...

• Store code for later use

• Can accept input parameters (arguments).

• Can send output (return values).

Homework

• Build a micro-library which performs basic math operations

• Functions should accept arguments and return the result of the math operation

Homework

• Required Functions:

• add (num1, num2)

• subtract (num1, num2)

• multiply (num1, num2)

• divide (num1, num2)

Homework

• Required Functions:

• square (num)

• increment (num)

• decrement (num)

• power (num, power)

Recommended