by Danny, Joep & Tino

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;

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

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

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);

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';

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];

Iterate through an array 

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

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

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;
}

Thanks for listening!
Any questions?

JavaScript Hybride

By CodePamoja

JavaScript Hybride

Introduction to JavaScript

  • 52