Introduction to

Javascript

A bit of history...

1995

LiveScript

1996-99

ECMA 1

Netscape

2002

JSON

2006

jQuery

GWT

2009-11

NodeJS

ECMA 5

2020

Coffeescript

Firebug

Mocha

ECMA 2

ECMA 3

AngularJS

ReactJS

VueJS

2012-2019

JAM

* ECMA = European Computer Manufacturers' Association

ECMA 6-10

Javascript

Javascript is the programming language of the web a part of the well known trio that all web developers must learn:

- HTML to specify the content

- CSS which is the presentation layer

- JavaScript which adds the behaviour

Javascript is used to make your web pages more interactive & give them some special effects.

 

Javascript is a High-Level, Interpreted, Dynamic, Untyped, Prototype-based, Scripting language

Javascript

JS - Statements

console.log('Hello World!');

var greeting;

x = 5;

var myDogs = ["Bobby", "Tuna", "Pedro"];


alert(myDogs.length)

Each instruction in JS is a "statement":

JS - Variables

// Declare the variable and then initialize it in 2 statements
var x;
x = 5;
console.log(x); // It will print "5"

// Declare the variable and then initialize it in 1 statement
var x = 5;
console.log(x); // It will print "5"

// We can change the value of a variable
x = 3
console.log(x); // It will print "3"

We use variables to store data:

JS - Variable names

// valid variables names
var numPeople, $mainHeader, _num, _Num;

// not valid variables names
var 2coolForSchool, soHappy!;

Variables...

  • ...begin with letters, $ or _
  • ...should only contain letters, numbers, $ and _
  • ...are case sensitive.
  • ...cannot be the same as reserved words.
  • ...should be clear and meaningful
  • ...should have a format (camelCase, snake_case, PascalCase, ...etc)
  • ...should follow the same naming convention across the whole application.

JS - Primitive data types

// string: an immutable string of characters:
var greeting = 'Good morning!';
var email = "adrian.bolonio@gmail.com";
console.log(email.length); // It will print "24"
console.log(email[0]); // 'a'
console.log(email[email.length-1]); // 'm'

// number: whole (6, -102) or floating point (5.8737):
var age = 35;
var pi = 3.14;

// boolean: Represents logical values true or false:
var isPossible = true;
var hasResults = false;

// undefined: Represents a value that hasn't been defined.
var notDefinedYet;

// null: Represents an explicitly empty value.
var numberOfCoins = null;

Variable can have different primitive types:

JS - Expressions

// Declare the variable and then initialize it in 2 statements
var x;
x = 5; // x = 5
x = 3 + 5; // x = 8
var y = 2 * x; // y = 16

var name = 'Adrián';
var greeting = 'Hello ' + name; // greeting = "Hello Adrián"

Variables can also store the result of any "expression":

JS - Functions

function greet() {
  console.log('Hello!!');
}

// You can call the function multiple times
greet() // It will print "Hello!!"
greet() // It will print "Hello!!" 
greet() // It will print "Hello!!" 


// Be aware of Circular Dependencies a.k.a. infinite loops
 function chicken() {
  egg();
}

function egg() {
  chicken();
}

egg();

Functions are re-usable collections of statements:

JS - Functions

function greet(name) {
  console.log('Hello ' + name);
}

greet("Adrián") // It will print "Hello Adrián"
greet("Elena") // It will print "Hello Elena"



function add(x, y) {
  console.log(x + y);
}

add(7, 21); // It will print "28"

// You can also pass variables
var n = 10;
add(3, n); // It will print "13"

Functions can accept any number of named arguments:

JS - Functions

function add(x, y) {
  return x + y;
}

var z = add(7, 21);
console.log(z) // It will print "28"


var n = 10;
var z = add(3, n);
console.log(z) // It will print "28"

// You can use function calls in expressions
var p = add(2, 2) + add(3, 2);
console.log(p) // It will print "9"


// You can even call functions inside function calls
var z = add(add(2, 2), add(3, 2));
console.log(z) // It will print "9"

The return keyword returns a value to whoever calls the function (and exits the function):

JS - Scope

// A variable with "local" scope
function add(x, y) {
  var localResult = x + y;
  console.log("The local result is: " + localResult);
}

add(5, 7);
console.log(localResult);  // ReferenceError

// ---------------------------------------

// A variable with "global" scope:
var globalResult;

function add(x, y) {
  globalResult = x + y;
  console.log("The global result is: " + globalResult);
}

addNumbers(5, 7);
console.log(globalResult); // It will print "12"

JavaScript variables have "function scope". They are visible in the function where they're defined:

JS - comparison operators

Use these operators to compare two values for equality, inequality, or difference

Operator Meaning True expressions
== Equality x == 28
=== Strict Equality x === 28
!= Inequality x != 29
!== Strict inequality x !== '28'
> Greater than x > 25
>= Greater than or equal x >= 28
< Less than x < 30
<= Less than or equal x <= 28

Common mistake: Do not confuse = (the assignment operator) with ==

JS - logical operators

Use these operators to compare two values for equality, inequality, or difference

Operator Meaning True expressions
&& AND posNum > 0 && negNum < 0

4 > 0 && -2 < 0
|| OR posNum > 0 || negNum > 0

4 > 0 || -2 > 0
! NOT !(posNum === negNum)

!(posNum < 0)

When combining together multiple conditions, use parentheses to group:

var posNum = 4;
var negNum = -2;
var age = 28;
if ((age >= 0 && age < 3)  || age > 90) {
  console.log('You are not that old!');
}

JS - short-circuit Evaluation

JS evaluates logical operators from left to right and stops evaluating as soon as it knows the answer.

// (false && anything) => false
// (true || anything) => true

var nominator = 5;
var denominator = 0;

if (denominator != 0 && (nominator/denominator > 0)) {
  console.log('Thats a valid, positive fraction');
}


if(nominator > 2 || nominator < 10) {
  console.log('The number is between 2 and 10');
}

JS - conditions

Use if to tell JS which statements to execute, based on a condition

var x = 5;

if (x > 0) {
  console.log('x is a positive number!');
} else if (x === 0) {
  console.log('x is a 0!');
} else {
  console.log('x is a negative number!');
}

Use else to give JS an alternative statement to execute

Or you can use else if when you have multiple exclusive conditions to check.

JS - loops

The while loop tells JS to repeat statements until a condition is true

var x = 0;
// while (condition)
while (x < 5) {
  console.log(x);
  x = x + 1;
}

The for loop tells JS to repeat statements a specific number of times

// for (init, condition, step)
for (var i = 0; i < 5; i = i + 1) {
  console.log(i);
}

// You can stop a for loop using "break;"
for (var current = 100; current < 200; current++) {
  console.log('Testing ' + current);
  if (current % 7 == 0) {
    console.log('Found it! ' + current);
    break;
  }
}

// current++ => current = current + 1

JS - switch

The switch tells JS to execute statements in a case-by-case situation

switch(favouriteDog){
  case 'Tobby':
    console.log('I love you Tobby');
    break;
  case 'Chewie':
    console.log('You are my fav Chewie');
    break;
  case 'Pedro':
    console.log('There is no one like you Pedro');
    break;
  default:
    console.log('I have no preferences');
}

JS - arrays

An array is a type of data-type that holds an ordered list of values, of any type

// var arrayName = [element0, element1, ...];
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
var raceWinners = [33, 72, 64];
var myDogs = ["Bobby", "Tuna", "Pedro"];

// The length property reports the size of the array
console.log(rainbowColors.length); // It will print "7"

// You can access items with "bracket notation".
// IMPORTANT: The index starts at 0.
var arrayItem = arrayName[indexNum];
var firstColor = rainbowColors[0]; // firstColor = "Red"
var lastColor = rainbowColors[6]; // lastColor = "Violet"

// You can also use bracket notation to change the item in an array
myDogs[0] = "Tomy"; // myDogs = ["Tomy", "Tuna", "Pedro"]
// Or to add to an array
myDogs[3] = "Lemon"; // myDogs = ["Tomy", "Tuna", "Pedro", "Lemon"]
// You can also use the push method
myDogs.push("Pancho"); // myDogs = ["Tomy", "Tuna", "Pedro", "Lemon", "Pancho"]

JS - arrays

Use a for loop to easily process each item in an array

var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
for (var i = 0; i < rainbowColors.length; i++) {
  console.log(rainbowColors[i]);
}

// Or a string
var rainbowColorsLetters = 'ROYGBIV';
for (var i = 0; i < rainbowColorsLetters.length; i++) {
  console.log(rainbowColorsLetters[i]);
}

QUESTION: Why do we use a for loop and not a while loop?

JS - objects

Objects are a data type that let us store a collection of properties and methods

var person = {
  name: "Adrián",
  surname: "Bolonio",
};


var person = {
  name: "Adrián",
  surname: "Bolonio",
  age: 35,
  likes: ["sleeping", "football"],
  birthDaye: {
    "month": 7,
    "day": 10,
    year: 1985
  }
};

JS - objects access

Access properties using "dot notation"

var person = {
  name: "Adrián",
  surname: "Bolonio",
};

person.name // Adrián
var person = {
  name: "Adrián",
  surname: "Bolonio",
};

var myName = person.name // Adrián
var myAge = person.age // undefined

Access properties using "array notation"

var person = {
  name: "Adrián",
  surname: "Bolonio",
};

var myName = person["name"] // Adrián
var myAge = person["age"] // undefined

Non-existent properties will return undefined

JS - changing objects

Use dot or bracket notation with the assignment operator to change objects

var person = {
  name: "Adrián",
  surname: "Bolonio",
};

person.name // Adrián
var person = {
  name: "Adrián",
  surname: "Bolonio",
};

person.name = "John"
person.age = 35
delete person.surname;


// Now the object looks like this
person = {
  name: "John",
  age: 35,
};

JS - array of objects

Since arrays can hold any data type, they can also hold objects

var person = {
  name: "Adrián",
  surname: "Bolonio",
};

person.name // Adrián
var people = [
  {
    name: "Adrián",
    surname: "Bolonio",
  },
  {
    name: "John",
    surname: "Doe",
  }
]

for (var i = 0; i < people.length; i++) {
  var person = people[i];
  console.log(person.name + ' ' + person surname);
}

JS - objects as arguments

Just like other data types, objects can be passed into functions

var person = {
  name: "Adrián",
  surname: "Bolonio",
};

person.name // Adrián
var person = {
  name: "Adrián",
  surname: "Bolonio",
};

function getNameAndSurname(p) {
  p.name = "John"
  console.log(p.name + ' ' + p surname);
}

getNameAndSurname(person);

getNameAndSurname({
  name: "Adrián",
  surname: "Bolonio",
});

console.log(person)

JS - objects methods

Object properties can also be functions. Object functions are called "methods"

var person = {
  name: "Adrián",
  surname: "Bolonio",
};

person.name // Adrián
var person = {
  name: "Adrián",
  surname: "Bolonio",
  shout: function() {
    console.log("AAAAHHHH!!!")
  }
  eat: function(food) {
    console.log("I am eating " + food);
  }
};

Call object methods using dot notation

person.shout(); // It will print "AAAAHHHH!!!"
person.eat("Apple"); // It will print "I am eating Apple"

Questions?

JavaScript & the DOM (Document-Object Model)

Including JS in HTML

You can write your JS inside a script tag in your HTML file

<html>
  <body>
    <script>
      console.log("I am Javascript running on a web page!");
    </script>
  </body>
</html>

You can also write your JS in a separate file and reference it from your HTML file via a script tag

<html>
  <body>
    <script src="app.js"></script>
  </body>
</html>

What is the DOM?

DOM stands for "Document Object Model" (a map of our HTML document).

 

Defines the logical structure of an HTML document and how it is accessed and manipulated.

 

Anything found in an HTML or XML document can be accessed, changed, deleted, or added by a programmer using the DOM.

DOM Access Methods

You can use the following methods to access elements in the DOM

// Finding DOM nodes by id:
document.getElementById(id);

// Finding DOM nodes by tag name:
document.getElementsByTagName(tagName);

// Finding DOM nodes by class name:
document.getElementsByClassName(className);

// Finding DOM nodes by query selector:
document.querySelector(cssQuery);
document.querySelectorAll(cssQuery);

DOM Access Methods

Selecting Nodes From the DOM

<ul id="hobby-list">
  <li class="hobby">Playing the banjo</li>
  <li class="hobby">Paddleboarding</li>
</ul>
// By Id
var hobbiesList = document.getElementById('hobby-list');

// By Tag Name
var hobbies = document.getElementsByTagName('li');

// By Class Name
var alsoHobbies = document.getElementsByClassName('hobby');

// By CSS Query
var firstHobby = document.querySelector('ul li.hobby');
var againAlsoHobbies = document.querySelectorAll('ul li.hobby');

DOM Access Methods

Returning Element vs. Array of Elements

<ul id="hobby-list">
  <li class="hobby">Playing the banjo</li>
  <li class="hobby">Paddleboarding</li>
</ul>
// getElementById() and querySelector()return a single element:

var hobbiesList = document.getElementById('hobby-list');
var firstHobby = document.querySelector('ul li.hobby');


// getElementsByClassName(), getElementsByTagName(), and querySelectorAll()
// return a collection of elements (which acts like an array):
var myHobbies = document.getElementsByClassName('hobby');
var firstHobby = myHobbies[0];

var catNames = document.querySelectorAll('ul li.catname');
var firstCatName = catNames[0];

DOM Access Methods

Manipulating a DOM Node's Attributes

<img id="kitty" src="./img/kitty.jpg">
// Changing the src of an image:

// Finding the DOM node by id
var catImage = document.getElementById('kitty');
// Assigning the new image url to the DOM node
catImage.src = "./img/cat.jpg";

// Changing the className of a DOM node:

// Finding the DOM node by id
var catImage = document.getElementById('kitty');
// Assigning the new class to the DOM node
catImage.className = "cat";

You can access and change the attributes of a DOM node using dot notation.

<img id="kitty" class="cat" src="./img/cat.jpg">

DOM Access Methods

Manipulating a DOM Node's Styles

#kitty {
  color: red;
  background-color: pink;
  padding-top: 10px;
}
var catImage = document.getElementById('kitty');
catImage.style.color = 'red';
catImage.style.backgroundColor = 'pink';
catImage.style.paddingTop = '10px';

You can access and change the styles of a DOM nodes via the style property. CSS property names with a "-" must be camelCased and number properties must have a unit.

Applying the Same Styles via JavaScript

DOM Access Methods

Manipulating a DOM Node's Inner HTML

var pageNode = document.body;
console.log(pageNode.innerHTML);

Each DOM node has an innerHTML attribute that contains the HTML of all its children

You can set innerHTML yourself to replace the contents of the node:

pageNode.innerHTML = "<h1>Oh, no! Everything is gone!</h1>"

You can also just add to the innerHTML, instead of replacing it altogether:

pageNode.innerHTML += "P.S. Please do write back.";

Creating DOM Nodes

The document object also allows us to create new nodes from scratch:

// document.createElement(tagName);
// document.createTextNode(text);
// document.appendChild(childToAppend);

var body = document.body;

// append a new image
var newImg = document.createElement('img');
newImg.src = 'http://placekitten.com/400/300';
newImg.style.border = '1px solid black';
body.appendChild(newImg);

// append a new paragraph
var newParagraph = document.createElement('p');
var newText = document.createTextNode('Squee!');
newParagraph.appendChild(newText);
body.appendChild(newParagraph);

Questions?

JavaScript

Events

Event Types

The browser triggers many events. For example:

  • Mouse events (MouseEvent): mousedown, mouseup, click, dblclick, mousemove, mouseover, mousewheel, mouseout, contextmenu
  • Touch events (TouchEvent): touchstart, touchmove, touchend, touchcancel
  • Keyboard events (KeyboardEvent): keydown, keypress, keyup
  • Form events: focus, blur, change, submit
  • Window events: scroll, resize, hashchange, load, unload

Adding Event Listeners

// domNode.addEventListener(eventType, eventListener);

// Find the DOM node by id
var addButton = document.getElementById('addButton');

// Create a function
var onButtonClick = function() {
  ... // statements
};

// Add the "click" eventListener to the DOM node
// So everytime the user clicks, the "onButtonClick" function will be executed
addButton.addEventListener('click', onButtonClick);
<button id="addButton">+</button>

Processing Form Input 

// domNode.addEventListener(eventType, eventListener);

// Find the DOM node by id
var squareButton = document.getElementById('squareButton');

// Create a function
var onButtonClick = function() {
  // Find the DOM node by id
  var number = document.getElementById("number").value;
  alert(number * number)
};

// Add the "click" eventListener to the DOM node
// So everytime the user clicks, the "onButtonClick" function will be executed
squareButton.addEventListener('click', onButtonClick);
<input id="number" type="number">
<button id="squareButton">^2</button>

Assignment 2 (no points)

* Add ids to the form (inputs...)

* Add ids to the "sent data" items to display the data

* Create an onClick event with a function to retrieve all data from the form

* Add the event to the submit button

* Fill the the "sent data" elements with the correct data from the form.

 

If you have problems or doubts, please DM me in Teams

Javascript

By Adrián Bolonio

Javascript

  • 802