JavaScript Syntax: Data Types, Variables, Expressions
Download
Report
Transcript JavaScript Syntax: Data Types, Variables, Expressions
JavaScript for .Net Developers
The things you need to know
Pavel Kolev
www.pavelkolev.com
Table of Contents
1. History of the Web
2. The Good, The Bad and the Evil
3. The Future
2
History of the Web
HTML
Just a document viewer, not a platform
It’s not a page – it’s a scroll
The good and the bad
Custom
tags
Make the evolution possible
Accept bad html
Not
No
so many tags – lets have ids and classes
control over the presentation
4
HTML
Runoff
GML
SGML
HTML
XML
Scribe(< >)
LATEX
TEX
GML:
:h1.Gosho
:ol
:li.Pesho
:li.Ivan
:eol.
…
::ol.
…
</ol>
SGML – IBM government, CERN
HTML – Simplified SGML
5
CSS
CSS isn’t bad. You just don’t understand it like I do.
Designed for paper printing.
The good and the bad
Not implementable – every specification fails
Complicated selector management (imagine no tools and !important)
Not intended for dynamic content
No modularity – different modules on the page with different style
Naming
6
CSS vs JavaScript
CSS
JavaScript(DOM)
background-color
font-size
list-style-type
z-index
float
backgroundColor
fontSize
listStyleType
zIndex
cssFloat / styleFloat
7
The DOM
Document Object Model
At first not all elements are scriptable (MS makes them all)
The good and the bad
document.write
Useless #textnode for whitespace
document.documentElement – return html
Hell a lot of a pointers
The DOM - nodes
Pointers
Child (firstChild,
lastChild)
Siblinds (nextSibling, previousSibling)
Parent (parentNode)
Children (childNodes)
You just need firstChild and nextSibling
node.property vs node.getAttribute (W3C fault – JAVA style)
node.className should be node.classNames
9
The DOM – nodes operations
document.createElement – does not add it to the DOM
node.appendChild(newNode)
node.replaceChild(new, old) is actually
old.parentNode.replaceChild(new, old)
node.removeChild(old) is actually
old.parentNode.removeChild(old) – in IE you should remove all
event handlers because of memory leaks
All browsers implemented MS’s innerHTML which acts like a
parser (W3C does not provide access to HTML parser)
10
But meanwhile
JavaScript happened
JavaScript – the beginning
The Mosaic browser introducing the <img />
The Netscape startup getting Brendan Eich on board
JavaScript
Java
(syntax)
Scheme
(functions model)
LiveScript
Self
(prototypes)
JavaSceript – the early years
The language of the web should have been JAVA
In Netscape 2.0 we got LS both on server and client
Netscape & Sun vs Microsoft
We kill LavaScript
JScript
Making the standart – W3C, ISO, ECMA
Can’t use the name so call it ECMAScript
Microsoft declares victory and leave the field
13
JavaScript and Microsoft
Netscape with bad business model
Microsoft moves to the X – Internet and .NET
JS should have died with Netscape as all languages do
Microsoft – the good guy
JScript
Generelized document model – made the DOM good enough
XMLHttpRequest(AJAX)
– the second surprise to MS and the
reason the web survived
The AJAX revolution succeeded because of the goodness of JS
14
The Good, The Bad and the Evil
JavaScript in short
The need of interactivity in the browsers – HyperCards (Apple)
Brilliant ideas but not enough time to fix all the bugs during the
browser wars
The greatest discovery of 21st century – JS has good parts
The bad parts reasons
Legacy – coping some of the JAVA problems
Make it easy for newbies – “;”, global object – great or not
Too little time to design, develop and ship
The bad parts can be avoided and it’s a brilliant language
16
JavaScript – all about Objects
Its all about objects
Objects in JS are not instances of a Class
Object – dynamic collection of properties
Each property has a key string that is unique within that object
get, set, delete
Think of them as hash tables
17
JavaScript Types
JavaScript is NOT a typeless language
JavaScript is a loosely typed language – you don’t declare the
data types of the variables explicitly
Types – Number, Boolean, String, Array, Function, Date, RegExp
Use var for declaration
18
var statement
Declares AND initializes variable within function
You do not specify type
JavaScript does not respect block scope
Declaration is split in 2 parts:
the declaration part is hoisted at the top of the function and
initialized with undefined
the initialization
part turns into ordinary assign statement
var a = “gosho”;
19
Number
Only one type for Number – no Integer, BigInteger, Float, Double
etc… which makes the language easier for beginners
Using 64 – bit floating point
Using “Double” (IEEE-754) to represent numbers
Associative Law does not hold
(a + b) + c === a + (b + c)
Inherits from Number.prorotype
20
Math object
Inherited from JAVA. Should be in Number
abs
acos
asin
atan
atan2
ceil
cos
exp
floor
log
max
min
pow
random
round
sin
sqrt
tan
E
LN10
LN2
LOG10E
LOG2E
PI
SQRT1_2
SQRT2
21
NaN
Special Number – Not a Number
NaN – a number which is not any real number
With bad math you get NaN instead of error
NaN === NaN // false
NaN !== NaN // true
22
Boolean
Got it right
Exactly 2 Boolean values in the language:
true
false
23
String
Why we call them strings? They don’t look like strings?
No separate character type
A sequence of 0 or more 16 bit Unicode characters
Similar strings are equal (===)
Strings are immutable
You can use both ‘’ and “” for strings
Multiline strings
var myString = “This is a sample multiline \
string that will cause error”;
24
Strings
Numbers to Strings
var myString = num.toString();
var mySecondString = String(num);
Strings to number
var
var
var
var
var
myNum = Number(str);
mySecondNum = +str;
myThirdNum = parseInt(“123mm”) // result in 123
myForthNum = parseInt(“08”) // result in 0
myFifthNum = parseInt(“08”, 10) // result in 8
25
String methods
charAt
charCodeAt
compareLocale
concat
indexOf
lastIndexOf
localeCompare
match
replace
search
slice
split
substring
toLocaleLowerCase
toLocaleUpperCase
toLowerCase
toString
toUpperCase
trim
length
26
Trim
if(typeOf String.prototype.trim !== ‘function’) {
String.prorotype.trim = function() {
return this.replace(placeRegExHere);
}
}
27
Array
There are no Arrays in JavaScript
JavaScript use objects to simulate array
Indexes are converted to strings and used as keys to retrieving values
You don’t have the speed advantage
No need to provide initial length of the array – they don’t actually
have a length
We have length property
Don’t use for in with arrays – order of iteration is not guaranteed
28
Array literals
Array litteral uses []
Can contain anything because it is object
Will fill the empty with udnefined
var arr = [1, “pesho”, function() { … }];
arr.length === 3; // true
arr[arr.length] = true;
29
Array methods
concat
every
filter
forEach
indexOf
join
lastIndexOf
map
pop
push
reduce
reduceRight
reverce
shift
slice
some
splice
toLocaleString
toString
unshift
30
Array methods
Sorting
arr.sort(function(a, b) {
// my sorting function
});
forEach
arr.forEach(function(item, index, array) {
// do what you want
});
Removing items from the array
delete delete arr[5]; // will leave undefined
splice
arr.splice(index, 1); // will reorder array
31
Other (before the major)
Date – based on JAVA’s Date
RegExp
All values are objects except for 2
null – value that isn’t anything
undefined – lack of value
default for variables and parameters
value for missing members of objects
probably not the best name “undefined”
32
Other (before the major)
typeof – returns a string representing the type of a value
typeof null === ‘object’ // true
typeof array === ‘object’ // true but we have Array.isArray
falsy values – if you put it in if statement you get to else branch
false // “false” is true
null
undefined
0 // “0” is true
“”
NaN
33
Others
JSON.parse – parse json object
JSON.stringify – make json object “to string”
Object.keys – returns array of all enumerable properties of obj
Object.create(obj, newMembers) – you can now inherit from
null
Array.isArray – check if passed obj is array
Use ‘strict mode’ on top of function (nice survey in MS for IE9)
34
Objects
Object based vs Class based
Key – Value
Two kind of properties
data properties – value, writeable
accessor properties – get, set (available with ES5)
No initialization
var obj = { name: “Pesho” };
obj.class = 10;
35
Objects
var obj =
Object.defineProperties(Object.create(Object.prototype),
{
age: {
value: 20,
writeable: true,
enumerable: true,
configurable: true,
get: function() {…},
set: function() {…}
}
})
Object.seal(obj); // prevents new prop & all are non-config
Object.freeze(obj); // makes it immutable
Object.getOwnPropertyNames(obj); // event not enumerables
36
Operators
Coming from C it has all the same operators
Arithmetic
+ - * / %
Comparison
== != > < >= <=
Logical
&& || !
Bitwise
& | ^ >> >>> <<
Ternary
?:
37
+
Used for both addition and concatenation
If both operands are numbers – add them else – convert them
to strings and concatenate them
Bad part that works in JAVA but not here
HTML does not know about numbers
“$” + 1 + 2 = “$12”
38
Statements
If
switch – the value does not need to be number
while
with(obj) {
do
a = b;
}
for
break
obj.a = b;
continue
obj.a = obj.b;
a = b;
return
a = obj.b;
try/throw
with – evil do not use it, please, please
eval – evil do not use it, please, please
39
Functions
JavaScript is functional language – first class functions
functions can be passed as arguments to a function
functions can be returned from functions
The beaty and one of the best parts
One of the key idea and they make JavaScript so powerfull
Functions in JavaScript does it all – Method, Class, Constructor,
Module
function name () { … return null; }
Produce instance of function object
40
Functions statement vs expression
Function expression
var myFunc = function myFuncName() { … }
Function statement / declaration
function myFunc() { … };
Because of function hoisting function statement can be called
before declaration
41
Scope
JavaScript does not respect {} scope
Only functions have scope
Variables declared inside a function are not visible outside of it
42
Invocation and return
Invocation
Suffix () operator containing 0 or more parameters separated by
comma
Will ignore extra arguments and will fill the missing with
undefined
no type checking
Return
You can return any type you want
By default always returns undefined;
43
How to call a function
Function form
myFunction(arguments); // ES3 -> global object, ES5 - undefined
Method form – when it is part of an object
obj.myFunction(arguments); // this will be obj
obj[“myFunction”](arguments);
Constructor form
new MyFunction(arguments); // new object is created and assigned to
this and if there is no return, this will be returned
Apply / Call form
myFunc.apply(obj, [arguments]); // this will be obj
44
Closure
Great idea! Of course not accepted.
Closure – the context of the inner function includes the scope of
the outer function. The inner function has access to that context
even when the parent has returned
var myFunc = (function () {
var months = [“Jan”, “Feb” … ];
return function(n) {
return months[n-1];
}
}());
myFunc(2);
45
arguments
Pseudo paramenter that all functions get
Contains all arguments from the invocation
Array-like object but not array
arguments.length – number of passed arguments
Use it as read-only
46
this
Pseudo paramenter that all functions have
Reference to the object of invokation
Allows a method to know what object it is connected with
Key to prototypal inheritance
47
Reference
Objects can be passed to functions and returned
objects are passed by reference not by value
objects are almost never copied which is great
The equality operator === compares references not values
48
Pseudoclassical inheritance
function Human (name) {
this.name = name;
}
Human.prototype.myFunc = function () { … };
function Student(name) {
this.name = name;
}
Student.prototype = new Human();
Student.prototype.otherFunc = function() { … };
49
Functional inheritance
function human (name) {
return {
name: name,
myFunc: function () { … }
}
}
function student(name) {
var that = human(name);
that.otherFunc = function() { … };
return that;
}
50
Event loop
JavaScript unlike many other languages does not have Read
which makes it possible to have Event loop
Free of races and deadlocks
One stack only
Low overhead
If a turn fails, the program continues
51
Tips
Declare all variables on top of function
Don’t create functions in loops – new function object will be created
with each iteration
!!variable – converts variable to boolean
return a && a.member / return a || a.member
You can have private members with closure
++ is Assembly language feature – don’t use it
Don’t use the global object
Use JSLint
52
AJAX
2000-2005?
The future
12.01.2016
I believe this presentation is not
going to end on time but if you
have any questions… otherwhise
contact me
[email protected]
http://pavelkolev.com