The Fundamentals of Javascript

The Fundamentals of Javascript

The Fundamentals of Javascript

The exercises repo can be found here:

github.com/cdepman/April2015JavascriptWorkshop

Open index.html in the top level directory.

Javascript, formally known as ECMAScript 5.1, is a fast growing, multi paradigm programming  language. It is a popular front end scripting language (used on almost any webpage you can think of!), but is now becoming a popular option for building servers using Node.js. Node.js is now used as a server side platform by companies like Microsoft, Yahoo!, Walmart, SAP, LinkedIn,  and PayPal.

The Fundamentals of Javascript

JS: Intro

JS runs natively on all modern web browsers, including the ones on your smart phones. Web browsers have a built-in javascript interpreter that reads and executes JS code.

You can use the JavaScript Console REPL provided by
Firefox Developer Tools or Chrome Developer Tools
to write, run and test any small piece of JavaScript code/function/program.

The Fundamentals of Javascript

JS: Intro

The Fundamentals of Javascript

<Hello World! Exercise>

The Fundamentals of Javascript

Tip:

Follow along by trying out all the code examples in your console. Practice makes perfect!

 

Building Blocks:

Variables, Operators and Expressions

The Fundamentals of Javascript

Building Blocks: Variables

A variable is a storage location paired with an associated name (an identifier). It contains some quantity or information referred to as a value. We use the variable name to reference the stored value.

 

In Javascript, we declare variables with the keyword var. The name cannot have spaces and cannot start with a number.

var quantitySold = 5;
var price = 2.50;
var totalSales = quantitySold * price;

The Fundamentals of Javascript

var a;                // declaration without assignment: default value is 'undefined'
var b = "Hello!";     // assignment to a value
var c = 1;            // assignment to a value

a

undefined

b

"Hello!"

c

1

identifier (name)

value

Variable Declaration (var) and Assignment (=):

 

The Fundamentals of Javascript

Building Blocks: Variables

The Fundamentals of Javascript

Building-Blocks: Variables

5 Primitive Types:

var isAwake = true;                   // boolean
var isAsleep = false;                 // boolean
var firstName = "John";               // string
var location = "Capetown";            // string
var age = 29.4;                       // number
var children = 0;                     // number
var relationShipStatus;               // undefined
var job = null;                       // null

Booleans are binary: true or false

Strings are characters, words, and sentences in quotes

Numbers are whole or floating-point

Undefined is for things that haven't been assigned value, yet

Null is assigned to things that are explicitly non-existent

 

var a = 6 + 2;           // addition operator
var b = a / 2;           // division operator
var c = ( 11 - b ) * 3;  // subtraction and multiplication
                         // operators

a

8

b

4

c

??

identifier (name)

value

Mathematical Operators are symbols that represent computations like addition, multiplication and division.

The Fundamentals of Javascript

Building Blocks: Operators

var a = 6 % 2;           // 2 goes into 6 evenly, 3 times, so no remainder
var b = 10 % 7;          // 7 goes into 10 once, leaving a remainder of 3
var c = 99 % 1;          // 1 never leaves a remainder
var d = 39 % 37;         // ??

a

0

b

3

c

0

identifier (name)

value

Special Mathematical Operator: Modulo

 The modulo operation finds the remainder after repeated division of one number by another

The Fundamentals of Javascript

Building Blocks: Operators

d

??

The Fundamentals of Javascript

Building-Blocks: Operators

Special String Behavior:

var firstName = "Barack";
var lastName = "Obama";
var middleName = "Hussein";

console.log(firstName + " " + middleName + " " + lastName);
// Barack Hussein Obama

Strings can be added together - this is called concatenation

var b = 12 - 3;    // expression evaluates to 9 and gets stored into b
var c = 1 + b;    

b

c

??

identifier (name)

value

An expression is a combination of values, variables, operators, and calls to functions. When evaluated, an expression produces, or returns, a value that can be assigned to another variable.

The Fundamentals of Javascript

Building Blocks: Expressions

9

The Fundamentals of Javascript

<Variables, Operators and

Expressions Exercise>

Control Statements

The Fundamentals of Javascript

Control Statements

Control statements help us with the flow and logic of our code. Using control statements, we can have the computer make decisions based on certain conditions, or repeat certain operations until a certain condition is met. We'll be going over two main control types: Conditionals and Loops. All control statements make use of Booleans.

The Fundamentals of Javascript

Control Statements

Basics:

Comparison Operators are symbols used to test conditions for true or false.

The Fundamentals of Javascript

==

===

!=

!==

>

<

>=

<=

 

"5" == 5;             // true
"5" === 5;            // false
"mary" != "maryanne"; // true
9 !== 9;              // false
8 > 4;                // true
3 < 3;                // false
4 >= 4;               // true
100 <= 99;            // false

equal to

strict equal to

not equal to

strict not equal to

greater than

less than

greater or equal to

less or equal to

 

Control Statements

Basics:

Logical Operators are symbols used to test multiple conditions at once.

The Fundamentals of Javascript

&&

||

 

true && true;         // true
true && false;        // false
1 === 3 || 4 === 4;   // true
0 > 1 || 5 < 3;       // false

AND : both conditions must be true

OR : one of the conditions must be true

 

Control Statements

A Special Logical Operator:

The Fundamentals of Javascript

!

!(8 < 4);             // true
!true;                // false
!false;               // true
!(5 === 5);           // false

NOT : inverts true to false and false to true 

 

Control Statements

if (condition1){

    // do something if condition1 is true

} else if (condition2) {

    // do something else if condition2 is true

} else {

    // do something else if previous conditions are not true

}

if/else:

The Fundamentals of Javascript

Control Statements

var moneyInMyWallet = 700;
var priceOfSteak = 1200;
var priceOfChips = 300;

if (moneyInMyWallet >= priceOfSteak){

    console.log('You can afford a steak!');

} else if (moneyInMyWallet >= priceOfChips) {

    console.log('You can afford chips!');

} else {

    console.log('You cannot afford steak or chips :('):
}

Example:

The Fundamentals of Javascript

<Conditionals Exercise>

The Fundamentals of Javascript

Control Statements

var y = 0;
while (y < 10){
    console.log(y);
    y++;
}

The While Loop

The Fundamentals of Javascript

Initially, we set a variable equal to a start value, then we set a continue condition in parentheses after the keyword 'while'. Until that condition is false, we'll keep executing the code inside of the while loop. We can increment (or decrement) the conditioned variable inside of the loop.

The Fundamentals of Javascript

for (var i = 0; i < 10; i++){
    console.log(i);
}

Control Statements

The For Loop

The 'for' loop is a more concise version of a while loop. After the 'for' keyword, we define a start value for a new variable, followed by a semicolon, then a continue condition for the variable followed by a semicolon, then an increment/decrement rule. Inside of the for loop, we have access to the variable as it changes.

The Fundamentals of Javascript

<Loop Exercise>

Functions

The Fundamentals of Javascript

Functions

var doSomethingComplex(input){
    result1 = calculation1(input);
    result2 = calculation2(result1);
    result3 = calculation3(result2);
    return result3;
}

doSomethingComplex("Charlie");
doSomethingComplex("Mary");
doSomethingComplex("Moses");

Functions are a powerful way to package sets of code/calculations that we want to reuse with different inputs. We give that set of code a name and then we can call/invoke it as much as we like afterward by referring to it and passing it input. 

The Fundamentals of Javascript

Functions

var prependHello = function(input){
    return "hello " + input;
}

var output = prependHello("world")
console.log(output);
// hello world

Function Definition

The Fundamentals of Javascript

Functions take input data, perform operations on that data, and output some sort of result.

Functions

var prependHello = function(input){
    return "hello " + input;
}

var functionCallResult = prependHello("world");

console.log(functionCallResult);
// hello world

Functions usually accept a number of inputs, called 'parameters'. They have an output as well, specified by the return keyword. When we call/invoke a function (an expression!) , we pass in 'argument' values that get assigned to variable names we specified in the 'parameters' of our function definition. The return value of an invoked function can then be set into a variable using the assignment operator.

The Fundamentals of Javascript

Functions

var prependHello = function(input){
    console.log("hello " + input);
}

var functionCallResult = prependHello("world");
// hello world
console.log(functionCallResult);
// undefined

var y = 0;
var addXToY = function(x){
    y += x;
}

console.log(addXToY(10));
// undefined
console.log(y);
// 10

Functions that don't have an explicit return statement return undefined by default. Those functions usually manipulate data in a different way - through 'side effects'.

The Fundamentals of Javascript

<Function Exercise>

The Fundamentals of Javascript

Data Structures:

Objects and Arrays

The Fundamentals of Javascript

Objects and Arrays

Arrays are data structures that hold elements (usually variables or other data) in an ordered sequence of numerical indices. The index starts at 0 - this is known as zero-based-indexing. We can access elements in an array by referring to them by their index.

The Fundamentals of Javascript

var myArrayOfCousins = ['mary', 'jennifer', 'carl', 'frank];

console.log(myArrayOfCousins[0]); // mary
console.log(myArrayOfCousins[2]); // carl

index 0

index 1

index 2

index 3

Objects and Arrays

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];

console.log(rainbowColors.length); // 7

console.log(rainbowColors[1]); // Orange

var arraysHoldAnything = ['string', ['array'], {object: 'object'}, 88, false];

Array Example:

The Fundamentals of Javascript

*Arrays have an important property,  length, that let's us know how many elements are in the array. This is extremely useful in setting a stop condition in a for loop if we want to access each item in the array.

Objects and Arrays

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];

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

// Red
// Orange
// Yellow
// Green
// Blue
// Indigo
// Violet

For-looping over an array:

The Fundamentals of Javascript

<Array Exercise>

The Fundamentals of Javascript

Objects and Arrays

Objects are data structures that hold key-value pairs. Arrays are limited to ordered, numerical keys, but Object keys/properties can be almost any unique string you can think of, in no particular order. You assign a value to a key/property, and then use that key to look up the value.

The Fundamentals of Javascript

var myObject = {"favoriteNumber": 42};

console.log(myObject["favoriteNumber"]); // 42

key

value

key/property lookup

Objects and Arrays

var friendsCountries = { 
    Litizie: 'Kenya', 
    Frank: 'Kenya', 
    Shawn: 'USA', 
    Walter: 'UK', 
    Hassan: 'Canada',
    "Sarah": 'Brazil'
};

console.log(friendsCountries['Litizie']); // Kenya
console.log(friendsCountries['Hassan']); // Canada
console.log(friendsCountries.Walter); // UK
console.log(friendsCountries.Sarah); // Brazil

friendsCountries.Moses = 'Uganda';
friendsCountries["Jackie"] = 'Nigeria';

The Fundamentals of Javascript

Javascript will automatically convert keys to strings when you're defining an Object. Property/Key assignments and lookups can also be done using 'dot' notation instead of bracket notation.

Objects and Arrays

var Robot = {
    name: 'eR42',
    model: 'Basic Medical Bot',
    homeHospital: 'Nairobi General',
    instructionSet: medRobotV14,
    heal: function(bodypart){.......},
    greet: function(patient){.......},
    sleep: function(wakeTime){.......}
};

Object values can be anything - even functions! We call these methods.

The Fundamentals of Javascript

Objects and Arrays

var Me = {
    name: 'Charlie',
    greet: function(){
        console.log('Hi, my name is ' + this.name);
    }
};

Inside of an object's method, we can use a special keyword called this. This refers to the object itself and we can use it to access the method's own keys/properties. 

The Fundamentals of Javascript

<Objects Exercises>

The Fundamentals of Javascript

JS Libraries

The Fundamentals of Javascript

JS Libraries

The Fundamentals of Javascript

Libraries are external collections of code that give our own code access to powerful methods and functionality. We can load them into our code using a <script> element - either from a local file or from a file hosted on a webserver. Then we need to familiarize ourselves with their API or Application Programming Interface. That is, we need to learn what methods they expose to us, and how we can use them.

JS Libraries

The Fundamentals of Javascript

jQuery is the most used Javascript library in the world. It is used on millions of web pages to create interactive user interfaces. Let's get familiar with some of its basic functionality and syntax.

JS Libraries

The Fundamentals of Javascript

When we load the jQuery script, $ is the global method that is exposed to us and is the main way we'll be interfacing with the jQuery API. In the most basic sense, we use the $ method to select HTML/DOM elements and then manipulate them with jQuery's built-in methods.

JS Libraries

The Fundamentals of Javascript

The first thing we do in jQuery is to select an element we want to perform an action on. To select an element we pass its HTML element name ( 'div'), its class name ('.myClass'), or its ID name ('#myID') as a string argument. Then we can use a jQuery method to animate it or change its CSS properties. 

$('.myClass').css('color', 'green')   
// class element selection and CSS property manipulation

JS Libraries

The Fundamentals of Javascript

If we want to set up an event handler, we select the element and use a listener method. Into that listener method, we pass a function - we can think of that as passing in an action - that we want to perform if that event is triggered.

$('#myID').click(function(){
    $('#myID').animate('height', '+=50px');
});

// ID element selection and event handler setup

<jQuery Exercises>

The Fundamentals of Javascript

Made with Slides.com