Professional Documents
Culture Documents
next
ES6
CSC 3916
JavaScript
History
3
JavaScript is a Client-side, Simple and Power to
front-end mobile and flexible manipulate the
scripting desktop DOM
language technology
developed by
Netscape for
dynamic content
1997
ECMAScript 1
1998 2009
ECMAScript 2 ECMAScript 5
2005 - 2007
1999 2014
ECMAScript 3 ECMAScript 4 - Abandoned ECMAScript 6?
2014
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
1997 2015
Terminology
2. Establish timer
<script>
$(function() {
var local = 1;
window.SetInterval(function() {
alert(local);
local++; 3. Local variable
} incremented
});
</script>
CSS- definition
1. Cascading Style Sheets is a style sheet language used to describe the
presentation semantics of a document written in a markup language
AJAX- definition
1. Asynchronous JavaScript and Xml is a group of interrelated web
development techniques used on the client-side to create interactive
web applications.
i. Html/XHtml and CSS for presentation
ii. DOM for dynamic display of and interaction with data
iii. Xml and Xslt for the interchange, and manipulation and display,
of data, respectively
iv. XmlHttpRequest object for asynchronous communication
v. JavaScript to bring them all together
JavaScript
Fundamentals
Same as Java/C++/C-
style langs
for-loops:
for (let i = 0; i < 5; i++) { … }
while-loops:
while (notFinished) { … }
comments:
// comment or /* comment */
conditionals (if statements):
if (...) {
...
} else {
...
}
If Statements
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
While Loops
while (condition) {
statements;
}
do {
statements;
} while (condition);
Comments
function name() {
statement;
statement;
...
}
script.js
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
hello();
hello();
Console output
script.js
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
hello();
hello();
hello();
hello();
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
hello();
hello();
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
A: Yes, for this particular syntax.
This works because function
declarations are "hoisted" (mdn).
You can think of it as if the
definition gets moved to the top of
the scope in which it's defined Console output
(though that's not what actually happens).
script.js
hello();
hello();
function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
Caveats:
- There are other ways to define
functions that do not get hoisted;
we'll visit this once we graduate
from JS
- Try not to rely on hoisting when
coding. It gets bad.
Console output
Variables: var, let, const
Declare a variable in JS with one of three keywords:
You do not declare the datatype of the variable before using it ("
dynamically typed")
Function parameters
function printMessage(message, times) {
for (var i = 0; i < times; i++) {
console.log(message);
}
}
But you can't refer to a variable outside of the function in which it's
declared.
Understanding let
function printMessage(message, times) {
for (let i = 0; i < times; i++) {
console.log(message);
}
console.log('Value of i is ' + i);
}
printMessage('hello', 3);
let can be reassigned, which is the difference between const and let
Variables best practices
Use const whenever possible.
If you need a variable to be reassignable, use let.
(This is also what the Google and AirBnB JavaScript Style Guides recommend.)
Variables best practices
Use const whenever possible.
If you need a variable to be reassignable, use let.
There are also Object types, including Array, Date, String (the object
wrapper for the primitive type), etc.
Numbers
const homework = 0.45;
const midterm = 0.2;
const final = 0.35;
const score =
homework * 87 + midterm * 90 + final * 95;
console.log(score); // 90.4
Numbers
const homework = 0.45;
const midterm = 0.2;
const final = 0.35;
const score =
homework * 87 + midterm * 90 + final * 95;
console.log(score); // 90.4
if (username) {
// username is defined
}
Boolean
Equality
NaN === NaN // still weirdly false
[''] === '' // false
false === undefined // false
false === null // false
null === undefined // false
0-based indexing
Mutable
Can check size via length property (not function)
Arrays
<script type="text/javascript">
var a = 10;
var b = 11;
var c;
c = a + b;
alert(‘The answer is’ + c);
</script>
JavaScript Variables
Property myObject.make;
Reference myObject['make'];
Op var p = 'make';
myObject[p];
Using an object literal is the preferred
method, over the multiple assignment
means of building an object.
var ride = {
Window
var foo = bar;
Properties? window.foo = bar;
foo = bar;
Assigned to Variables
as callbacks
In this case the timer function “calls back” to
function in our own code
setTimeout(doSomething, 5000);
In JavaScript the object referenced by this
(function context) is determined not by how
the function is declared but by how it is
invoked.
var ride = {
make: ‘Chevy',
Of An iteratable object
function* generator(maxValue){
for(let i = 0; i < maxValue; i+=1){
yield i;
}
}
let iter = generator(10);
for(let val of iter()){
console.log(val);
}
For-of loop
LIVE DEMO
Templated String
Templated Strings in ES6
LIVE DEMO
Arrow Functions
ALSO CALLED LAMBDA EXPRESSIONS
Arrow Functions
Arrow functions
easify the creation
of functions:
Arrow Functions
Arrow functions
easify the creation
of functions:
numbers.sort(function(a, b){
return b – a;
});
Arrow Functions
Arrow functions
easify the creation
of functions:
numbers.sort(function(a, b){
return b – a;
});
Becomes
numbers.sort((a, b) => b –
a);
Arrow Functions
Arrow functions numbers.sort(function(a, b){
easify the creation return b – a;
of functions: });
Becomes
numbers.sort((a, b) => b –
a);
var fullnames =
people.filter(function (person) {
return person.age >= 18;
}).map(function (person) {
return person.fullname;
});
Arrow Functions
Arrow functions numbers.sort(function(a, b){
easify the creation return b – a;
of functions: });
Becomes
numbers.sort((a, b) => b –
a);
var fullnames =
people.filter(function (person) {
return person.age >= 18;
}).map(function (person) {
return person.fullname; Becomes
});
var fullnames2 =
people.filter(p => p.age >= 18)
.map(p => p.fullname);
Arrow Functions
LIVE DEMO
Object Literals
Object Literals
ES6 adds a new feature (rule) to the way of defining properties:
Instead of
let name = 'Doncho Minkov',
age = 25;
let person = {
name: name,
age: age
};
We can do just:
let name = 'Doncho Minkov';
let person = {
name,
age
};
Object Literals
LIVE DEMO
Destructuring
Assignments
Destructuring Assignments
Destructuring assignments allow to set values to objects in an easier way:
Destructuring assignments with arrays:
Result of method:
function get(){ return [1, 2, 3]; }
var [x, y] = get();
Destructuring Assignments
Destructuring assignments allow to set values to objects in an easier way:
Destructuring assignments with objects:
var person = {
name: 'Doncho Minkov',
address: {
city: 'Sofia',
street: 'Aleksander Malinov'
}
};
module.exports = { persons.js
Person: Person,
Mammal: Mammal
}
To use the module in another file:
import classes from './persons'
import {Mammal, Person} form '.persons'
ES6 Modules
LIVE DEMO
Simple Node
App
WALK THROUGH
Build an App
What is HTTP?
http in Node.js is an inbuilt module that allows
client-server communication via HTTP protocol.
This module provides an interface to create either
an HTTP client or HTTP server that can
communicate with other HTTP servers or clients.
And to make this communication space efficient,
an http module provides streaming of data using
stream interface. And since stream passes data in
chunks, that means Node.js never buffers the entire
request or response at once in the memory. We will
come to streams soon.
So for our app, we will use this http interface to
create an HTTP server that will listen to a
particular port and give data back to the user.
Require
Let’s look a bit into the Much of the Node.js core APIs are built Let us see an example to get the hang of
named event and emitter objects. around an event-driven architecture. it.
Certain kinds of objects (called
“emitters”) can cause some Function
(“listeners”) to be called by emitting any
“named” events.
Emitter
Example
Emitter (subset)
Our web server object is also like all other emitter objects
implementing event emitter interfaces. It also emits different
kinds of named events.
Some of them are the following:
connect— raised for all the ‘connect’ request by the HTTP
client.
connection — Emitted when a new TCP stream is established.
Provide access to the socket established.
request — Emitted for Each request from the client (We would
listen here).
upgrade — emitted each time a client requests an upgrade of
the protocol (can be HTTP version).
Now since our server needs to listen to the incoming request, we will listen
to the request event of our HTTP server.
Listen In the 3rd line, a listener function is attached to listen to all the request
events on our server object.
The request event provides the listener function with 2 parameters which
are:
request — an instance of http.incomingMessage object and
response — an instance of http.ServerResponse object.
These request and response objects have properties and methods that they
inherit from the http.incomingMessage and http.ServerResponse classes,
respectively.
Parse
The request object that’s passed into the handler also implements
the readable stream interface. This means that our request object is a
stream that can be listened to or piped elsewhere to grab the data
that is flowing into it. We will also grab the data right out of
the request stream by listening to the stream’s data and end events.
Different kinds of data may be passed to our server, but to keep it
simple we will be passing only the string in the body.
To use that data we need to parse it, so we will be using
the data and endevent of the readable stream which is implemented
by our request object as mentioned earlier.
On each data event, the readable stream passes data as a buffer
chunk.We will be appending all the chunks in an empty array. And
at the end event we will concat and stringify the array to get the
cumulative body.
Sending a Response
Although if you do not set the response code explicitly, then Node.js
itself sets it to 200. But as complexity increases you will want to set
the desired statusCode of the HTTP response.
Headers
Write a
Response
Errors
Complete