- Why Javascript?
- Powers most internet
- React, Angular, NodeJS
- Problems:
- Confusing
- Topics
- Theory
- Basics to complex
- How Javascript works behind the scenes
- Javascript in the browser: DOM manipulation and events
- Advanced Javascript: Objects and Functions
- Putting it all together: The Budget App Project
- Get ready for future: ES6/ ES2015
- Bonus: Coding challenges with solutions
- Bonus: Exam
- Brackets
- Themes
- Extension
- Autosave Files on Window Blur: save on leaving app
- Chrome
- View > Developer > JavaScript Console
console.log('Hello World!')
- Basics
- Variables
- Data flows
- Functions
- Objects
- ...
- JavaScript is a lightweight, cross-platform, object-oriented computer programming language
- Lightweight: less memory usage, simple syntax
- Cross-platform: multiple systems
- Object-oriented: Based on objects
- JavaScript is one of hte three core technologies of web development
- JavaScript is most commonly used as a part of webpages
- Today, JavaScript can be used in different places:
- Client-side: JavaScript was traditionally only used in the browser
- Server-side: Thanks to node.js, we can use JavaScript on the server as well
- JavaScript is what made modern web development possible
- Dynamic effects and interactivity
- Modern and complex web applications that we can interact with
- HTML: COntent
- NOUNS:
<p></p>
means "paragraph"
- NOUNS:
- CSS: Presentation (styling)
- ADJECTIVES:
p { color: red; }
`means "the paragraph text is red"
- ADJECTIVES:
- JS: Dynamic effects/programming
- Manipulation of content
- VERBS:
p.hide();
means hide the paragraph
-
Open Brackets
- Getting Started v Open Folder > JS Basics
-
Two ways to write JS
- Inline script:
- Inside html file
- External script:
- Separate file
- Inline script:
-
Inline scripting (M)
<script> console.log('Hello World!'); </script>
- Drawback:
- Difficult to maintain code
- Drawback:
-
Open the text file in Browser
- Inspect > Console
-
External script
-
New File >
script.js
console.log('Hello World!');
-
Linking
<script src="script.js"></script>
-
-
script.js
var name = 'John'; // var name = "John"; console.log(name); var lastName = 'Smith'; // Camel casing console.log(lastName); var age = 26; console.log(age); var fullAge = true; console.log(fullAge);
-
Data types
- Number: Always floating point numbers, for decimals and integers
- String: Sequence of characters, used for text
- Boolean: Logical data type that can only be
true
orfalse
(M) - Undefined (M): Data type of a variable which does nto have avalue yet
- Automatically assigned to variable that is not assigned a value yet
- Null (M): Also means 'non-existent'
- More specific
-
Dynamic typing:
- Javascript figures out data type on its own and on the fly
-
Comments
// single line /* multiple lines */
-
script.js
// Lecture: variables 2 var name = 'John'; // var is only for declaration var age = 26; console.log(name + age); console.log(age + age); // adds numbers var job, isMarried; console.log(job); // Prints 'undefined' job = 'teacher'; isMarried = false; console.log(name + ' is a ' + age + ' years old ' + job + '. Is he married? ' + isMarried + '.'); age = 'thirty six'; job = 'driver'; console.log(name + ' is a ' + age + ' years old ' + job + '. Is he married? ' + isMarried + '.');
-
Why Javscript converts to string?
- Type Coercion: JS Automatically converts datatypes
- Figures out to which type to convert and converts automatically
- Type Coercion: JS Automatically converts datatypes
-
Getting data from console:
var lastName = prompt('What is the last name?'); **(M)** console.log(lastName); alert(name + ' is a ' + age + ' years old ' + job + '. Is he married? ' + isMarried + '.');
-
script
// Lecture: operators var now = 2017; var birthYear = now - 26; birthYear = now - 26 * 2; console.log(birthYear);
-
Operator precedence
- codingheros.io/resources
- Operator precedence table
- codingheros.io/resources
-
More
var ageJohn = 30; var ageMark = 30; ageJohn = (3 + 5) * 4 - 6; console.log(ageJohn); ageJohn = ageMark = (3 + 5) * 4 - 6; console.log(ageJohn); console.log(ageMark); ageJohn++; // adds 1 to ageJohn
-
Code
// Lecture: if/else statements var name = 'John'; var age = 26; var isMarried = 'no'; if (isMarried === 'yes') { console.log(name + ' is married!'); } else { console.log(name + ' will hopefully marry soon'); } isMarried = false; if(isMarried) { console.log('YES!'); } else { console.log('NO!'); } if(23 == '23') { console.log('Something to print...'); }
-
=== vs ==
- no type conversion is done for ===. Even the types of lhs and rhs have to match
- 1 === '1' is false
- 1 == '1' is true, does type coersion
- no type conversion is done for ===. Even the types of lhs and rhs have to match
-
code
// Lecture: boolean logic and switch var age = 16; if (age < 20) { console.log('John is a teenager'); } else { console.log('John is a man'); }
-
Boolean logic
-
AND (&&) -> true if all are true
-
OR (||) -> true if one is true
-
NOT (!) -> inverts true/false value
-
Examples:
var age = 16; age >= 20; // false age < 30; // true !(age < 30); // false age >= 20 && age < 30; // false age >= 20 || age < 30; // true
-
Example:
var age = 25; if (age < 20) { console.log('John is a teenager.'); } else if (age >= 20 && age < 30) { console.log('John is a young man.'); } else { console.log('John is a man.'); }
-
-
Switch statement
var job = 'teacher'; job = prompt('What does John do?'); switch (job) { case 'teacher': console.log('John teacher kids.'); break; case 'driver': console.log('John drives a cab in Lisbon.'); case 'cop': console.log('John helps fight crime.'); break; default: console.log('John does something else.'); }
-
Challenge:
John and a friend invented a simple game where the player with the highest value of his height (in centimeters) plus five times his age wins (what a silly game :) 1. Create variables for the heights and ages of two friends and assign them some values 2. Calculate their scores 3. Decide who wins and print the winner to the console. Include the score in the string that you output to the console. Don't forget that there can be a draw (both players with the same score). 4. EXTRA: Add a third player and now decide who wins. Hint: you will need the && operator to take the decision. If you can't solve this one, just watch the solution, it's no problem
-
code
var heightJohn = 172; var heightMike = 165; var ageJohn = 26; var ageMike = 29; var scoreJohn = heightJohn + 5 * ageJohn; var scoreMike = heightMike + 5 * ageMike; if (scoreJohn > scoreMike) { console.log('John wins the game with ' + scoreJohn + ' points!'); } else if (scoreJohn < scoreMike) { console.log('Mike wins the game with ' + scoreMike + ' points!'); } else { console.log('There is a draw.'); } var heightMary = 158; var ageMary = 31; var scoreMary = heightMary + 5 * ageMary; if (scoreJohn > scoreMike && scoreJohn > scoreMary) { console.log('John wins the game with ' + scoreJohn + ' points!'); } else if (scoreMike > scoreJohn && scoreMike > scoreMary) { console.log('Mike wins the game with ' + scoreMike + ' points!'); } else if (scoreMary > scoreJohn && scoreMary > scoreMike) { console.log('Mary wins the game with ' + scoreMary + ' points!'); } else { console.log('It\'s is a draw.'); }
-
Console:
-
scoreJohn
-
scoreMike
- up arrow shows all commands
-
-
What are functions?
- A peice of code that can be run many times
- They can take arguments and may return a result
- It is like a machine that takes something and return something
- To satisfy the principle "don't repeat yourself"
-
Code
function calculateAge(yearOfBirth) { var age = 2017 - yearOfBirth; return age; } var ageJohn = calculateAge(1990); var ageMike = calculateAge(1969); var ageMary = calculateAge(1948); console.log(ageJohn); console.log(ageMike); console.log(ageMary); function yearsUntilRetirement(name, year) { var age = calculateAge(year); var retirement = 65 - age; if (retirement >= 0) { console.log(name + ' retires in ' + retirement + ' years.'); } else { console.log(name + ' has already retired.'); } } yearsUntilRetirement('John', 1990); yearsUntilRetirement('Mike', 1969); yearsUntilRetirement('Mary', 1948);
-
Code
// Lecture: Statements and expressions
-
Function statement:
function someFun(par) { // code }
-
Example
if (x === 5) { // do something }
-
Nothing is produce value
-
-
Function expression:
var someFun = function (par) { // code }
-
Produces an outcome
-
Examples:
var x = 3; 3 + 4;
-
-
Code
// Lecture: Arrays var names = ['John', 'Jane', 'Mark']; var years = new Array(1990, 1969, 1948); **(M)** console.log(names); console.log(names[0]); // John names[1] = 'Ben'; console.log(names); // ['John', 'Ben', 'Mark']
-
Mixing types in arrays
var john = ['John', 'Smith', 1990, 'teacher', false]; john.push('blue'); **(M)** console.log(john); john.unshift('Mr.'); **(M)** console.log(john); john.pop(); console.log(john); john.shift(); console.log(john); alert(john.indexOf('Smith')); **(M)** if (john.indexOf('designer') === -1) { console.log('John is NOT a teacher.'); }
-
Code
// Lecture: Objects var john = { name: 'John', lastName: 'Smith', yearOfBirth: 1990, job: 'teacher', isMarried: false } console.log(john);
-
Two ways to retrieve
-
Dot notation
console.log(john.lastName);
-
Square brackets
console.log(john['lastName']);
-
-
Using variable as key
var xyz = 'job'; console.log(john[xyz]);
-
Data mutation
john.lastName = 'Miller'; john['job'] = 'programmer'; console.log(john);
-
Another way of creation
var jane = new Object(); **(M)** jane.name = 'Jane'; jane.lastName = 'Smith'; jane['yearOfBirth'] = 1969; jane['job'] = 'retired'; jane['isMarried'] = true; console.log(jane);
-
Code
// Lecture: Objects and Methods var john = { name: 'John', lastName: 'Smith', yearOfBirth: 1990, job: 'teacher', isMarried: false };
-
Objects can have other objects, arrays or functions
var john = { ... family: ['Jane', 'Mark', 'Bob'], calculateAge: function () { return 2017 - this.yearOfBirth; } } console.log(john.family[2]); console.log(john.calculateAge()); var age = john.calculateAge(); john.age = age; console.log(john);
-
Write age in object
var john = { name: 'John', lastName: 'Smith', yearOfBirth: 1990, job: 'teacher', isMarried: false, family: ['Jane', 'Mark', 'Bob'], calculateAge: function () { this.age = 2016 - this.yearOfBirth; } }; john.calculateAge(); console.log(john); var mike = { yearOfBirth: 1950, calculateAge: function () { this.age = 2016 - this.yearOfBirth; } }; mike.calculateAge(); console.log(mike);
-
For loop
// Lecture: Loops for (var i = 0; i < 10; i++) { console.log(i); }
-
Looping through an array
var names = ['John', 'Jane', 'Mary', 'Mark', 'Bob']; for (var i = 0; i < names.length; i++) { console.log(names[i]); } for (var i = names.length - 1; i >= 0; i--) { console.log(names[i]); }
-
While loop
var i = 0; while (i < names.length) { console.log(names[i]); i++; }
-
Break, Continue
for (var i = 1; i <= 5; i++) { console.log(i); if (i === 3) { break; } } for (var i = 1; i <= 5; i++) { if (i === 3) { continue; } console.log(i); }
-
Problem
1. Creation of an array with some years where persons were born 2. Creation of empty array (just []) 3. Use a loop to fill the array with the ages of the persons 4. Use another loop to log into the console whether each person is of full age (18 or older), as well as their age 5. Finally, creation of a function called printFullAge which receives the vector of years as an argument, executes the steps 2., 3. and 4. and returns a vector of ture/false boolean values: ture if the person is of full age (>= 18 years) and false if not (< 18 years) 6. Call the function with two different vectors and store the results in two variables: full_1 and full_2 7. Example input: [1965, 2008, 1992] 8. Example Output: [true, false, true] 9. Hint: you can use a loop not only to read from an array, like y[i], but also to set values in an array, like y[i] = ... You can also use the specific array methods.
- 1196: Changed LiveScript to JavaScript to atract Java developers but nothing to do with Java
- 1997? ECMAScript 1 the language standard, JavaScript: the language in practice
- 2009: ECMAScript 5 was released with lots of features
- 2015: ECMAScript 2015 was released. biggest update (ES2015)
- 2016: ES 2016
- ES5 is fully supported by modern browsers, ES6 partial support in modern browsers, ES2016: poor support in modern browsers
- ES5 Preferred:
- ES2015 very incomplete browser support today
- Almost all tutorials on web in ES5
- When working on old codebases, these will be written in ES5
- It is easier to learn ES5 and upgrade to ES6
- How JavaScript works behind the scenes
- Environment: Browser usually
- Node.JS web server
- Host has a Javascript engine (program that executes Javascript code)
- Google V8 engine
- Spider monkey
- ...
- Parser:
- Parses checks syntax
- Throws error if there is error
- Praser then constructs an Abstract Syntax Tree
- Abstract Syntax Tree is translated to machine code (executed by processor)
- Code Runs on Machine
- Parses checks syntax
- Execution context:
- A box, a container, or a wrapper which stores variables and in which a peice of our code is evaluated and executed
- Default execution context: Global context
- Code that is not inside any functions
- Associated with global object (window object in a browser)
lastName === window.lastName // true
- Code inside functions
-
Each function gets its own execution context
var name = 'John'; function first() { var a = 'Hello!'; second(); var x = a + name; } function second() { var b = 'Hi!'; third(); var z = b + name; } function third() { var c = 'Hey!'; var z = c + name; } first();
-
name
,first()
,second()
andthird()
definitions are in global execution context -
first();
call will give rise to new Execution Context on top of Global Execution Context -
Execution Stack is formed and the new execution context becomes the active context in which the code is executed
a
is stored in execution context
-
second();
call will give rise to a new execution context and the new execution context becomes the active contextb
is stored in the new execution context
-
third();
will give rise to a new execution context which will become the active contextc
is stored in the new execution contextz
is stored in the new execution context
-
When
third()
returns, the execution context is removed and the next execution context becomes active -
z
is stored in the active context -
When
second()
returns, the execution context is popped out of execution stack and the next execution context becomes active -
x
is stored in the active execution context -
When
first()
returns, the execution context is popped out of the stack and the global execution context becomes active
-
- Execution context object
- Three properties
- Variable Object (VO): function arguments, inner variable declarations and function declarations
- Scope chain: contains current variable objects and variable objects of its parents
- "This" variable
- Three properties
- How is it created?
- When a function is called, a new execution context is put on stop of execution stack
- Two phases:
- Creation phase
-
Creation of VO
- Argument object is created, containing all arguments passed into function
- Code is scanned for function declarations: for each function, a property is created in Variable Object, pointing to the function (Hoisting)
- Code is scanned for variable declarations: for each variable, a property is created in VO, and set to
undefined
(Hoisting)
-
Creation of scope chain
-
this is determined and set
-
- Execution Phase
- Code of function that generated the current execution context is run line by line
- Creation phase
- Two phases:
- When a function is called, a new execution context is put on stop of execution stack
-
Code
calculateAge(1965); function calculateAge(year) { console.log(2017 - year); } // Hoisting: function definition is stored in Variable Object (VO) even before execution
-
Function expressions
retirement(1965); // errors out var retirement = function (year) { console.log() } // Hoisting only works for function declarations but not for function expressions
-
Variable hoisting
console.log(age); // age is undefined due to hoisting var age = 23; // stored in global execution context object console.log(age); console.log(bla); // bla is not declared at all so errors out function foo() { console.log(age); // ag is undefined var age = 65; // stored in VO of foo's execution object console.log(age); // } foo(); console.log(age);
-
Scoping: Where can we access a variable or a function in Javascript
- Each new function gives rise to a new scope (space or environment in which variables it defines are accessible)
-
For new scope, we need new function
-
Lexical scoping: lexical - position of something
-
function that is lexically within another function gets access to the scope of outer function
- Inner function gets access to variables of outer functions
-
Example:
var a = 'Hello!'; function first() { var b = 'Hi!'; second(); function second() { var c = 'Hey!'; console.log(a + b + c); } }
first()
has access to VO_Global + VO_l
-
Scope chain: (direction of resolution)
- local scope -> parent scope -> parent scope -> ... -> Global scope
-
During creation, each execution object gets same scope chain (?)
-
-
Example:
var a = 'Hello!'; first(); function first() { var b = 'Hi!'; second(); function second() { var c = 'Hey!'; third(); // possible because of scope chain } } function third() { var d = 'John'; console.log(a + b + c + d); // error since b, c are not in scope chain }
- Determining and setting 'this' variable:
- Each execution context gets a 'this' variable
- Regular function call: 'this' points to global object (window object)
- Method call:
this
points to object calling the method this
is assigned value when function where it is defined is called.
-
Example:
console.log(this); // Window object calculateAge(1985); function calculateAge(year) { console.log(2017 - year); console.log(this); // Window object } var john = { name: 'John', yearOfBirth: 1990, calculateAge: function () { console.log(this); // john object which called the method console.log(2017 - this.yearOfBirth); function innerFunction() { console.log(this); // Window object (?) - it is a regular function } innerFunction(); } }; john.calculateAge();
-
Example:
var mike = { name: 'Mike', yearOfBirth: 1984 }; mike.calculateAge = john.calculateAge; // method borrowing mike.calculateAge(); // mike object - since mike is calling the method and this is assigned a value only when the method is called
- Download the code:
- DOM: Document Object Model - structured representation of an HTML document.
- Used to connect webpages to scripts like JavaScript
- It is object oriented representation
- For each element in html there is a corresponding object
- JavaScript can manipulate the DOM
- Open the project
-
What we will learn?
- Creation of fundamental game variables
- How to generate a random number
- How to manipulate DOM
- How to read from DOM
- How to change CSS styles
-
JS
var scores, roundScores, activePlayer, dice; scores = [0, 0]; roundScore = 0; activePlayer = 0; // used to read scores array dice = Math.floor(Math.random() * 6) + 1; // document.querySelector('#current-' + activePlayer).textContent = dice; document.querySelector("#current-" + activePlayer).innerHTML = '<em>' + dice + '</em>'; var x = docuement.querySelector('#score-' + activePlayer).textContent; console.log(x); document.querySelector('.dice').style.display = 'none';
-
Events: notifications sent to notify the code that something happened on webpage
- Clicking a button, resizing a window, scrolling down or pressing key
-
Event listener: function that performs action based on certain event. It waits for specific events to happen
-
How is event processed?
- Event is processed as soon as the execution stack is empty
- Message Queue: Events are put in the queue and wait to be processed
- When an event needs to be processed, an execution context is put on top of the Execution stack for the event handler
-
What you will learn in the lecture?
-
Code
document.getElementById('score-0').textContent = '0'; document.getElementById('score-1').textContent = '0'; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.querySelector('.btn-roll').addEventListener('click', function () { // 1. Random number dice = Math.floor(Math.random() + 6) + 1; //2. Display the result var diceDOM = document.querySelector('.dice'); diceDOM.style.display = 'block'; diceDOM.src = 'dice-' + dice + '.png'; //3. Update the round score IF the rolled number was NOT a 1 });
-
What we will learn?
- What the ternary operator is
- How to add, remove and toggle HTML classes.
-
Code
//3. Update the round score IF the rolled number was NOT a 1 if (dice !== 1) { // Add score roundScore += dice; document.querySelector('#current-' + activePlayer).textContent = roundScore; } else { // Next player activePlayer === 0? activePlayer = 1: activePlayer = 0; roundScore = 0; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; // document.querySelector('.player-0-panel').classList.remove('active'); // document.querySelector('.player-1-panel').classList.add('active'); document.querySelector('.player-0-panel').classList.toggle('active'); document.querySelector('.player-1-panel').classList.toggle('active'); document.querySelector('.dice').style.display = 'none'; }
-
What you will learn?
- How to use functions to correctly apply DRY principle
- How to think about the game logic like a programmer
-
Code
document.querySelector('.btn-hold').addEventListener('click', function () { // Check if player won the game if (scores[activePlayer] >= 100) { document.querySelector('#name-' + activePlayer).textContent = 'Winner!'; document.querySelector('.dice').style.display = 'none'; document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner'); document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active'); } else { ... // Next Player nextPlayer(); } } document.querySelector('.btn-hold').addEventListener('click', function () { // Add CURRENT score to GLOBAL score scores[activePlayer] += roundScore; // Update the UI document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer]; // Check if player won the game nextPlayer(); }); function nextPlayer() { // Next player activePlayer === 0? activePlayer = 1: activePlayer = 0; roundScore = 0; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; // document.querySelector('.player-0-panel').classList.remove('active'); // document.querySelector('.player-1-panel').classList.add('active'); document.querySelector('.player-0-panel').classList.toggle('active'); document.querySelector('.player-1-panel').classList.toggle('active'); document.querySelector('.dice').style.display = 'none'; }
-
Code
document.querySelector('.btn-new').addEventListener('click', init); function init() { scores = [0, 0]; activePlayer = 0; roundScore = 0; document.querySelector('.dice').style.display = 'none'; document.getElementById('score-0').textContent = '0'; document.getElementById('score-1').textContent = '0'; document.getElementById('current-0').textContent = '0'; document.getElementById('current-1').textContent = '0'; document.getElementById('name-0').textContent = 'Player 1'; document.getElementById('name-1').textContent = 'Player 2'; document.querySelector('.player-0-panel').classList.remove('winner'); document.querySelector('.player-1-panel').classList.remove('winner'); document.querySelector('.player-0-panel').classList.remove('active'); document.querySelector('.player-1-panel').classList.remove('active'); document.querySelector('.player-0-panel').classList.add('active'); }
-
What you will learn?
- What a state variable is, how to use it and why
-
State variable: tells the condition of a system
-
Code
var ..., gamePlaying; document.querySelector('.btn-hold').addEventListener('click', function () { if (gamePlaying) { ... if (scores[activePlayer] >= 100) { ... gamePlaying = false; } } }); document.querySelector('.btn-roll').addEventListener('click', function () { if (gamePlaying) { ... } }); function init() { ... gamePlaying = true; ... }