Introduction

What is JavaScript?

Multi-paradigm script language

Why learn JavaScript?

This is the only script language that is supported in all browsers

'use strict'

What is it?

  • Defines that JavaScript code should be executed in "strict mode"
     
  • Was designed to be compatible with older versions of JavaScript
     
  • You cannot use undeclared variables in strict mode
     
  • Can be declared at the beginning of a script or inside a function
/* 
    declared at the beginning of script 
    global scope
*/

'use strict';

function functionName() {
    // code block here
}
/*
    declared inside a function
    local scope
    useful for browser-, client-side 
    projects and modular code
*/

function functionName() {
    'use strict';
    // code block here
}

Why use it?

  • Prevents you from writing bad JavaScript
     
  • Changes previously accepted "bad syntax" into real errors
     
  • Examples what is not allowed in strict mode:
    • Using undeclared variables
    • Deleting variables, objects, functions and undeletable properties

Placement

How to include?

  • Inside the head and body tag
     
  • Inline or in external files
<!-- Recommended way of including JavaScript -->

<!DOCTYPE html>
<html lang="en">
    <head>
    </head>
    <body>
        <script type="text/javascript" src="script.js" ></script>
    </body>
</html>

Variables

What are variables?

  • Containers for storing data values
     
  • Can hold many data types: strings, arrays, objects
// an empty variable, also called undefined
var foo;

// variable with a string
var foo = 'This is a string';

// variable with a number
var foo = 10;

// boolean
var foo = false;

Naming conventions

  • Use camelCase
  • Always start with a letter
  • Can only contain letters, numbers, $ and _
  • Should clearly describe what it's used for
// Bad
var averylongname;
var p1;

// Good
var aVeryLongName;
var person1;

Booleans

What are booleans?

  • Represents one of two values:
    • true
    • false
// true
var foo = true;

// false
var foo = false;

Sending & capturing messages

Sending messages

  • A pop-up dialog
     
  • Directly onto the page "Hidden" messages to the console
// a pop-up dialogue
alert('This is a message');

// directly onto the page
document.write('This is a message');

// "hidden" message in the console
console.log('This is a message');

Capturing messages

  • Forms
     
  • Prompt command
// prompt command
prompt('How old are you?');

// prompt command in a variable
var age = prompt('How old are you?');

Concatenation

What is concatenation?

  • Method to combine 2 or more strings
     
  • It returns a new string containing the combined strings
// using the + to combine strings
var firstName = 'John';
var lastName = 'Doe';
var fullName = firstName + ' ' + lastName;

// using the concat() method
var firstName = 'John ';
var lastName = 'Doe';
var fullName = firstName.concat(lastName);

// output will be:
John Doe

Comments

What are comments?

  • Messages to explain what's happening in the code
  • Doesn't effect how your program works
  • Ignored by your browser
  • Useful for yourself and other developers
// Single-line comment

/*
  Multiple -line
  comment
*/

Statements

What is a statement?

  • Every single instruction is a statement
     
  • They end with a semicolon
     
  • Can be organised into code blocks

Conditions

  • Evaluating a situation by comparing values to see if the result is true or false
     
  • If a condition is met, it executes one or more statements

Conditional statements

if (10 === '10') { // condition
    console.log('foo'); // statement
} else { // condition
    console.log('bar'); // statement
}

Numbers

Type of numbers

  • Integers
  • Floating point numbers
  • Scientific notation
// Integers

10
3
-15
-989
0
// Scientific notation

5e-6 // Which is .000005
3e+6 // Which is 3000000
2e+2 // Which is 200
// Floating point numbers

4.56
-0.9342
1.5
.26

Parsing numbers

  • ParseInt convert to integer
     
  • ParseFloat convert to decimal
// ParseInt

parseInt('210');
// Outcome = 210


parseInt('This is 210');
// Outcome = NaN


parseInt('2.10');
// Outcome = 2
// ParseFloat

parseFloat('5.10');
// Outcome = 5.10

Math

  • Addition
  • Subtraction
  • Multiplication
  • Division
// Addition                  // Multiplication
10 + 5                       10 * 5


// Subtraction               // Division
10 - 5                       10 / 5







Storing numbers & calculate

var totalScore;

var playerScore1 = 10,
    playerScore2 = 5,
    playerScore3 = 6,
    playerScore4 = 2;

// Addition
totalScore = playerScore1 + playerScore2;
console.log(totalScore);

// Subtraction
totalScore = playerScore4 - playerScore3;
console.log(totalScore);

// Multiplication
totalScore = playerScore3 * playerScore1;
console.log(totalScore);

// Division
totalScore = playerScore1 / playerScore4;
console.log(totalScore);

What's the outcome?

var yourAge = prompt('What is your Age?'),
    myAge = 30,
    ourAge = yourAge + myAge;

console.log(ourAge);
var yourAge = prompt('What is your Age?'),
    myAge = 30,
    ourAge = parseInt(yourAge) + myAge;

console.log(ourAge);
var yourAge = 15,
    myAge = yourAge * 2,
    ourAge = myAge + yourAge;

console.log(ourAge);

Math Object

Operators

Different types

  • Arithmetic
     
  • Comparison
     
  • Logical
     
  • Conditional

Arithmetic

  • Used to perform arithmetic between variables and/or values
// addition: output = 15                   // modulus: output = 2
10 + 5;                                    12 % 5;

// subtraction: output = 45                // incement
145 - 100;                                 ++

// multiplication: output = 12             // decrement
2 * 6;                                     --

// division: output = 3
12 / 4;

Comparison

  • Used in logical statements to determine equality or difference between variables or values
==	// equal to	

===	// equal value and equal type (recommended)

!=	// not equal

!==	// not equal value or not equal type (recommended)

>	// greater than

<	// less than

>=	// greater than or equal to

<=	// less than or equal to

Logical

  • Used to determine the logic between variables or values
&&	// and


||	// or


!       // not

Conditional

  • Assigns a value to a variable based on a condition
if (condition) {
   action = 'do something';
} 
else {
   action = 'do something else';
}


// can be written as
action = (condition) ? 'do something' : 'do something else';

Functions

What is a function?

  • A block of code that you can run over and over again
     
  • Uses the same conventions as naming variables

Function declaration

  • Does not need a variable
     
  • Do not use a semicolon at the end
     
  • Visible inside the scope
// Declaring a function
function nameOfFunction () {
}


// Calling the function
nameOfFunction();

Function expression

  • Assign a function to a variable
  • Has no name after "function" -> anonymous function
  • End with an semicolon
  • Not visible outside of it's scope
// Declaring a function expression
var message = function() {
    var askAge = prompt('What is your age?');
    alert(askAge);
};


// Calling a function expression
message();

Return statement

  • Stops the execution of a function and returns a value from that function
     
  • Should be the last thing in a function
     
  • Can only return 1 thing

Arguments

  • Is stored inside a variable, called a parameter which you use inside a function
function myFavorite(band) {
    alert(band + ' is awesome!');
}

myFavorite('ColdPlay');
function myFavorite(band, serie) {
    alert(band + ' & ' + serie + ' are awesome!');
}

myFavorite('ColdPlay', 'Mr. Robot');

IIFE

  • Immediately-Invoked-Function-Expression
  • Function itself without a name will return undefined
  • It treats itself as an expressing
  • Doesn't clutter the global namespace
// Declaring a function, which then calls itself immediately
// It creates a new scope

(function() {
    
    function foo() {
        console.log('Text here');
    }
    
    foo();

})();

Cluttering global scope

  • Functions that are accessible in the global namespace could share the same name as variables from libraries
// Function expression
function foo() {
    console.log('foobar');
}

foo();

Closures

  • A function with access to its own private variables
     
  • You can create closures with the same variable name contained in each one of them
     
  • Variables are hidden from all of the functions
     
  • Avoid variable conflicts
// Create a function
function functionName() {

    // Private variable in functionName scope
    var totalDevs = 0;

    // An inner function that has access to the private variable
    function innerFunction() {
        totalDevs++;
        console.log('Total devs = ' + totalDevs);
    }
   
    return innerFunction;
}

// Create a new private scope every time "functionName" gets called
devCount = functionName();
devCount();

Loops

What's a loop?

  • Loops can execute a block of code a number of times
     
  • Type of loops:
    • for
    • for/in
    • while
    • do/while

For loop

  • Loops through a block of code a number of times
  • Statement 1: is executed before the loop starts.
  • Statement 2: defines the condition for running the loop.
  • Statement 3: is executed each time after the loop has been executed.
for (statement 1; statement 2; statement 3) {
    // code block to be executed
}

For/in loop

  • Loops through the properties of an object
var person = {
    firstName:"John", 
    lastName:"Doe", 
    age:25
}; 

var text = "";

var x;

for (x in person) {
    text += person[x];
}

While loop

  • Loops through a block of code while a specified condition is true
  • Runs till the condition is false
  • Will never run if condition is false to start with
  • Be aware of an endless/infinite loop
while (condition) {
    // code block to be executed
}
while (i < 10) {
    text += 'The number is ' + i;
    i++;
}

Do/while loop

  • Loops through a block of code while a specified condition is true
     
  • Will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested
do {
    // code block to be executed
}

while (condition);
do {
    text += 'The number is ' + i;
    i++;
}

while (i < 10);

Arrays

What's an array?

  • Also called a data structure and are used to store multiple values in a single variable
  • The brackets are called an Array literal
  • Can hold any combination of data types
  • Use the same rules for naming Array's as variables
  • Has a comma separated list of values Items are stored on an index position
var arrayName = [];

var arrayName = ['name1', 'name2', 'name3'];
// If you have a long list
var arrayName = [
    'name1',
    'name2',
    'name3',
    'name4',
    'name5',
    'name6'
];

Array methods

  • Convert Array's to strings
  • Popping and pushing
  • Shifting, changing and deleting elements
  • Splicing, joining and splitting an Array
  • Click here for more details
// Current Array
var arrayName = [22, 23, 24, 25, 26];

// Add data to Array 
arrayName.push(27);

// Result
arrayName = [22, 23, 24, 25, 26, 27];

Two-dimensional array

  • An array in an array
var list = [
    [1, 2, 3, 4], // index 0
    ['Phil', 'Peter', 'Mitchell'], // index 1
    [true, false] // index 2
];

Iterate through an array 

var developers = [
    'Phil',
    'Joe',
    'Ryan',
    'David',
    'Carla'
];

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

Combination

var developers = [
    'Phil',
    'Joe',
    'Ryan',
    'David',
    'Carla'
];

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

printDevelopers(developers);

Concatenate an array

var developers = [
    'Phil',
    'Joe',
    'Ryan'
];

var designers = [
    'Jeroen',
    'Kathy',
    'Billy'
];

developers.concat(designers);

// Output would be:
[
    'Phil',
    'Joe',
    'Ryan',
    'Jeroen',
    'Kathy',
    'Billy'
];

Objects

What's an object?

  • Containers for named values
     
  • Each object can have:
    • Properties
    • Events
    • Methods
// Object literal
var objectName = {};


var developer = {
    name: 'John',
    age: 30,
    hobbies: ['Coding', 'Gaming']
};

Properties

  • Could call it "characteristics" of an object
     
  • It has a name and a value
var person = {
    firstName: 'Klaas',
    lastName: 'Jansen',
    age: 30,
    job: 'Software developer'
};

Events

  • Could also be called "interaction"
     
  • When an event happens, can be used to trigger an action

Methods

  • An object property containing a function definition
     
  • Actions that can be performed on objects
var person = {
    firstName: 'Klaas',
    lastName: 'Jansen'
    age: 30,
    job: 'Software developer',
    fullName: function() { 
        return this.firstName + ' ' + this.lastName; 
    }
};

How to access an item?

  • Using the properties name as a string
     
  • Dot notation
var person = {
    name: 'John Doe',
    age: 30,
    profession: 'developer',
    hobbies: ['Coding', 'Gaming'],
    single: true
};

// Option 1: Using the properties name as string
person['name']
person['age']

// Option 2: Dot notation (more common!)
person.name
person.age

Notations

  • Literal notation (individual object)
     
  • Constructor notation (multiple objects)

Literal notation

  • Properties an methods can be added to the object afterwards
var person = {}

person.firstName = 'Klaas';
person.lastName = 'Jansen';
person.age = '30';
person.job = 'Software developer';
person.fullName = function() { 
        return this.firstName + ' ' + this.lastName; 
};

Create an object

  • A colon separates the name (key) and values
     
  • A comma separates each pair
var person = {
    firstName: 'Klaas',
    lastName: 'Jansen'
    age: 30,
    job: 'Software developer',
    fullName: function() { 
        return this.firstName + ' ' + this.lastName; 
    }
};

When and why to use?

  • For storing data between applications
     
  • Takes less space in your code
     
  • For global objects that set up information for a page

Constructor notation

  • The syntax for adding or removing properties and methods is the same
var person = new Object();

person.firstName = 'Klaas';
person.lastName = 'Jansen';
person.age = '30';
person.job = 'Software developer';
person.fullName = function() { 
        return this.firstName + ' ' + this.lastName; 
};

Create an object

  • A function can create multiple objects this keyword is being used in stead of the object name
function Person(firstName, lastName, age, job) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.job = job;
    this.fullName = function() {
        return this.firstName + ' ' + this.lastName;
    };
}

// Creating a new instance with the "new" keyword
var developer1 = new Person('Klaas', 'Jansen', 30, 'Software developer'); 
var developer2 = new Person('Timo', 'de Jong', 18, 'Front-end developer');

When and why to use?

  • A complex object might not be used in code
     
  • Object with similar used functionality within a page/application

Creating & changing

var person = {
    name: 'John Doe',
    age: 30,
    profession: 'developer',
    hobbies: ['Coding', 'Gaming'],
    single: true
};

person.name = 'Jane Doe';
person.age = 28;
person.email = 'jane.doe@mail.com';

console.log(person);

Iterate through items

var person = {
    name: 'John Doe',
    age: 30,
    profession: 'developer',
    hobbies: ['Coding', 'Gaming'],
    single: true
};

// Gives you access to the properties
for (var item in person) {
    console.log(item);
}

// Give you full access to all data in Object
for (var item in person) {
    console.log(item, ':', person[item]);
}

Arrays & objects

var developers = [
    {
        name: 'John',
        age: 20,
        skills: ['HTML', 'CSS', 'JavaScript']
    },
    {
        name: 'Jane',
        age: 25,
        skills: ['Java', 'PHP', 'AngularJS']
    }
];

Looping through

// An array with an object
var developers = [
    {
        name: 'John',
        age: 20,
        skills: ['HTML', 'CSS', 'JavaScript']
    },
    {
        name: 'Jane',
        age: 25,
        skills: ['Java', 'PHP', 'AngularJS']
    }
];


// Looping through with a for loop
for( var i = 0; i < developers.length; i += 1) {
    console.log(developers[i].name + ' is ' + developers[i].age + ' years old');
}

DOM

What is it?

  • Document Object Model
     
  • Is fully made out of objects
     
  • Specifies how browsers should create a model of an HTML page
     
  • Defines methods and properties to access and update content

DOM tree

  • Is stored in the browser's memory
     
  • Gets created when you load a page
     
  • Consists of four main types of nodes:
    • Document nodes
    • Element nodes
    • Attribute nodes
    • Text nodes

document

<html>

<head>

<body>

<title>

<link>

<h1>

<p>

<strong>

lorem ipsum

lorem ipsum

lorem ipsum

document

element

text

Document nodes

  • Used to navigate to access the other nodes
     
  • It's the starting point for all visits to the DOM tree
     
  • Every node is a descendant of the document node

Element nodes

By accessing element nodes you can reach attribute and text nodes

Accessing elements

It's possible to select an individual and multiple element nodes or moving an element node to a related node

// methods returning a single node
document.getElementById('id');
document.querySelector('css selector');


// methods returning a nodelist
document.getElementsByClassName('class');
document.getElementsByTagName('tagName');
document.querySelectorAll('css selector');

Creating elements

// creating a new element, a text node attach them
var newElement = document.createElement('<p>'),
    newContent = document.createTextNode('Hi all');

newElement.appendChild(newContent);

// place them into its position
var positionElement = document.getElementsByTagName('div')[0];
positionElement.appendChild(newElement);

Attribute nodes

  • Are part of elements that carry them, not called their children
     
  • Methods and properties can be used to easily read of change attributes

Attribute methods

// getting value of an attribute
var foo = document.getAttribute();

// check if element has an attribute
var foo = document.hasAttribute();

// set value
var foo = document.setAttribute();

// remote attribute
var foo = document.removeAttribute();


// example: find an element and get value of attribute
var foo = document.getElementById('bar').getAttribute('class');

Text nodes

  • Can be reached by accessing an element node first
     
  • Cannot have children
     
  • It's always a new branch of the DOM tree

Work with content

// retrieve or amend the content of a text node with nodeValue
var foo = document.getElementById('bar').firstChild.nodeValue = 'Hi all';

// collect or update text in the containing element with textContent
var foo = document.getElementById('bar').textContent = 'Hi all';

// access or amend content of an element incl. it's children
var foo = document.getElementById('bar').innerHTML = 'Hi all';

Scoping

Global scope

  • Can be used anywhere
     
  • Stored in memory as long as a page is loaded
     
  • Higher risk of naming conflicts
var size = 50 + 20;
document.write(size);

Local scope

  • Value of the variable can be different after running it again
     
  • Different functions can use the same variable names
     
  • Recommended, it uses less memory
function size(height, width) {
    var size = height + width;
    return size;
}

Errors

Error objects

  • Can help you find where the problems are
     
  • Built-in objects:
    • Error SyntaxError
    • ReferenceError
    • TypeError
    • RangeError
    • URIError
    • EvalError

Error

  • Generic error
     
  • Is the template for the other error objects

SyntaxError

  • "Syntax is not correct"
     
  • Often a result of a typo Examples:
    • Mismatching quotes
    • Missing comma's, brackets
SyntaxError: Unexpected EOF

ReferenceError

  • Variable is undeclared or out of scope
     
  • Example:
    • Names function is undefined
ReferenceError: Can't find variable: variableName

TypeError

  • Caused by trying to use a method or object that doesn't exist
     
  • Examples:
    • Method doesn't exist
    • DOM node doesn't exist
TypeError: 'null' is not an object

RangeError

  • Calling a function where the number is outside its range
     
  • Example:
    • Cannot create array with -1 items
RangeError: Array size is not a small enough positive integer

URIError

  • Character are not escaped in URI's
URIError: URI error

EvalError

  • Incorrect use of the eval() function
     
  • A rare error
     
  • Browsers often show another error

JavaScript (ES5)

By CodePamoja

JavaScript (ES5)

The basic fundamentals

  • 76