SlideShare a Scribd company logo
[solutions]
JavaScript: Core
Part
Wei-Shao Tang
April 15, 2015
Who am I?
Why JavaScript?
Language
ECMAScript
Core Part
Primitive Type and Variables
String
Control Structure
Function
Array
Object
Who am I?
About Myself
Master in IM, NTU (2014 - )
BS in MIS, NCCU (2010 - 2014)
I'm interested in Web Programming, Functional Programming
I write codes in: Python, JavaScript,
For now, I am learning: Haskell, LISP
My mail is: pa4373 <at> gmail.com
Along with my: Skype, LINE ID: pa4373,
https://github.com/pa4373
Why JavaScript?
"JavaScript is eating the world."
JavaScript is dominant in the World Wide Web.
#1 Programming language, according to popularity on GitHub
and StackOverflow. ( )
It runs everywhere. Web client, desktop / mobile app, server,
embedded system and such.
It got more than 40K+ jobs on LinkedIn, closely following Java
jobs.
Many languages now can compiled to JavaScript. (web
assembly)
source
Unreal engine 4 run on Firefox
Leap Motion Node Drone Flight in 2013
Language
Specification vs. Implementation
Specification
What makes a piece of code a program, and what its
behaviour shall be.
Syntax (form)
Semantic (meaning)
Implementation
System for executing computer program. (Compiler,
Interpreter, Runtime and etc.)
Little Analogy
"Google that yourself"
which means finding something with Google Search Engine.
Reese opened Firefox, went to and
searched for something.
Finch opened Chrome, went to and
searched for something.
Reese and Finch did same things, but with different approaches.
(Different implementors)
https://www.google.com/
https://www.google.co.uk/
Back to JavaScript
By syntax rules, the following piece of code is a program:
Semantic: declare a function named id which takes one object
and return exactly the same object.
v a r i d = f u n c t i o n ( o b j ) {
r e t u r n o b j ;
} ;
What about Implementation?
Several existing implementations, referred to JavaScript
engine:
the program executes JavaScript, usually called Process
Virtual Machine.
Popular ones such as , ,
Don't reinvent the wheel:
Lots of functions are pre-built, as libraries.
SpiderMonkey + Gekco Firefox
V8 + WebKit Chrome
V8 + Few networking libraries Node.js
Google's V8 Mozilla's SpiderMonkey
Rhino
→
→
→
Standardization
If we have so many implementations, what guarantees that they
all follow the specification? (Compatibility)
: the process of developing and implementing
technical standards.
Few groups known for standardization: , , .
Standardization
ISO ANSI ECMA
ECMAScript
In 1996, Netscape filed the application to ECMA, and it was
released as ECMAScript 1 in 1997.
For now, the mainstream is ECMAScript 5, released in 2009,
supported by most of modern browsers.
While the browsers don't always stick to the specification, it's
good to take it as the guideline.
Core Part
Core Part
It's beneficial to understand the relationship of components of
the language, due to the rich (and sophisticated) ecosystem of
JavaScript.
Although you need different knowledge for different
environments, the common part stands out as the core part.
This tutorial is dedicated to the core part of the language.
We won't talk about how to interact with browsers or write
server program, yet...
INSTEAD we focus on components allows you to mentally
model your application.
"A language that doesn't affect the way you
think about programming, is not worth
knowing." ~ Alan Peris (1922 – 1990)
"No, I just want to get my job done, it doesn't matter my codes
all look like the same."
To better understand the usage pattern of others' libraries.
To design the program easier for others to understand.
For fun, and make yourself look smart.
Like learning English, you will do better likely if you appreciate
its culture.
REPL (Read–eval–print loop)
The environment reads input from user, evaluates them as
code at the given context, prints the result, and loops back.
Great for learning, debugging and experimental programming.
REPL (Read–eval–print loop)
Most browsers have built-in REPL:
for Firefox and Chrome: Right click on the web page, choose
"Inspect Element" and select "Console" tab on the developer
panel.
Firefox will be used through the following demonstration.
Type 㫠㫔㫚㫔㫠㫘 and then press "Enter", it will output 㫡.
To represent the process of using REPL, we take the following
form from now on:
where '//: ' stands for program output. the input can be
divided in multiple lines.
Make a newline instead of evaluating: "Shift" + "Enter"
(㫞㫞 for single-line comment.)
v a r i d = f u n c t i o n ( o b j ) {
r e t u r n o b j ;
} ;
/ / : u n d e f i n e d
Exercise (~5 mins)
Fire up REPL and type following statements (ends with ;) in
sequence by instructions, try and discuss the outputs of REPL:
Don't copy & paste, muscle memory helps learn a new language.
/ / p r o g r a m 1 .
" I t h o u g h t F e l i c i t y J o n e s w a s m e . " ;
/ / p r o g r a m 2 .
v a r j a n e H a w k i n g S a y = f u n c t i o n ( ) {
r e t u r n " I t h o u g h t F e l i c i t y J o n e s w a s m e . " ;
} ;
/ / p r o g r a m 3 , i t o n l y w o r k s a f t e r p r o g r a m 2 i s e v a l u a t e d .
j a n e H a w k i n g S a y ( ) ;
Some facts about this little exercise
Each statement ends with semicolon (;)
Just like each sentence in English ends with period.
By convention, the naming rule of JavaScript is Camel-Case.
The indentation use two spaces, not tab.
When declaring a function, there's one space between 㫝㫬㫥㫚㫫㫠㫦㫥
keyword and argument list.
Primitive Type
and Variables
REPL as Calculator
We have seen that how to use REPL to do addition:
Multiplication:
Combine them together:
This does the same for subtraction (-), division (/).
1 + 1 ;
/ / : 2
2 * 5 * 1 3 ;
/ / : 1 3 0
( 1 + 1 0 0 0 ) * 1 0 0 0 / 2 ;
/ / : 5 0 0 5 0 0
We can also compare them:
The statement we've seen so far is called expression, which
means it's evaluated by interpreter and the result value is
produced and returned.
Wait, what is 㫝㫘㫣㫪㫜?
2 > 8 ;
/ / : f a l s e
1 0 > = 1 0 ;
/ / : t r u e
Data Type
Data type is very important, since it determines:
The possible values (range)
Operations allowed to be done
In JavaScript, data type can be categorised into:
Primitive Types: the basic unit provided by JavaScript.
Composite Types: can be constructed from primitive values
and composite values.
Special Types: 㫗㫬㫣㫣, 㫚㫥㫛㫜㫝㫠㫥㫜㫛. (will talk about it later.)
and etc.
Primitive Types
Referred to built-in data structures, and they are:
Atomic: can't be broken down into smaller data type.
Immutable: once the value is decided, it can't be changed.
In ES5, primitive types are:
Boolean
Number
String
It's fair to assume that 㫝㫘㫣㫪㫜 seen in the previous slides is type
of Boolean.
Boolean Type
Only contains two values:
It denotes the truth value of one proposition, such as:
㫖㫙㫖㫔㫚㫚㫚㫔㫣㫖
㫠㫟㫔㫛㫔㫡
{true, f alse}
Logical Operations:
Take one or two boolean value, produces a new value by:
Negation (not): 㫕
Conjunction (and): 㫕㫕
Disjunction (or): 㫚㫚
Negation has higher precedence than conjunction and
disjunction.
! t r u e ;
/ / : f a l s e
t r u e & & f a l s e ;
/ / : f a l s e
f a l s e | | t r u e ;
/ / : t r u e
Number Type
Only one number type: the double-precision 64-bit binary
format IEEE 754 value (number between -( ) and
)
Nah, basically you just need to remember it got double type
internally.
There is no specific type for integers.
No need to worry about integer overflow.
Everything not within the range goes: 㫘㫥㫝㫠㫥㫠㫫㫚
− 12
53
− 12
53
2 / 0 ;
/ / : I n f i n i t y
Number Type
Unary operator: 㫜 (signed)
Binary operators: 㫚, 㫜, 㫙, 㫞, 㫔 (mod)
Operations on float-point numbers is tricky:
While normally it didn't affect the usage, sometimes you may
need precise result. Scale to integer and dividing later:
more
0 . 1 + 0 . 2 ;
/ / : 0 . 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4
( 0 . 1 * 1 0 + 0 . 2 * 1 0 ) / 1 0 ;
/ / : 0 . 3
Number Type
㫗㫘㫗: 'not a number' (although it has number type)
Can be made when converting a illegal string to number:
you can test a number with 㫠㫪㫗㫘㫗 function.
If isNaN returns false, the input is or can be parsed to
number type.
p a r s e I n t ( ' o o p s ' , 1 0 ) ;
/ / : N a N
i s N a N ( 1 0 ) ;
/ / : f a l s e
Comparison and Equivalence
You can compare numbers with 㫛, 㫙, 㫛㫚, 㫙㫚.
The result got boolean type.
Equivalence is a little tricky:
Stick to 㫚㫚㫚, 㫕㫚㫚 instead of 㫚㫚, 㫕㫚
2 > = 8 ;
/ / : f a l s e
0 = = f a l s e ;
/ / : t r u e
0 = = = f a l s e ;
/ / : f a l s e
Ternary Operator
An operator in the sense of 㫘㫗㫜㫙㫗㫖㫗㫜㫖㫗㫘㫖.
㫙㫗㫘㫙㫘㫘㫘㫙㫘㫘㫗㫔㫜㫔㫖㫘㫙㫗㫖㫘㫘㫘㫘㫗㫔㫠㫔㫗㫔㫖㫘㫙㫗㫖㫘㫘㫘㫘㫗㫔㫡
If PROPOSITION is 㫫㫩㫬㫜 then return EXPRESSION 1, else
return EXPRESSION 2.
( 2 > 8 ) ? 6 8 9 : 6 3 3 ;
/ / : 6 3 3
Variable
The programs we've seen so far were written in one-line
expression.
We need some way to save the result for later use, at the given
context.
Variable, serving as program's memory, is a popular way to
address the problem.
Variable in the sense of computer architecture, not
mathematically.
Variable
Variable is composed of an identifier and its value. (the value
may not be defined.)
Consider the following program:
v a r x ; / / x i s i d e n t i f i e r .
/ / : u n d e f i n e d
x ; / / f o r n o w , x h a s n o t c o n t a i n e d a n y v a l u e , y e t .
/ / : u n d e f i n e d
x = 3 ;
/ / : 3
x ; / / x c o n t a i n s 3 n o w .
/ / : 3
Declaration
New local variable is declared with keyword 㫭㫘㫩, along with
identifier.
If you skip 㫭㫘㫩 keyword, the variable became global, which is
very evil.
The identifier is case-sensitive.
Don't need to specify the data type.
v a r x ;
Assignment
To assign a value to a variable, put the value / expression on
RHS, the variable on LHS of 㫚.
When the assignment occurs, the value is returned immediately.
If a variable is declared, but has not been assigned, the value of
the variable is 㫬㫥㫛㫜㫝㫠㫥㫜㫛.
x = 3 ;
/ / : 3
v a r x ;
/ / : u n d e f i n e d
x ;
/ / : u n d e f i n e d
Assignment
Assignment can occurs more than one time, with value in
different data type.
v a r x ;
/ / : u n d e f i n e d
x = 0 ;
/ / : 0
x = f a l s e ;
/ / : f a l s e
Shortcut
The following is not necessary to construct program.
Declaration and assignment:
Operator and assignment 㫚㫚:
The same goes with 㫜㫚, 㫙㫚, 㫞㫚, 㫔㫚
v a r x = 0 ;
/ / : u n d e f i n e d / / n o t i c e t h a t t h e v a l u e i s n o t r e t u r n e d i n t h e c a s e .
x
/ / : 0
v a r x = 1 0 ;
/ / : u n d e f i n e d
x + = 1 0 / / t h e s a m e a s x = x + 1 0
/ / : 2 0
㫥㫬㫣㫣
The value null is a JavaScript literal representing null or an
"empty" value, i.e. no object value is present.
n u l l ;
/ / : n u l l
㫥㫬㫣㫣 vs 㫬㫥㫛㫜㫝㫠㫥㫜㫛
null undefined
as the parameters of function
which is not a object.
the variable is declared but not
assigned, yet.
as the top of prototype
chains
some parameters is missing
when the function is applied.
the property of object doesn't
exist.
the function doesn't return
values (void vs undefined)
Falsy values
The values which act like 㫝㫘㫣㫪㫜 in boolean operations.
Falsy values in JavaScript:
㫝㫘㫣㫪㫜
㫟 (zero)
㫖㫖 (empty string)
㫥㫬㫣㫣
㫬㫥㫛㫜㫝㫠㫥㫜㫛
㫗㫘㫗 (a special Number value meaning Not-a-Number!)
u n d e f i n e d | | t r u e ;
/ / : t r u e
Exercises
In REPL, use variables, addition / subtraction / multiplication /
division to perform the following algorithms. Finally, use
comparison to determine the result is correct.
You shall be familiar with variable, arithmetic operations,
comparison, Boolean value
Mobile Number Magic: (It has to be 9 digits, and you might
assume it's 891230567.)
1. Write down the first 5 digits.
2. Multiple 80 with that number.
3. Plus 1 to that number.
4. Multiple 250 with that number.
5. Plus the last 4 digits, twice!
6. Minus 250.
7. Using comparison to check if it's your mobile number.
8. If it's your number, we're done here. If not, divide it by 2.
9. Repeat step 7 again.
Note: This can be seen as:
if a has 5 digits and b has 4 digits, it reflects your mobile
number structure.
2(a × + b) = a × 2 × + 2b10
4
10
4
= (a × 80 + 1) × 250 + 2b − 250
String
String
String is a finite sequence of characters, usually used to
represent text.
To construct a string, put things in double / single quotes (single
is preferable.)
There is no specific type for characters.
' H a a a a a v e y o u m e t T e d ? ' ;
/ / : ' H a a a a a v e y o u m e t T e d ? '
v a r c h a r = ' a ' ;
㫚 and Casting
Consider the program:
Notice that 㫙 as esacpe char before 㫖 in the string.
㫚 stands for concatenation when at least one of operand is
String.
It will attempt to call 㫫㫦㫘㫫㫩㫠㫥㫞 method on non-string
operand.
v a r s l a p C o u n t = 5 ;
/ / : u n d e f i n e d
' I  ' m g o i n g t o g o w i t h ' + s l a p C o u n t + ' s l a p s f o r e t e r n i t y . ' ;
/ / : " I ' m g o i n g t o g o w i t h 5 s l a p s f o r e t e r n i t y . "
s l a p C o u n t . t o S t r i n g ( ) ;
/ / : " 5 "
㫧㫘㫩㫪㫜㫙 and Casting
㫧㫘㫩㫪㫜㫘㫥㫫㫗㫪㫫㫩㫛㫔㫙㫘㫪㫜㫘
㫧㫘㫩㫪㫜㫗㫣㫦㫘㫫㫗㫪㫫㫩㫘
Keep in mind that parseInt better goes with base.
Anything failed to be parsed will be represented as 㫗㫘㫗
p a r s e I n t ( ' 3 . 1 4 1 5 9 2 6 ' , 1 0 ) ;
/ / : 3
p a r s e F l o a t ( ' 3 . 1 4 1 5 9 2 6 ' ) ;
/ / : 3 . 1 4 1 5 9 2 6
p a r s e F l o a t ( ' L e g e n . . . W a i t f o r i t . . . D a r y ' ) ;
/ / : N a N
String Has Properties
Most string properties are accessible in the form of:
variableName.property
Property can be function, and thus can be applied.
v a r w e t W e t W e t = ' I f e e l i t i n m y f i n g e r s I f e e l i t i n m y t o e s '
/ / : u n d e f i n e d
w e t W e t W e t . l e n g t h ; / / p r o p e r t y
/ / : 4 4
w e t W e t W e t . t o U p p e r C a s e ( ) ; / / f u n c t i o n i n v o c a t i o n / a p p l i c a t i o n .
/ / : " I F E E L I T I N M Y F I N G E R S I F E E L I T I N M Y T O E S "
w e t W e t W e t . t o U p p e r C a s e ; / / r e f e r s t o f u n c t i o n i t s e l f
/ / : f u n c t i o n t o U p p e r C a s e ( )
' I a m g o n n a b e a n g r y ! ' . r e p l a c e ( ' g o n n a b e ' , ' ' ) . t o U p p e r C a s e
/ / : " I A M A N G R Y ! "
Some methods on String
string.charAt(k): get the character at position k, or '' if k is not in
the range of string length.
string.length: get the length of the string
string.replace(searchString, replaceString): Make new string by
replacing searchString with replaceString in string
v a r w e t W e t W e t = ' I f e e l i t i n m y f i n g e r s I f e e l i t i n m y t o e s ' ;
/ / : u n d e f i n e d
w e t W e t W e t . l e n g t h ;
/ / : 4 4
w e t W e t W e t . c h a r A t ( 1 3 ) ;
/ / : " m "
w e t W e t W e t . r e p l a c e ( ' I ' , ' i ' ) ;
/ / : " i f e e l i t i n m y f i n g e r s i f e e l i t i n m y t o e s "
Some methods on String
string.indexOf(searchString, [position]): the position of the
searchString in string, starts from 0, from left to right.
position: The position to start search, default to 0.
return -1 if not found.
'The rain of spain falls mainly in the plain.'
v a r s p a i n R a i n = ' T h e r a i n o f s p a i n f a l l s m a i n l y i n t h e p l a i n . ' ;
/ / : u n d e f i n e d
s p a i n R a i n . i n d e x O f ( ' a i n ' ) ;
/ / : 5
s p a i n R a i n . i n d e x O f ( ' a i n ' , 0 ) ;
/ / : 5
s p a i n R a i n . i n d e x O f ( ' a i n ' , 1 3 ) ;
/ / : 1 4
s p a i n R a i n . i n d e x O f ( ' A u d r e y H e p b u r n ' ) ;
/ / : - 1
Some methods on String
string.slice(start, [end]): capture substring from start to end
start: the start position of the string for substring, could be
negative (count backward from the end.)
end: the end position of the string for substring, could be
negative. Defaults to the length of String.
string.substring: do not use it since it doesn't support backward
counting, slice is superior.
v a r f i x Y o u = ' L i g h t s w i l l g u i d e y o u h o m e , a n d i g n i t e y o u r b o n e s ' ;
/ / : u n d e f i n e d
f i x Y o u . s l i c e ( 2 2 , 2 6 ) ;
/ / : " h o m e "
f i x Y o u . s l i c e ( - 5 ) ;
/ / : " b o n e s "
Some methods on String
string.split(delimeter, [limit]): divide a string to an array by its
delimeter
limit: the limit to divided, at most.
v a r i n d u c t i o n = ' T o I t e r a t e I s H u m a n , T o R e c u r s e D i v i n e ' ;
/ / : u n d e f i n e d
i n d u c t i o n . s p l i t ( ' T o ' ) ;
/ / : A r r a y [ " " , " I t e r a t e I s H u m a n , " , " R e c u r s e D i v i n e " ]
i n d u c t i o n . s p l i t ( ' T o ' , 2 ) ;
/ / : A r r a y [ " " , " I t e r a t e I s H u m a n " ]
String is immutable
It cannnot be altered by string[index].
We prefer string.charAt to string[index], since we do not want to
deal with 㫬㫥㫛㫜㫝㫠㫥㫜㫛
Usually we generate new string and assign new string to variable.
v a r s c i e n t i s t = ' N o b o d y s a i d i t w a s e a s y , i t i s s u c h a s h a m e f o r u s t o p a r t '
/ / : u n d e f i n e d
s c i e n t i s t [ 0 ] = ' n ' ;
/ / : " n "
s c i e n t i s t ;
/ / : " N o b o d y s a i d i t w a s e a s y , i t i s s u c h a s h a m e f o r u s t o p a r t "
s c i e n t i s t [ 2 0 0 2 ] ;
/ / : u n d e f i n e d
More string opeartions goes there......
"Complicated string operation?"
Regular expression comes to rescue!
Regular Expression
Extremely useful on strings operations.
Due to its learning curve, we can't cover here but give you a
glimpse today:
v a r i s V a l i d I d = / ^ [ A - Z ] { 1 } [ 1 - 2 ] { 1 } [ 0 - 9 ] { 8 } $ / ;
/ / : u n d e f i n e d
i s V a l i d I d . t e s t ( ' E 2 7 1 5 3 8 1 6 3 ' ) ;
/ / : t r u e
Learning source
Online test tool
Control Structure
Prime Number Test
We can determine whether a number is prime number or not by:
1. for a number , compute
2. we check all prime numbers one by one, if none of
them is a factor of , is a prime number.
x x√
< x√
x x
Prime Number Test
We can determine whether a number is prime number or not by:
1. for a number , compute
2. we check all prime numbers one by one (Iteration,
Loop), if (Condition) none of them is a factor of , is a
prime number.
x x√
≤ x√
x x
Another Example
Abs:
1. For two numbers , compute
2. If (Condition) , abs is , else (Condition),
abs is
a, b (a − b)
(a − b) ≥ 0 (a − b)
(a − b) × (−1)
Control Structure
The examples we've seen above can be described as program
running step by step, the same as (imperative) programming
languages.
The program block: a pieces of codes meant to be executed as a
unit.
To control program's behaviour, it can be generalised as:
Condition: The program block is executed based on the
certain condition is satisfied.
Iteration: The program block executes repeatedly based on
the certain condition is satisfied.
if (else if...else)
v a r a = 9 ;
v a r b = 8 1 ;
v a r a b s ;
a b s = a - b ; / / C o m p u t e ( a - b )
i f ( a b s > = 0 ) { / / I f ( a - b ) > = 0 , a b s i s ( a - b )
a b s = a b s ;
} e l s e i f ( a b s < 0 ) { / / I f ( a - b ) < 0 , a b s i s ( a - b ) * ( - 1 )
a b s = a b s * - 1 ;
}
a b s ;
/ / : 7 2
What abs will be if a = 1812 and b = 1984?
if (else if...else)
i f ( B O O L E A N _ E X P R E S S I O N _ 1 ) {
P R O G R A M _ B L O C K _ 1 ;
} e l s e i f ( B O O L E A N _ E X P R E S S I O N _ 2 ) {
P R O G R A M _ B L O C K _ 2 ;
} e l s e {
P R O G R A M _ B L O C K _ 3 ;
}
The program check if:
1. BOOLEAN_EXPRESSION_1 is evaluated as 㫙㫩㫬㫜, then
PROGRAM_BLOCK_1 is executed, else if
2. BOOLEAN_EXPRESSION_2 is evaluated as 㫙㫩㫬㫜, then
PROGRAM_BLOCK_2 is executed. else
3. if the above checks failed, PROGRAM_BLOCK_3 is
executed.
In JavaScript, else if / else is optional.
if statement can be contained in another if statement.
if (else if..else)
Back to abs program, we see:
v a r a = 9 ;
v a r b = 8 1 ;
v a r a b s ;
a b s = a - b ; / / C o m p u t e ( a - b )
i f ( a b s > = 0 ) { / / I f ( a - b ) > = 0 , a b s i s ( a - b )
a b s = a b s ;
} e l s e i f ( a b s < 0 ) { / / I f ( a - b ) < 0 , a b s i s ( a - b ) * ( - 1 )
a b s = a b s * - 1 ;
}
a b s ;
/ / : 7 2
1. 㫘㫙㫪㫔㫚㫔㫘㫙㫪 is unnecessary (have no effects on program), if
block can be omitted.
2. else if part then will be if part.
v a r a = 9 ;
v a r b = 8 1 ;
v a r a b s ;
a b s = a - b ; / / C o m p u t e ( a - b ) a s a b s
i f ( a b s < 0 ) { / / I f ( a - b ) < 0 , a b s i s ( a - b ) * ( - 1 )
a b s = a b s * - 1 ;
}
a b s ;
/ / : 7 2
The program is cleaner, and the logic is the same.
while
/ / R u s s i a n r o u l e t t e p r o g r a m
v a r b u l l e t = 3 ;
v a r t i m e s = 1 ;
v a r r o t a t e ;
v a r i s D e a d = f a l s e ;
w h i l e ( t i m e s ! = = 1 0 ) {
r o t a t e = M a t h . f l o o r ( M a t h . r a n d o m ( ) * ( 1 + 6 - 1 ) ) + 1 ;
/ / F o r n o w , y o u o n l y n e e d t o k n o w R H S p r o d u c e s r a n d o m n u m b e r f r o m 1 t o 6 .
i f ( r o t a t e = = = b u l l e t ) {
i s D e a d = t r u e ;
b r e a k ;
}
t i m e s = t i m e s + 1 ;
}
i s D e a d ;
/ / : N a h , i t ' s e i t h e r t r u e o r f a l s e , b u t I c a n ' t t e l l y o u .
while
w h i l e ( B O O L E A N _ E X P R E S S I O N ) {
P R O G R A M _ B L O C K ;
}
Entry: When the program is about to enter the loop, it evaluates
BOOLEAN_EXPRESSION. If it turns out to be 㫫㫩㫬㫜, the
program goes into PROGRAM_BLOCK, or just skip.
Loop: When PROGRAM_BLOCK is executed, it evaluates
BOOLEAN_EXPRESSION again. If it turns out to be 㫫㫩㫬㫜, the
program goes into PROGRAM_BLOCK again, or just skip.
Termination: The loop terminates when
BOOLEAN_EXPRESSION is evaluated as 㫝㫘㫣㫪㫜.
㫙㫩㫜㫘㫢, 㫚㫦㫥㫫㫠㫥㫬㫜:
㫙㫩㫜㫘㫢: jumps out of loop no matter what.
㫚㫦㫥㫫㫠㫥㫬㫜: go through the next iteration.
while
/ / R u s s i a n r o u l e t t e p r o g r a m
v a r b u l l e t = 3 ;
v a r t i m e s = 1 ;
v a r r o t a t e ;
v a r i s D e a d = f a l s e ;
w h i l e ( t i m e s ! = = 1 0 ) {
r o t a t e = M a t h . f l o o r ( M a t h . r a n d o m ( ) * ( 1 + 6 - 1 ) ) + 1 ;
/ / F o r n o w , y o u o n l y n e e d t o k n o w R H S p r o d u c e s r a n d o m n u m b e r f r o m 1 t o 6 .
i f ( r o t a t e = = = b u l l e t ) {
i s D e a d = t r u e ;
b r e a k ;
}
t i m e s = t i m e s + 1 ;
}
i s D e a d ;
/ / : N a h , i t ' s e i t h e r t r u e o r f a l s e , b u t I c a n ' t t e l l y o u .
㫫㫠㫤㫜㫪㫔㫕㫚㫚㫔㫠㫟: Boolean Expression.
㫙㫩㫜㫘㫢: jumps out of loop since you're dead already.
㫫㫠㫤㫜㫪㫔㫚㫔㫫㫠㫤㫜㫪㫔㫚㫔㫠: It guarantees that your program
terminates at last.
How many rounds the player has to play if he / she is lucky
enough to stay alive?
Exercises for while
Refine Russian roulette program by introducing 㫧㫣㫘㫚㫜㫩 variable.
㫧㫣㫘㫚㫜㫩 can be either 㫠 or 㫡. The program shall show that it
indicates a death duel (Program stops when either player 1 or
player 2 winds up dead.)
for
Recall while loop in Russian roulette program:
v a r t i m e s = 1 ;
. . .
w h i l e ( t i m e s ! = = 1 0 ) {
. . .
t i m e s = t i m e s + 1 ;
}
The pattern is so common that it leads to the birth of for:
f o r ( v a r t i m e s = 1 ; t i m e s ! = = 1 0 ; t i m e s = t i m e s + 1 ) {
. . .
}
for
f o r ( I N I T I A L I S E R ; C O N D I T I O N ; I T E R A T O R ) {
P R O G R A M _ B L O C K ;
}
can be expanded to:
I N I T I A L I S E R ;
w h i l e ( C O N D I T I O N ) {
P R O G R A M _ B L O C K ;
I T E R A T O R ;
}
for
Recall prime test problem.
v a r n = 8 8 4 9 ;
v a r s q r t O f N = M a t h . s q r t ( n ) ;
v a r i s P r i m e = t r u e ;
f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) {
i f ( n % i = = = 0 ) {
i s P r i m e = f a l s e ;
b r e a k ;
}
}
i s P r i m e ;
/ / : t r u e
Notice i starts from 2.
n % 0 produces 㫗㫘㫗
Wait, you said we only need to check the primes !
However, checking all numbers includes checking those are
prime. (weaker)
≤ x√
Exercises for for
Calculate the sum of 1 to 1000, using for.
Explain why is superior.(1+n)n
2
Exercises
Collatz conjecture: for any natural number , if:
is odd: verify
is even: verify
recursively, and ends up with 1.
Using while, and for to verify Collatz conjecture holds for 1 -
10000;
n > 1
n 3n + 1
n
n
2
n reference
Function
Prime Test (again?)
v a r n = 8 8 4 9 ;
v a r s q r t O f N = M a t h . s q r t ( n ) ;
v a r i s P r i m e = t r u e ;
f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) {
i f ( n % i = = = 0 ) {
i s P r i m e = f a l s e ;
b r e a k ;
}
}
i s P r i m e ;
/ / : t r u e
What if we want to check whether 15919 is a prime number?
Easy, just copy & paste and change n:
v a r n = 1 5 9 1 9 ;
v a r s q r t O f N = M a t h . s q r t ( n ) ;
v a r i s P r i m e = t r u e ;
f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) {
i f ( n % i = = = 0 ) {
i s P r i m e = f a l s e ;
b r e a k ;
}
}
i s P r i m e ;
/ / : t r u e
Okay, what about 15791 15797 15803 15809 15817 15823 15859
15877 15881 15887 15889 15901 15907 15913 15919 15923
15937 15959 15971 15973 15991 16001 16007 16033 16057
16061 16063 16067 16069 16073 .......
As you can see, these codes is basically the same, except for n.
We can refine the code by parameterisation and make it a
subprogram.
v a r i s P r i m e = f u n c t i o n ( n ) {
v a r s q r t O f N = M a t h . s q r t ( n ) ;
v a r i s P r i m e = t r u e ;
f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) {
i f ( n % i = = = 0 ) {
i s P r i m e = f a l s e ;
r e t u r n i s P r i m e ;
}
}
r e t u r n i s P r i m e ;
} ;
/ / : u n d e f i n e d
i s P r i m e ( 1 5 9 0 7 ) ;
/ / : t r u e
Here, we take n as the parameter of the function.
It return values either true or false;
Note you can totally discard isPrime by simply return true or
false.
Ugh, you got two isPrime, which ones you're talking about?
Function
Definition
Function as subprogram
Function as mapping from domain to range (mathematical
definition)
However, in JavaScript, the border of definitions become
blurred.
In JavaScript, function can be seen having two phases:
1. Definition: define the function body, assign it to a variable.
2. Invocation / Application: execute the function body by giving
the parameters to function variable.
How to define a function
v a r F U N C T I O N _ N A M E ;
F U N C T I O N _ N A M E = f u n c t i o n ( p 1 , p 2 , p 3 . . . . . ) {
P R O G R A M _ B L O C K ;
} ;
The function body which takes p1, p2, p3... as parameters and
executes PROGRAM_BLOCK, is assigned to
FUNCTION_NAME.
You might see the following as well, but it didn't give a sense of
function as data.
f u n c t i o n F U N C T I O N _ N A M E ( p 1 , p 2 , p 3 . . . . . . ) {
P R O G R A M _ B L O C K ;
}
How to apply function
F U N C T I O N _ N A M E ( p 1 , p 2 , p 3 . . . . . . ) ;
/ / : r e t u r n v a l u e o r u n d e f i n e d .
Simply supply parameters to function.
PROGRAM_BLOCK may contain 㫩㫜㫫㫬㫩㫥 keyword, which
takes one value as the result of the function. If it's not given,
function will return 㫬㫥㫛㫜㫝㫠㫥㫜㫛 instead.
v a r s u m O f = f u n c t i o n ( n ) {
v a r s u m = ( 1 + n ) * n / 2 ;
r e t u r n s u m ;
} ;
/ / : u n d e f i n e d ;
s u m O f ( 1 0 0 0 ) ;
/ / : 5 0 0 5 0 0
v a r s u m O f 2 = f u n c t i o n ( n ) {
v a r s u m = ( 1 + n ) * n / 2 ;
} ;
/ / : u n d e f i n e d
s u m O f 2 ( 1 0 0 0 ) ;
/ / : u n d e f i n e d
When to define a function
1. You discover duplicate code and common pattern, and you need
to abstract it.
We've seen it before.
2. You discover the mathematical relation of input and output.
v a r f i b o n a c c i = f u n c t i o n ( x ) {
i f ( x = = = 1 | | x = = = 2 ) {
r e t u r n 1 ;
} e l s e i f ( x > 2 ) {
r e t u r n f i b o n a c c i ( x - 1 ) + f i b o n a c c i ( x - 2 ) ;
}
} ;
It just a plain translation from the definition of Fibonacci
number.
Parameter
JavaScript functions do not check the number of arguments
received.
If you supply more arguments than those you define, the
remaining will be omitted.
If you supply less, the rest will be set as 㫬㫥㫛㫜㫝㫠㫥㫜㫛.
v a r f n = f u n c t i o n ( a , b , c ) {
r e t u r n a * b * c ;
} ;
f n ( 1 , 2 , 3 ) ;
/ / : 6
f n ( 1 , 2 ) ;
/ / : N a N ( a n y n u m b e r m u l t i p l i e s u n d e f i n e d e q u a l s t o N a N )
f n ( 1 , 2 , 3 , 7 , 9 ) ;
/ / : 6
Default Values
JavaScript doesn't support default values of parameters by
default, but it can be addressed via:
JavaScript evaluates boolean expression in the form of
㫫㫩㫬㫜㫔㫚㫚㫔㫗㫘㫥㫚㫫㫟㫠㫥㫞㫘. In this case, if 㫘 is 㫬㫥㫛㫜㫝㫠㫥㫜㫛, if
evaluates as 㫢;
v a r f n = f u n c t i o n ( a , b ) {
a = a | | 3 ;
b = b | | 7 ;
r e t u r n a * b ;
} ;
f n ( ) ;
/ / : 2 1
f n ( 9 ) ;
/ / : 6 3
Anonymous Function ( )λ
Recall when we define a function, we define the function body
first and assign it to a variable later.
Instead of assigning it to a variable, the function body can be
used directly, it's called 㫘㫥㫦㫥㫚㫤㫦㫬㫪㫔㫝㫬㫥㫚㫫㫠㫦㫥 in such context.
For example, execute function right after the definition:
( f u n c t i o n ( a , b ) {
r e t u r n a * b ;
} ) ( 7 , 6 ) ;
/ / : 4 2
Function as Data
In JavaScript, you can pass function as data to other function,
return function out of function.
You can construct your logical components in the unit of
functions, and junction them together.
It's quite common pattern in JavaScript: using function as
function callback.
v a r r e p e a t = f u n c t i o n ( f , t i m e s ) {
r e t u r n f u n c t i o n ( n ) {
v a r v = n ;
f o r ( v a r i = 0 ; i < t i m e s ; i = i + 1 ) {
v = f ( v ) ;
}
r e t u r n v ;
} ;
} ;
/ / : u n d e f i n e d
v a r s q u a r e = f u n c t i o n ( n ) {
r e t u r n n * n ;
} ;
/ / : u n d e f i n e d
v a r q u a d = r e p e a t ( s q u a r e , 2 ) ;
/ / : u n d e f i n e d
q u a d ( 3 ) ;
/ / : 8 1
We use square function to make a new function quad which is:
quad(x) = square(square(x))
Scope
In JavaScript, when you invoke a function, you create a local
scope.
When you access a variable in a function, it first lookups the
variables in the scope (parameters, local variables), if it didn't
find a one, it lookups outside the functions. (Bubble up)
v a r i s P r i m e = f u n c t i o n ( n ) {
v a r s q r t O f N = M a t h . s q r t ( n ) ;
v a r i s P r i m e = t r u e ;
f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) {
i f ( n % i = = = 0 ) {
i s P r i m e = f a l s e ;
r e t u r n i s P r i m e ;
}
}
r e t u r n i s P r i m e ;
} ;
Due to the declaration of 㫠㫪㫙㫩㫠㫤㫜 in the function, all 㫠㫪㫙㫩㫠㫤㫜
occurs in the function act as a concrete variable different from
the function name.
Hosting
Consider the program:
㫝㫥㫗㫘 will be 10? or 100?
v a r x = 1 0 ;
v a r f n = f u n c t i o n ( ) {
r e t u r n x ;
v a r x = 1 0 0 ;
} ;
f n ( ) ;
/ / : ?
㫬㫥㫛㫜㫝㫠㫥㫜㫛 actually, but why?
The code actually looks like this:
v a r x = 1 0 ;
v a r f n = f u n c t i o n ( ) {
v a r x ; / / x i s u n d e f i n e d t h e n .
r e t u r n x ;
x = 1 0 0 ;
} ;
f n ( ) ;
/ / : u n d e f i n e d
When you invoke a function, the interpreter scans through your
function body and define the variables you declare first (not
assigned, yet.) and then it executes line by line.
So, in reality, it's a good practice to define your variables at top,
then your program logic.
Closure
v a r x = 1 0 ;
v a r f n = f u n c t i o n ( n ) {
r e t u r n n * x ;
} ;
f n ( 1 0 ) ;
/ / : 1 0 0
n ;
/ / : u n d e f i n e d
x = 1 0 0 0 ;
f n ( 1 0 ) ;
/ / : 1 0 0 0 0
Functions that refer to independent (free) variables. In other
words, the function defined in the closure 'remembers' the
environment in which it was created.
Since 㫝㫥 has access to REPL, 㫝㫥's behaviour is dependent on
REPL. (if REPL will be modified later)
By-Value vs By-Reference
When we talk about variable as parameters of the function:
By-value: the program will make a copy of variable and
operate on the copy.
By-Reference: the program will operate directly on the
variable.
In JavaScript, variables which have primitive type (boolean,
number, string) goes by-value, and those with composite types
(object, array..) go by-reference.
By-Value:
v a r f n = f u n c t i o n ( x ) {
x = 1 0 0 0 ;
r e t u r n x ;
} ;
/ / : u n d e f i n e d
v a r n = 1 0 ;
/ / : u n d e f i n e d
f n ( n ) ;
/ / : 1 0 0 0
n ;
/ / : 1 0
By-Reference:
v a r f n = f u n c t i o n ( x ) {
x . p u s h ( 0 ) ;
r e t u r n x ;
} ;
/ / : u n d e f i n e d
v a r c = [ ] ;
/ / : u n d e f i n e d
f n ( c ) ;
/ / : [ 0 ]
c ;
/ / : [ 0 ]
Exercises
Recall abs program, choose proper parameters and make it a
function.
Design a function fn which gets off work: Write a function
which takes a function f and produces another function which
only works between 9 AM - 5 PM. Your code might work like
this:
v a r s q u a r e = f n ( f u n c t i o n ( e ) {
r e t u r n e * e ;
} ) ;
s q u a r e ( 2 ) ; / / I t ' s 8 : 5 0 n o w
/ / : " I ' m o f f w o r k n o w , l e a v e m e a l o n e ! "
s q u a r e ( 2 ) ; / / I t ' s 9 : 0 1 n o w
/ / : 4
To do so, you need to know the current time:
It's actually a quite common pattern in functional programming,
to compose new functions by mixing them together.
We'll introduce the concept of object later.
v a r c u r r e n t D a t e = n e w D a t e ( ) ;
v a r c u r r e n t H o u r = c u r r e n t D a t e . g e t H o u r s ( ) ;
c u r r e n t H o u r ;
/ / : 0 ( i t v a r i e s )
Array
What does an array look like?
v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ;
/ / : u n d e f i n e d
p r i m e s
/ / : [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ;
p r i m e s [ 3 ] ;
/ / : 7
p r i m e s [ 8 9 ] ;
/ / : u n d e f i n e d
Index Value
0 2
1 3
2 5
...
Array
Like list.
Used to represent sequential data.
Neither the length nor the types of an array are fixed.
However, keep it the same type helps design / use algorithm.
Access its value by a given index, where the index starts
from 0.
where 2 is the index, and 5 is the value.
p r i m e s [ 2 ] ;
/ / : 5
Construct Array
Either by array literal or array.push method:
v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; / / a r r a y l i t e r a l
/ / : u n d e f i n e d
v a r p r i m e s = [ ] ; / / d e f i n e a e m p t y a r r a y
/ / : u n d e f i n e d
p r i m e s . p u s h ( 2 ) ;
/ / : 1
p r i m e s . p u s h ( 3 ) ;
/ / : 2
Add element to an array
The index increases incrementally when new element is added.
array.push method return the length of the new-added array.
Some use 㫧㫩㫠㫤㫜㫪㫘㫧㫩㫠㫤㫜㫪㫝㫣㫜㫥㫞㫫㫟㫚㫔㫚㫔㫡㫢, which returns the
value.
p r i m e s . p u s h ( 2 3 ) ;
/ / : 9
p r i m e s [ 8 ] ;
/ / : 2 3
Remove element from an array
Either by array.pop or array.splice method:
array.pop(): remove the last item and return it.
array.splice(s, c, [items]): remove c items from s, added items
if supplied. (return the deleted part.)
v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ;
/ / : u n d e f i n e d
p r i m e s . p o p ( ) ;
/ / : 1 9
p r i m e s ;
/ / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 ]
p r i m e s . s p l i c e ( 1 , 2 , 0 , 0 ) ;
/ / : A r r a y [ 3 , 5 ]
p r i m e s ;
/ / : A r r a y [ 2 , 0 , 0 , 7 , 1 1 , 1 3 , 1 7 ] ;
Lookup / Modify the array
Remark: we can access the value by a given index:
To change its value, simply assign:
p r i m e s [ 3 ] ;
/ / : 7
p r i m e s [ 3 ] = 3 ;
/ / : 3 ;
p r i m e s [ 3 ] ;
/ / : 3
Some properties / methods on Array
array.length: returns the length of the array.
returns (the maximum index + 1) of the array
Stick to array.push or arr[arr.length]
v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ;
/ / : u n d e f i n e d
p r i m e s [ 8 8 4 9 ] = 9 1 5 2 9 ;
/ / : 9 1 5 2 9
p r i m e s . l e n g t h ;
/ / : 8 8 5 0
p r i m e s ;
/ / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 , < 2 e m p t y s l o t s > , 8 8 4 0 m o r e … ]
Some properties / methods on Array
array.slice(start, [end]): make a new array as sub-array from the
original one
start: the start position of the array for sub-array, could be
negative (count backward from the end.)
end: the end position of the array for sub-array, could be
negative. Defaults to the length of array.
Don't be confused with array.splice.
v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ;
/ / : u n d e f i n e d
p r i m e s . s l i c e ( 3 , 7 ) ;
/ / : A r r a y [ 7 , 1 1 , 1 3 , 1 7 ]
p r i m e s ;
/ / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ]
Sorting
Consider the following program:
By default, the array sorts according to each character's Unicode
value, converted to String first if not.
To make use of array.sort function, we need to supply a
comparison function.
[ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] . s o r t ( ) ;
/ / : A r r a y [ 1 1 , 1 3 , 1 7 , 1 9 , 2 , 3 , 5 , 7 ]
Sorting
The comparison function is supplied as parameter of sort
function.
a and b denotes arbitrary items.
The comparison function denotes the relations of two items by:
[ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] . s o r t ( f u n c t i o n ( a , b ) {
r e t u r n ( a - b ) ;
} ) ;
/ / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ]
(a − b < 0) → (a < b)
(a − b = 0) → (a = b)
(a − b > 0) → (a > b)
The sort method will swap if the return value is larger than 0.
By default it sorts in ascending order. To sort in descending
order, simply return 㫗㫙㫔㫜㫔㫘㫘
How the relations are represented in the above function?
How you would write a comparison function to make it keep the
array the same? (unsorted)
[ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] . s o r t ( f u n c t i o n ( a , b ) {
r e t u r n ( b - a ) ;
} ) ;
/ / : A r r a y [ 1 9 , 1 7 , 1 3 , 1 1 , 7 , 5 , 3 , 2 ]
Exercises
Selection Sort (ascending)
For one unsorted array: [6, 9, 7, 2, 3]
Compare the first element (6 in the case) with the rest by
each, swap them if the first is larger than any in the rest.
In the case, 6 will be swapped with 2. Since we knew
, and those compared with 6 , we knew those
compared with 6 (Transitive relation)
6 > 2 > 6
> 2
Selection Sort (ascending)
After one iteration, the first one is the smallest in the
array. ([2, 9, 7, 6, 3])
Start again from the second element (9 in the case), and the
third..., to the end of the array.
See visualisation
Selection Sort with Comparison Function
Refine your sorting algorithm with one function parameter,
known as comparison function, which is the same as
array.sort
Object
Object
An object is a collection of properties. Properties could be:
Primitive types: Number, String, Boolean
Composite types: Object
Object could be: Function, Array
Function in object is called method.
Whey do we need object, after all?
To define a square in Cartesian coordinates system, we have
two different ways:
Records four points such as (0, 0), (4, 0), (0, 4), (4, 4)
Records the center point (2, 2) and the length of its sides (4)
Diagonal is always larger than the side.
Two representaions of a square
To calculate the area of the square, using the definition 1:
v a r p 1 x = 0 ;
v a r p 1 y = 0 ;
v a r p 2 x = 4 ;
v a r p 2 y = 0 ;
v a r p 3 x = 0 ;
v a r p 3 y = 4 ;
v a r p 4 x = 4 ;
v a r p 4 y = 4 ;
v a r d i s t a n c e = f u n c t i o n ( p 1 x , p 1 y , p 2 x , p 2 y ) {
r e t u r n M a t h . s q r t ( M a t h . p o w ( p 1 x - p 2 x , 2 ) + M a t h . p o w ( p 1 y - p 2 y , 2 ) ) ;
} ;
v a r s q u a r e A r e a = f u n c t i o n ( p 1 x , p 1 y , p 2 x , p 2 y , p 3 x , p 3 y , p 4 x , p 4 y ) {
v a r d 1 = d i s t a n c e ( p 1 x , p 1 y , p 2 x , p 2 y ) ;
v a r d 2 = d i s t a n c e ( p 1 x , p 1 y , p 3 x , p 3 y ) ;
v a r l e n g t h = ( d 1 < = d 2 ) ? d 1 : d 2 ; / / ( d 1 , d 2 m i g h t b e o n l y d i a g o n a l / s i d e
r e t u r n l e n g t h * l e n g t h ;
} ;
s q u a r e A r e a ( p 1 x , p 1 y , p 2 x , p 2 y , p 3 x , p 3 y , p 4 x , p 4 y ) ;
One day, your lead programmer came and says: "Hey, let's do
that in def 2!"
The code is prettier, but every occurrence of old 㫪㫨㫬㫘㫩㫜㫖㫩㫜㫘
need to be modified, along with the coordinates of squares.
v a r c 1 x = 2 ;
v a r c 2 y = 2 ;
v a r s i d e = 4 ;
v a r s q u a r e A r e a = f u n c t i o n ( s i d e ) {
r e t u r n s i d e * s i d e ;
} ;
Imagine Find / Replace for few hundred times...
Let's make a object of it!
In fact, what we REALLY care about is the square, not its
coordinates / sides.
We want to know the area of the square, right?
if we have something like:
Let's refine our code then.
Wouldn't it be nice
v a r s q u a r e A r e a = f u n c t i o n ( s q u a r e ) {
. . . . . .
} ;
s q u a r e A r e a ( s q u a r e ) ;
/ / : 1 6
v a r s q u a r e = {
p 1 : {
x : 0 ,
y : 0
} ,
p 2 : {
x : 4 ,
y : 0
} ,
p 3 : {
x : 0 ,
y : 4
} ,
p 4 : {
x : 4 ,
y : 4
}
} ;
(Cont'd)
v a r d i s t a n c e = f u n c t i o n ( p 1 , p 2 ) {
r e t u r n M a t h . s q r t ( M a t h . p o w ( p 1 . x - p 2 . x , 2 ) + M a t h . p o w ( p 1 . y - p 2 . y
} ;
v a r s q u a r e A r e a = f u n c t i o n ( s ) {
v a r d 1 = d i s t a n c e ( s . p 1 , s . p 2 ) ;
v a r d 2 = d i s t a n c e ( s . p 1 , s . p 3 ) ;
v a r l e n g t h = ( d 1 < = d 2 ) ? d 1 : d 2 ;
r e t u r n l e n g t h * l e n g t h ;
} ;
s q u a r e A r e a ( s q u a r e ) ;
/ / : 1 6
Create Object
We create object by object literal:
object literal: {key: value, [key: value...]}
Key is unique.
we created a nested object. (since the value of 㫧㫠 is a object
and etc.)
You can create new property on the fly:
v a r o b j = {
a : 0
} ;
o b j . b = 1 ;
o b j ;
/ / : O b j e c t { a : 0 , b : 1 }
Access object
We access the value of properties by pointing to their keys, such
as:
Note: you can access properties in the form of square['p1'], too.
(useful when you need to determine key on runtime.)
s q u a r e . p 1 . x ;
/ / : 0 , w h i c h i s e q u a l s t o :
v a r p 1 = s q u a r e . p 1 ;
p 1 . x ;
/ / : 0
Let's rewrite in Def. 2
Notice the parameters of squareArea is the same as the previous
one.
v a r s q u a r e = {
c 1 : {
x : 2 ,
y : 2
} ,
s i d e : 4
} ;
v a r s q u a r e A r e a = f u n c t i o n ( s ) {
r e t u r n s . s i d e * s . s i d e ;
} ;
s q u a r e A r e a ( s q u a r e ) ;
/ / : 1 6
Methods
When you put function into the object:
㫫㫟㫠㫪 is a reference to the object itself.
array.sort and such are all object methods.
v a r s q u a r e = {
c 1 : {
x : 2 ,
y : 2
} ,
s i d e : 4 ,
g e t A r e a : f u n c t i o n ( ) {
r e t u r n t h i s . s i d e * t h i s . s i d e ;
}
} ;
s q u a r e . g e t A r e a ( ) ;
/ / : 1 6
㫫㫟㫠㫪
㫫㫟㫠㫪 depends on the current context where function is invoked:
Since when the function is invoked, the current scope refers to
the function body itself and outer (recall closure), and there is no
㫪㫠㫛㫜 defined.
/ / N o t i c e w e a s s i g n t h e f u n c t i o n b o d y i n s t e a d o f c a l l i n g i t .
v a r a r e a = s q u a r e . g e t A r e a ;
a r e a ( ) ;
/ / : N a N
Function vs. Method
We put function in a object (method) when it's dependent of the
object.
A good indicator is the use of 㫫㫟㫠㫪.
Of course, it might arise political wars. : ) (Critical thinking, and
only the paranoid survive!)
Create object based on the existing one.
The object is by-reference, so the following don't copy new
object. (They refers to the same object.)
v a r o b j = {
f o o : ' b a r '
} ;
v a r n e w O b j = o b j ;
n e w O b j . b a z = ' q u x ' ;
o b j . b a z ;
/ / : ' q u x '
To construct a new object, we can use:
Object.create (ECMAScript 5)
㫥㫜㫮 Keyword
function returning new object
We sticks to the first for now.
v a r o b j = {
f o o : m s g ,
b a z : ' q u x '
} ;
v a r o b j 1 = O b j e c t . c r e a t e ( o b j ) ;
v a r o b j 2 = O b j e c t . c r e a t e ( o b j ) ;
o b j 1 . b a z = ' L a l a l a ' ;
o b j 2 . b a z ;
/ / : ' q u x '
Construct Playlist
Given the following playlist:
Can you choose proper data structure for it?
T r a c k N a m e A r t i s t D u r a t i o n ( s )
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
G o d O n l y K n o w s T h e B e a c h B o y s 1 7 1
P i a n o M a n B i l l y J o e l 3 3 8
N e w Y o r k , N e w Y o r k F r a n k S i n a t r a 2 0 6
M y W a y F r a n k S i n a t r a 2 7 6
N e w Y o r k , N e w Y o r k C a t P o w e r 1 2 0
D o w n t o w n T r a i n E v e r y t h i n g b u t t h e G i r l 1 8 4
I ' m G o n n a B e ( 5 0 0 M i l e s ) T h e P r o c l a i m e r s 2 1 7
L a V i e E n R o s e C r i s t i n M i l i o t i 1 1 5
Since it's a playlist, an array is a reasonable choice.
How can we represent one song? Maybe using array:
v a r s o n g = [ ' G o d O n l y K n o w s ' , ' T h e B e a c h B o y s ' , 1 7 1 ] ;
and access the property by 㫪㫦㫥㫞㫘㫟㫚....
Nah, it sucks.
We cannot determine the relation between properties and
index directly!
Using object:
And we can puts it in an array:
v a r s o n g = {
t i t l e : ' G o d O n l y K n o w s ' ,
a r t i s t : ' T h e B e a c h B o y s ' ,
d u r a t i o n : 1 7 1
} ;
v a r p l a y l i s t = [
{ t i t l e : ' G o d O n l y K n o w s ' , a r t i s t : ' T h e B e a c h B o y s ' , d u r a t i o n
. . . . . .
] ;
Exercises
We can answer questions like:
What songs is performed by Frank Sinatra?
Going through the list and find those performed by him.
Can you sort the playlist by its duration?
Recall array.sort method?
List all artists who perform New York, New York
Going through the list and find those performed the song.
How many object exist in the code?
8? Are you sure...
Inheritance
JavaScript uses prototype-based inheritance, by referring to
existing object to extends its behaviours.
Each object may has a prototype reference, which points to the
object they want to inherit.
when you access properties, it searches from itself, then its
prototype object. If the object is found and property exists, then
it stops. If not, it searches from its prototype object again....
recursively, to 㫘㫙㫡㫜㫚㫫 or failed when it cannot find prototype
object.
v a r a = {
f o o : ' b a r '
} ;
v a r b = O b j e c t . c r e a t e ( a ) ;
a . i s P r o t o t y p e O f ( b ) ;
/ / : t r u e
O b j e c t . g e t P r o t o t y p e O f ( b ) = = = a ;
/ / : t r u e , i t r e f e r s t o t h e s a m e m e m o r y l o c a t i o n .
b . f o o ;
/ / : " b a r "
b . f o o = ' b a z ' ;
b . f o o ;
/ / : " b a z " , s i n c e b h a s i t s o w n f o o p r o p e r t y n o w , ( w h a t a b o u t a . f o o ? )
So, instead of class-based, prototype-based much more like:
To see more .about prototype
Primitive types: object or not?
Recall the definition of object:
An object is a collection of properties.
str.toUpperCase is a function, and it got a property called
toUpperCase, so it's a object!?
str.toUpperCase is actually:
If you use typeof to check it's type.
Warning: typeof could be very deceiving, and typeof is a
operator, not a function.
' I t  ' s o v e r n o w , t h e m u s i c o f t h e n i g h t ! ' . t o U p p e r C a s e ( ) ;
/ / : " I T ' S O V E R N O W , T H E M U S I C O F T H E N I G H T ! "
/ / T h i s i s a c t u a l l y d o n e v i a a w r a p p e r o b j e c t :
v a r s t r = n e w S t r i n g ( ' I t  ' s o v e r n o w , t h e m u s i c o f t h e n i g h t ! ' ) ;
s t r . t o U p p e r C a s e ( ) ;
/ / : " I T ' S O V E R N O W , T H E M U S I C O F T H E N I G H T ! "
t y p e o f s t r ;
/ / : " o b j e c t "
t y p e o f ' I t  ' s o v e r n o w , t h e m u s i c o f t h e n i g h t ! ' ;
/ / : " s t r i n g "
Exercises
After the accident of Opéra de Paris, the Phantom was on the
run. He had an income of 22K and he needed to pay 15K to
keep himself alive. Design an phantom object which helps him
calculate how much he still had.
Design an object representing your mobile, and explain your
design.
Ad

More Related Content

What's hot (18)

Lecture 1
Lecture 1Lecture 1
Lecture 1
Soran University
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
yoavrubin
 
F sharp - an overview
F sharp - an overviewF sharp - an overview
F sharp - an overview
Christoph Santschi
 
F# for Scala developers
F# for Scala developersF# for Scala developers
F# for Scala developers
Alfonso Garcia-Caro
 
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
Kamiya Toshihiro
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 Variables
Hock Leng PUAH
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
Robbin Zhao
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in Python
Valerio Maggio
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Hossam Ghareeb
 
Opps concept
Opps conceptOpps concept
Opps concept
divyalakshmi77
 
Python master class 2
Python master class 2Python master class 2
Python master class 2
Chathuranga Bandara
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
Understanding F# Workflows
Understanding F# WorkflowsUnderstanding F# Workflows
Understanding F# Workflows
mdlm
 
TypeScript, Now.
TypeScript, Now.TypeScript, Now.
TypeScript, Now.
Suthep Sangvirotjanaphat
 
Software Craftsmanship - 2
Software Craftsmanship - 2Software Craftsmanship - 2
Software Craftsmanship - 2
Uri Lavi
 
While loop
While loopWhile loop
While loop
RabiyaZhexembayeva
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
yoavrubin
 
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
Kamiya Toshihiro
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 Variables
Hock Leng PUAH
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
Robbin Zhao
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in Python
Valerio Maggio
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Hossam Ghareeb
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
Understanding F# Workflows
Understanding F# WorkflowsUnderstanding F# Workflows
Understanding F# Workflows
mdlm
 
Software Craftsmanship - 2
Software Craftsmanship - 2Software Craftsmanship - 2
Software Craftsmanship - 2
Uri Lavi
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 

Similar to JavaScript: Core Part (20)

JavaScript Interview Questions PDF By ScholarHat
JavaScript Interview  Questions PDF By ScholarHatJavaScript Interview  Questions PDF By ScholarHat
JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
My final requirement
My final requirementMy final requirement
My final requirement
katrinaguevarra29
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
Cherimay Batallones
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
olracoatalub
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Ashita Agrawal
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
Survelaine murillo ppt
Survelaine murillo pptSurvelaine murillo ppt
Survelaine murillo ppt
Survelaine Murillo
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
JamaicaAubreyUnite
 
DEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellDEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World Haskell
Bryan O'Sullivan
 
Applicative Functor - Part 2
Applicative Functor - Part 2Applicative Functor - Part 2
Applicative Functor - Part 2
Philip Schwarz
 
Java script summary
Java script summaryJava script summary
Java script summary
maamir farooq
 
Javascript
JavascriptJavascript
Javascript
Sheldon Abraham
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
aprilyyy
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
Ni
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Modern_2.pptx for java
Modern_2.pptx for java Modern_2.pptx for java
Modern_2.pptx for java
MayaTofik
 
JavaScript Interview Questions PDF By ScholarHat
JavaScript Interview  Questions PDF By ScholarHatJavaScript Interview  Questions PDF By ScholarHat
JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
olracoatalub
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
DEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World HaskellDEFUN 2008 - Real World Haskell
DEFUN 2008 - Real World Haskell
Bryan O'Sullivan
 
Applicative Functor - Part 2
Applicative Functor - Part 2Applicative Functor - Part 2
Applicative Functor - Part 2
Philip Schwarz
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
aprilyyy
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
Ni
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
Modern_2.pptx for java
Modern_2.pptx for java Modern_2.pptx for java
Modern_2.pptx for java
MayaTofik
 
Ad

Recently uploaded (20)

The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Full Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest VersionFull Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest Version
jonesmichealj2
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Full Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest VersionFull Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest Version
jonesmichealj2
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Ad

JavaScript: Core Part

  • 2. Who am I? Why JavaScript? Language ECMAScript Core Part Primitive Type and Variables String Control Structure Function Array Object
  • 4. About Myself Master in IM, NTU (2014 - ) BS in MIS, NCCU (2010 - 2014) I'm interested in Web Programming, Functional Programming I write codes in: Python, JavaScript, For now, I am learning: Haskell, LISP My mail is: pa4373 <at> gmail.com Along with my: Skype, LINE ID: pa4373, https://github.com/pa4373
  • 6. "JavaScript is eating the world."
  • 7. JavaScript is dominant in the World Wide Web. #1 Programming language, according to popularity on GitHub and StackOverflow. ( ) It runs everywhere. Web client, desktop / mobile app, server, embedded system and such. It got more than 40K+ jobs on LinkedIn, closely following Java jobs. Many languages now can compiled to JavaScript. (web assembly) source
  • 8. Unreal engine 4 run on Firefox
  • 9. Leap Motion Node Drone Flight in 2013
  • 11. Specification vs. Implementation Specification What makes a piece of code a program, and what its behaviour shall be. Syntax (form) Semantic (meaning) Implementation System for executing computer program. (Compiler, Interpreter, Runtime and etc.)
  • 12. Little Analogy "Google that yourself" which means finding something with Google Search Engine. Reese opened Firefox, went to and searched for something. Finch opened Chrome, went to and searched for something. Reese and Finch did same things, but with different approaches. (Different implementors) https://www.google.com/ https://www.google.co.uk/
  • 13. Back to JavaScript By syntax rules, the following piece of code is a program: Semantic: declare a function named id which takes one object and return exactly the same object. v a r i d = f u n c t i o n ( o b j ) { r e t u r n o b j ; } ;
  • 14. What about Implementation? Several existing implementations, referred to JavaScript engine: the program executes JavaScript, usually called Process Virtual Machine. Popular ones such as , , Don't reinvent the wheel: Lots of functions are pre-built, as libraries. SpiderMonkey + Gekco Firefox V8 + WebKit Chrome V8 + Few networking libraries Node.js Google's V8 Mozilla's SpiderMonkey Rhino → → →
  • 15. Standardization If we have so many implementations, what guarantees that they all follow the specification? (Compatibility) : the process of developing and implementing technical standards. Few groups known for standardization: , , . Standardization ISO ANSI ECMA
  • 16. ECMAScript In 1996, Netscape filed the application to ECMA, and it was released as ECMAScript 1 in 1997. For now, the mainstream is ECMAScript 5, released in 2009, supported by most of modern browsers. While the browsers don't always stick to the specification, it's good to take it as the guideline.
  • 18. Core Part It's beneficial to understand the relationship of components of the language, due to the rich (and sophisticated) ecosystem of JavaScript. Although you need different knowledge for different environments, the common part stands out as the core part.
  • 19. This tutorial is dedicated to the core part of the language. We won't talk about how to interact with browsers or write server program, yet... INSTEAD we focus on components allows you to mentally model your application. "A language that doesn't affect the way you think about programming, is not worth knowing." ~ Alan Peris (1922 – 1990)
  • 20. "No, I just want to get my job done, it doesn't matter my codes all look like the same." To better understand the usage pattern of others' libraries. To design the program easier for others to understand. For fun, and make yourself look smart. Like learning English, you will do better likely if you appreciate its culture.
  • 21. REPL (Read–eval–print loop) The environment reads input from user, evaluates them as code at the given context, prints the result, and loops back. Great for learning, debugging and experimental programming.
  • 22. REPL (Read–eval–print loop) Most browsers have built-in REPL: for Firefox and Chrome: Right click on the web page, choose "Inspect Element" and select "Console" tab on the developer panel. Firefox will be used through the following demonstration.
  • 23. Type 㫠㫔㫚㫔㫠㫘 and then press "Enter", it will output 㫡.
  • 24. To represent the process of using REPL, we take the following form from now on: where '//: ' stands for program output. the input can be divided in multiple lines. Make a newline instead of evaluating: "Shift" + "Enter" (㫞㫞 for single-line comment.) v a r i d = f u n c t i o n ( o b j ) { r e t u r n o b j ; } ; / / : u n d e f i n e d
  • 25. Exercise (~5 mins) Fire up REPL and type following statements (ends with ;) in sequence by instructions, try and discuss the outputs of REPL: Don't copy & paste, muscle memory helps learn a new language. / / p r o g r a m 1 . " I t h o u g h t F e l i c i t y J o n e s w a s m e . " ; / / p r o g r a m 2 . v a r j a n e H a w k i n g S a y = f u n c t i o n ( ) { r e t u r n " I t h o u g h t F e l i c i t y J o n e s w a s m e . " ; } ; / / p r o g r a m 3 , i t o n l y w o r k s a f t e r p r o g r a m 2 i s e v a l u a t e d . j a n e H a w k i n g S a y ( ) ;
  • 26. Some facts about this little exercise Each statement ends with semicolon (;) Just like each sentence in English ends with period. By convention, the naming rule of JavaScript is Camel-Case. The indentation use two spaces, not tab. When declaring a function, there's one space between 㫝㫬㫥㫚㫫㫠㫦㫥 keyword and argument list.
  • 28. REPL as Calculator We have seen that how to use REPL to do addition: Multiplication: Combine them together: This does the same for subtraction (-), division (/). 1 + 1 ; / / : 2 2 * 5 * 1 3 ; / / : 1 3 0 ( 1 + 1 0 0 0 ) * 1 0 0 0 / 2 ; / / : 5 0 0 5 0 0
  • 29. We can also compare them: The statement we've seen so far is called expression, which means it's evaluated by interpreter and the result value is produced and returned. Wait, what is 㫝㫘㫣㫪㫜? 2 > 8 ; / / : f a l s e 1 0 > = 1 0 ; / / : t r u e
  • 30. Data Type Data type is very important, since it determines: The possible values (range) Operations allowed to be done In JavaScript, data type can be categorised into: Primitive Types: the basic unit provided by JavaScript. Composite Types: can be constructed from primitive values and composite values. Special Types: 㫗㫬㫣㫣, 㫚㫥㫛㫜㫝㫠㫥㫜㫛. (will talk about it later.) and etc.
  • 31. Primitive Types Referred to built-in data structures, and they are: Atomic: can't be broken down into smaller data type. Immutable: once the value is decided, it can't be changed. In ES5, primitive types are: Boolean Number String It's fair to assume that 㫝㫘㫣㫪㫜 seen in the previous slides is type of Boolean.
  • 32. Boolean Type Only contains two values: It denotes the truth value of one proposition, such as: 㫖㫙㫖㫔㫚㫚㫚㫔㫣㫖 㫠㫟㫔㫛㫔㫡 {true, f alse}
  • 33. Logical Operations: Take one or two boolean value, produces a new value by: Negation (not): 㫕 Conjunction (and): 㫕㫕 Disjunction (or): 㫚㫚 Negation has higher precedence than conjunction and disjunction. ! t r u e ; / / : f a l s e t r u e & & f a l s e ; / / : f a l s e f a l s e | | t r u e ; / / : t r u e
  • 34. Number Type Only one number type: the double-precision 64-bit binary format IEEE 754 value (number between -( ) and ) Nah, basically you just need to remember it got double type internally. There is no specific type for integers. No need to worry about integer overflow. Everything not within the range goes: 㫘㫥㫝㫠㫥㫠㫫㫚 − 12 53 − 12 53 2 / 0 ; / / : I n f i n i t y
  • 35. Number Type Unary operator: 㫜 (signed) Binary operators: 㫚, 㫜, 㫙, 㫞, 㫔 (mod) Operations on float-point numbers is tricky: While normally it didn't affect the usage, sometimes you may need precise result. Scale to integer and dividing later: more 0 . 1 + 0 . 2 ; / / : 0 . 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 ( 0 . 1 * 1 0 + 0 . 2 * 1 0 ) / 1 0 ; / / : 0 . 3
  • 36. Number Type 㫗㫘㫗: 'not a number' (although it has number type) Can be made when converting a illegal string to number: you can test a number with 㫠㫪㫗㫘㫗 function. If isNaN returns false, the input is or can be parsed to number type. p a r s e I n t ( ' o o p s ' , 1 0 ) ; / / : N a N i s N a N ( 1 0 ) ; / / : f a l s e
  • 37. Comparison and Equivalence You can compare numbers with 㫛, 㫙, 㫛㫚, 㫙㫚. The result got boolean type. Equivalence is a little tricky: Stick to 㫚㫚㫚, 㫕㫚㫚 instead of 㫚㫚, 㫕㫚 2 > = 8 ; / / : f a l s e 0 = = f a l s e ; / / : t r u e 0 = = = f a l s e ; / / : f a l s e
  • 38. Ternary Operator An operator in the sense of 㫘㫗㫜㫙㫗㫖㫗㫜㫖㫗㫘㫖. 㫙㫗㫘㫙㫘㫘㫘㫙㫘㫘㫗㫔㫜㫔㫖㫘㫙㫗㫖㫘㫘㫘㫘㫗㫔㫠㫔㫗㫔㫖㫘㫙㫗㫖㫘㫘㫘㫘㫗㫔㫡 If PROPOSITION is 㫫㫩㫬㫜 then return EXPRESSION 1, else return EXPRESSION 2. ( 2 > 8 ) ? 6 8 9 : 6 3 3 ; / / : 6 3 3
  • 39. Variable The programs we've seen so far were written in one-line expression. We need some way to save the result for later use, at the given context. Variable, serving as program's memory, is a popular way to address the problem. Variable in the sense of computer architecture, not mathematically.
  • 40. Variable Variable is composed of an identifier and its value. (the value may not be defined.) Consider the following program: v a r x ; / / x i s i d e n t i f i e r . / / : u n d e f i n e d x ; / / f o r n o w , x h a s n o t c o n t a i n e d a n y v a l u e , y e t . / / : u n d e f i n e d x = 3 ; / / : 3 x ; / / x c o n t a i n s 3 n o w . / / : 3
  • 41. Declaration New local variable is declared with keyword 㫭㫘㫩, along with identifier. If you skip 㫭㫘㫩 keyword, the variable became global, which is very evil. The identifier is case-sensitive. Don't need to specify the data type. v a r x ;
  • 42. Assignment To assign a value to a variable, put the value / expression on RHS, the variable on LHS of 㫚. When the assignment occurs, the value is returned immediately. If a variable is declared, but has not been assigned, the value of the variable is 㫬㫥㫛㫜㫝㫠㫥㫜㫛. x = 3 ; / / : 3 v a r x ; / / : u n d e f i n e d x ; / / : u n d e f i n e d
  • 43. Assignment Assignment can occurs more than one time, with value in different data type. v a r x ; / / : u n d e f i n e d x = 0 ; / / : 0 x = f a l s e ; / / : f a l s e
  • 44. Shortcut The following is not necessary to construct program. Declaration and assignment: Operator and assignment 㫚㫚: The same goes with 㫜㫚, 㫙㫚, 㫞㫚, 㫔㫚 v a r x = 0 ; / / : u n d e f i n e d / / n o t i c e t h a t t h e v a l u e i s n o t r e t u r n e d i n t h e c a s e . x / / : 0 v a r x = 1 0 ; / / : u n d e f i n e d x + = 1 0 / / t h e s a m e a s x = x + 1 0 / / : 2 0
  • 45. 㫥㫬㫣㫣 The value null is a JavaScript literal representing null or an "empty" value, i.e. no object value is present. n u l l ; / / : n u l l
  • 46. 㫥㫬㫣㫣 vs 㫬㫥㫛㫜㫝㫠㫥㫜㫛 null undefined as the parameters of function which is not a object. the variable is declared but not assigned, yet. as the top of prototype chains some parameters is missing when the function is applied. the property of object doesn't exist. the function doesn't return values (void vs undefined)
  • 47. Falsy values The values which act like 㫝㫘㫣㫪㫜 in boolean operations. Falsy values in JavaScript: 㫝㫘㫣㫪㫜 㫟 (zero) 㫖㫖 (empty string) 㫥㫬㫣㫣 㫬㫥㫛㫜㫝㫠㫥㫜㫛 㫗㫘㫗 (a special Number value meaning Not-a-Number!) u n d e f i n e d | | t r u e ; / / : t r u e
  • 48. Exercises In REPL, use variables, addition / subtraction / multiplication / division to perform the following algorithms. Finally, use comparison to determine the result is correct. You shall be familiar with variable, arithmetic operations, comparison, Boolean value
  • 49. Mobile Number Magic: (It has to be 9 digits, and you might assume it's 891230567.) 1. Write down the first 5 digits. 2. Multiple 80 with that number. 3. Plus 1 to that number. 4. Multiple 250 with that number. 5. Plus the last 4 digits, twice! 6. Minus 250. 7. Using comparison to check if it's your mobile number. 8. If it's your number, we're done here. If not, divide it by 2. 9. Repeat step 7 again.
  • 50. Note: This can be seen as: if a has 5 digits and b has 4 digits, it reflects your mobile number structure. 2(a × + b) = a × 2 × + 2b10 4 10 4 = (a × 80 + 1) × 250 + 2b − 250
  • 52. String String is a finite sequence of characters, usually used to represent text. To construct a string, put things in double / single quotes (single is preferable.) There is no specific type for characters. ' H a a a a a v e y o u m e t T e d ? ' ; / / : ' H a a a a a v e y o u m e t T e d ? ' v a r c h a r = ' a ' ;
  • 53. 㫚 and Casting Consider the program: Notice that 㫙 as esacpe char before 㫖 in the string. 㫚 stands for concatenation when at least one of operand is String. It will attempt to call 㫫㫦㫘㫫㫩㫠㫥㫞 method on non-string operand. v a r s l a p C o u n t = 5 ; / / : u n d e f i n e d ' I ' m g o i n g t o g o w i t h ' + s l a p C o u n t + ' s l a p s f o r e t e r n i t y . ' ; / / : " I ' m g o i n g t o g o w i t h 5 s l a p s f o r e t e r n i t y . " s l a p C o u n t . t o S t r i n g ( ) ; / / : " 5 "
  • 54. 㫧㫘㫩㫪㫜㫙 and Casting 㫧㫘㫩㫪㫜㫘㫥㫫㫗㫪㫫㫩㫛㫔㫙㫘㫪㫜㫘 㫧㫘㫩㫪㫜㫗㫣㫦㫘㫫㫗㫪㫫㫩㫘 Keep in mind that parseInt better goes with base. Anything failed to be parsed will be represented as 㫗㫘㫗 p a r s e I n t ( ' 3 . 1 4 1 5 9 2 6 ' , 1 0 ) ; / / : 3 p a r s e F l o a t ( ' 3 . 1 4 1 5 9 2 6 ' ) ; / / : 3 . 1 4 1 5 9 2 6 p a r s e F l o a t ( ' L e g e n . . . W a i t f o r i t . . . D a r y ' ) ; / / : N a N
  • 55. String Has Properties Most string properties are accessible in the form of: variableName.property Property can be function, and thus can be applied. v a r w e t W e t W e t = ' I f e e l i t i n m y f i n g e r s I f e e l i t i n m y t o e s ' / / : u n d e f i n e d w e t W e t W e t . l e n g t h ; / / p r o p e r t y / / : 4 4 w e t W e t W e t . t o U p p e r C a s e ( ) ; / / f u n c t i o n i n v o c a t i o n / a p p l i c a t i o n . / / : " I F E E L I T I N M Y F I N G E R S I F E E L I T I N M Y T O E S " w e t W e t W e t . t o U p p e r C a s e ; / / r e f e r s t o f u n c t i o n i t s e l f / / : f u n c t i o n t o U p p e r C a s e ( ) ' I a m g o n n a b e a n g r y ! ' . r e p l a c e ( ' g o n n a b e ' , ' ' ) . t o U p p e r C a s e / / : " I A M A N G R Y ! "
  • 56. Some methods on String string.charAt(k): get the character at position k, or '' if k is not in the range of string length. string.length: get the length of the string string.replace(searchString, replaceString): Make new string by replacing searchString with replaceString in string v a r w e t W e t W e t = ' I f e e l i t i n m y f i n g e r s I f e e l i t i n m y t o e s ' ; / / : u n d e f i n e d w e t W e t W e t . l e n g t h ; / / : 4 4 w e t W e t W e t . c h a r A t ( 1 3 ) ; / / : " m " w e t W e t W e t . r e p l a c e ( ' I ' , ' i ' ) ; / / : " i f e e l i t i n m y f i n g e r s i f e e l i t i n m y t o e s "
  • 57. Some methods on String string.indexOf(searchString, [position]): the position of the searchString in string, starts from 0, from left to right. position: The position to start search, default to 0. return -1 if not found. 'The rain of spain falls mainly in the plain.' v a r s p a i n R a i n = ' T h e r a i n o f s p a i n f a l l s m a i n l y i n t h e p l a i n . ' ; / / : u n d e f i n e d s p a i n R a i n . i n d e x O f ( ' a i n ' ) ; / / : 5 s p a i n R a i n . i n d e x O f ( ' a i n ' , 0 ) ; / / : 5 s p a i n R a i n . i n d e x O f ( ' a i n ' , 1 3 ) ; / / : 1 4 s p a i n R a i n . i n d e x O f ( ' A u d r e y H e p b u r n ' ) ; / / : - 1
  • 58. Some methods on String string.slice(start, [end]): capture substring from start to end start: the start position of the string for substring, could be negative (count backward from the end.) end: the end position of the string for substring, could be negative. Defaults to the length of String. string.substring: do not use it since it doesn't support backward counting, slice is superior. v a r f i x Y o u = ' L i g h t s w i l l g u i d e y o u h o m e , a n d i g n i t e y o u r b o n e s ' ; / / : u n d e f i n e d f i x Y o u . s l i c e ( 2 2 , 2 6 ) ; / / : " h o m e " f i x Y o u . s l i c e ( - 5 ) ; / / : " b o n e s "
  • 59. Some methods on String string.split(delimeter, [limit]): divide a string to an array by its delimeter limit: the limit to divided, at most. v a r i n d u c t i o n = ' T o I t e r a t e I s H u m a n , T o R e c u r s e D i v i n e ' ; / / : u n d e f i n e d i n d u c t i o n . s p l i t ( ' T o ' ) ; / / : A r r a y [ " " , " I t e r a t e I s H u m a n , " , " R e c u r s e D i v i n e " ] i n d u c t i o n . s p l i t ( ' T o ' , 2 ) ; / / : A r r a y [ " " , " I t e r a t e I s H u m a n " ]
  • 60. String is immutable It cannnot be altered by string[index]. We prefer string.charAt to string[index], since we do not want to deal with 㫬㫥㫛㫜㫝㫠㫥㫜㫛 Usually we generate new string and assign new string to variable. v a r s c i e n t i s t = ' N o b o d y s a i d i t w a s e a s y , i t i s s u c h a s h a m e f o r u s t o p a r t ' / / : u n d e f i n e d s c i e n t i s t [ 0 ] = ' n ' ; / / : " n " s c i e n t i s t ; / / : " N o b o d y s a i d i t w a s e a s y , i t i s s u c h a s h a m e f o r u s t o p a r t " s c i e n t i s t [ 2 0 0 2 ] ; / / : u n d e f i n e d More string opeartions goes there......
  • 63. Regular Expression Extremely useful on strings operations. Due to its learning curve, we can't cover here but give you a glimpse today: v a r i s V a l i d I d = / ^ [ A - Z ] { 1 } [ 1 - 2 ] { 1 } [ 0 - 9 ] { 8 } $ / ; / / : u n d e f i n e d i s V a l i d I d . t e s t ( ' E 2 7 1 5 3 8 1 6 3 ' ) ; / / : t r u e Learning source Online test tool
  • 65. Prime Number Test We can determine whether a number is prime number or not by: 1. for a number , compute 2. we check all prime numbers one by one, if none of them is a factor of , is a prime number. x x√ < x√ x x
  • 66. Prime Number Test We can determine whether a number is prime number or not by: 1. for a number , compute 2. we check all prime numbers one by one (Iteration, Loop), if (Condition) none of them is a factor of , is a prime number. x x√ ≤ x√ x x
  • 67. Another Example Abs: 1. For two numbers , compute 2. If (Condition) , abs is , else (Condition), abs is a, b (a − b) (a − b) ≥ 0 (a − b) (a − b) × (−1)
  • 68. Control Structure The examples we've seen above can be described as program running step by step, the same as (imperative) programming languages. The program block: a pieces of codes meant to be executed as a unit. To control program's behaviour, it can be generalised as: Condition: The program block is executed based on the certain condition is satisfied. Iteration: The program block executes repeatedly based on the certain condition is satisfied.
  • 69. if (else if...else) v a r a = 9 ; v a r b = 8 1 ; v a r a b s ; a b s = a - b ; / / C o m p u t e ( a - b ) i f ( a b s > = 0 ) { / / I f ( a - b ) > = 0 , a b s i s ( a - b ) a b s = a b s ; } e l s e i f ( a b s < 0 ) { / / I f ( a - b ) < 0 , a b s i s ( a - b ) * ( - 1 ) a b s = a b s * - 1 ; } a b s ; / / : 7 2 What abs will be if a = 1812 and b = 1984?
  • 70. if (else if...else) i f ( B O O L E A N _ E X P R E S S I O N _ 1 ) { P R O G R A M _ B L O C K _ 1 ; } e l s e i f ( B O O L E A N _ E X P R E S S I O N _ 2 ) { P R O G R A M _ B L O C K _ 2 ; } e l s e { P R O G R A M _ B L O C K _ 3 ; } The program check if: 1. BOOLEAN_EXPRESSION_1 is evaluated as 㫙㫩㫬㫜, then PROGRAM_BLOCK_1 is executed, else if 2. BOOLEAN_EXPRESSION_2 is evaluated as 㫙㫩㫬㫜, then PROGRAM_BLOCK_2 is executed. else 3. if the above checks failed, PROGRAM_BLOCK_3 is executed.
  • 71. In JavaScript, else if / else is optional. if statement can be contained in another if statement.
  • 72. if (else if..else) Back to abs program, we see: v a r a = 9 ; v a r b = 8 1 ; v a r a b s ; a b s = a - b ; / / C o m p u t e ( a - b ) i f ( a b s > = 0 ) { / / I f ( a - b ) > = 0 , a b s i s ( a - b ) a b s = a b s ; } e l s e i f ( a b s < 0 ) { / / I f ( a - b ) < 0 , a b s i s ( a - b ) * ( - 1 ) a b s = a b s * - 1 ; } a b s ; / / : 7 2 1. 㫘㫙㫪㫔㫚㫔㫘㫙㫪 is unnecessary (have no effects on program), if block can be omitted. 2. else if part then will be if part.
  • 73. v a r a = 9 ; v a r b = 8 1 ; v a r a b s ; a b s = a - b ; / / C o m p u t e ( a - b ) a s a b s i f ( a b s < 0 ) { / / I f ( a - b ) < 0 , a b s i s ( a - b ) * ( - 1 ) a b s = a b s * - 1 ; } a b s ; / / : 7 2 The program is cleaner, and the logic is the same.
  • 74. while / / R u s s i a n r o u l e t t e p r o g r a m v a r b u l l e t = 3 ; v a r t i m e s = 1 ; v a r r o t a t e ; v a r i s D e a d = f a l s e ; w h i l e ( t i m e s ! = = 1 0 ) { r o t a t e = M a t h . f l o o r ( M a t h . r a n d o m ( ) * ( 1 + 6 - 1 ) ) + 1 ; / / F o r n o w , y o u o n l y n e e d t o k n o w R H S p r o d u c e s r a n d o m n u m b e r f r o m 1 t o 6 . i f ( r o t a t e = = = b u l l e t ) { i s D e a d = t r u e ; b r e a k ; } t i m e s = t i m e s + 1 ; } i s D e a d ; / / : N a h , i t ' s e i t h e r t r u e o r f a l s e , b u t I c a n ' t t e l l y o u .
  • 75. while w h i l e ( B O O L E A N _ E X P R E S S I O N ) { P R O G R A M _ B L O C K ; } Entry: When the program is about to enter the loop, it evaluates BOOLEAN_EXPRESSION. If it turns out to be 㫫㫩㫬㫜, the program goes into PROGRAM_BLOCK, or just skip.
  • 76. Loop: When PROGRAM_BLOCK is executed, it evaluates BOOLEAN_EXPRESSION again. If it turns out to be 㫫㫩㫬㫜, the program goes into PROGRAM_BLOCK again, or just skip. Termination: The loop terminates when BOOLEAN_EXPRESSION is evaluated as 㫝㫘㫣㫪㫜. 㫙㫩㫜㫘㫢, 㫚㫦㫥㫫㫠㫥㫬㫜: 㫙㫩㫜㫘㫢: jumps out of loop no matter what. 㫚㫦㫥㫫㫠㫥㫬㫜: go through the next iteration.
  • 77. while / / R u s s i a n r o u l e t t e p r o g r a m v a r b u l l e t = 3 ; v a r t i m e s = 1 ; v a r r o t a t e ; v a r i s D e a d = f a l s e ; w h i l e ( t i m e s ! = = 1 0 ) { r o t a t e = M a t h . f l o o r ( M a t h . r a n d o m ( ) * ( 1 + 6 - 1 ) ) + 1 ; / / F o r n o w , y o u o n l y n e e d t o k n o w R H S p r o d u c e s r a n d o m n u m b e r f r o m 1 t o 6 . i f ( r o t a t e = = = b u l l e t ) { i s D e a d = t r u e ; b r e a k ; } t i m e s = t i m e s + 1 ; } i s D e a d ; / / : N a h , i t ' s e i t h e r t r u e o r f a l s e , b u t I c a n ' t t e l l y o u .
  • 78. 㫫㫠㫤㫜㫪㫔㫕㫚㫚㫔㫠㫟: Boolean Expression. 㫙㫩㫜㫘㫢: jumps out of loop since you're dead already. 㫫㫠㫤㫜㫪㫔㫚㫔㫫㫠㫤㫜㫪㫔㫚㫔㫠: It guarantees that your program terminates at last. How many rounds the player has to play if he / she is lucky enough to stay alive?
  • 79. Exercises for while Refine Russian roulette program by introducing 㫧㫣㫘㫚㫜㫩 variable. 㫧㫣㫘㫚㫜㫩 can be either 㫠 or 㫡. The program shall show that it indicates a death duel (Program stops when either player 1 or player 2 winds up dead.)
  • 80. for Recall while loop in Russian roulette program: v a r t i m e s = 1 ; . . . w h i l e ( t i m e s ! = = 1 0 ) { . . . t i m e s = t i m e s + 1 ; } The pattern is so common that it leads to the birth of for: f o r ( v a r t i m e s = 1 ; t i m e s ! = = 1 0 ; t i m e s = t i m e s + 1 ) { . . . }
  • 81. for f o r ( I N I T I A L I S E R ; C O N D I T I O N ; I T E R A T O R ) { P R O G R A M _ B L O C K ; } can be expanded to: I N I T I A L I S E R ; w h i l e ( C O N D I T I O N ) { P R O G R A M _ B L O C K ; I T E R A T O R ; }
  • 82. for Recall prime test problem. v a r n = 8 8 4 9 ; v a r s q r t O f N = M a t h . s q r t ( n ) ; v a r i s P r i m e = t r u e ; f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) { i f ( n % i = = = 0 ) { i s P r i m e = f a l s e ; b r e a k ; } } i s P r i m e ; / / : t r u e
  • 83. Notice i starts from 2. n % 0 produces 㫗㫘㫗 Wait, you said we only need to check the primes ! However, checking all numbers includes checking those are prime. (weaker) ≤ x√
  • 84. Exercises for for Calculate the sum of 1 to 1000, using for. Explain why is superior.(1+n)n 2
  • 85. Exercises Collatz conjecture: for any natural number , if: is odd: verify is even: verify recursively, and ends up with 1. Using while, and for to verify Collatz conjecture holds for 1 - 10000; n > 1 n 3n + 1 n n 2 n reference
  • 87. Prime Test (again?) v a r n = 8 8 4 9 ; v a r s q r t O f N = M a t h . s q r t ( n ) ; v a r i s P r i m e = t r u e ; f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) { i f ( n % i = = = 0 ) { i s P r i m e = f a l s e ; b r e a k ; } } i s P r i m e ; / / : t r u e What if we want to check whether 15919 is a prime number?
  • 88. Easy, just copy & paste and change n: v a r n = 1 5 9 1 9 ; v a r s q r t O f N = M a t h . s q r t ( n ) ; v a r i s P r i m e = t r u e ; f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) { i f ( n % i = = = 0 ) { i s P r i m e = f a l s e ; b r e a k ; } } i s P r i m e ; / / : t r u e
  • 89. Okay, what about 15791 15797 15803 15809 15817 15823 15859 15877 15881 15887 15889 15901 15907 15913 15919 15923 15937 15959 15971 15973 15991 16001 16007 16033 16057 16061 16063 16067 16069 16073 .......
  • 90. As you can see, these codes is basically the same, except for n. We can refine the code by parameterisation and make it a subprogram.
  • 91. v a r i s P r i m e = f u n c t i o n ( n ) { v a r s q r t O f N = M a t h . s q r t ( n ) ; v a r i s P r i m e = t r u e ; f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) { i f ( n % i = = = 0 ) { i s P r i m e = f a l s e ; r e t u r n i s P r i m e ; } } r e t u r n i s P r i m e ; } ; / / : u n d e f i n e d i s P r i m e ( 1 5 9 0 7 ) ; / / : t r u e
  • 92. Here, we take n as the parameter of the function. It return values either true or false; Note you can totally discard isPrime by simply return true or false. Ugh, you got two isPrime, which ones you're talking about?
  • 93. Function Definition Function as subprogram Function as mapping from domain to range (mathematical definition) However, in JavaScript, the border of definitions become blurred. In JavaScript, function can be seen having two phases: 1. Definition: define the function body, assign it to a variable. 2. Invocation / Application: execute the function body by giving the parameters to function variable.
  • 94. How to define a function v a r F U N C T I O N _ N A M E ; F U N C T I O N _ N A M E = f u n c t i o n ( p 1 , p 2 , p 3 . . . . . ) { P R O G R A M _ B L O C K ; } ; The function body which takes p1, p2, p3... as parameters and executes PROGRAM_BLOCK, is assigned to FUNCTION_NAME. You might see the following as well, but it didn't give a sense of function as data. f u n c t i o n F U N C T I O N _ N A M E ( p 1 , p 2 , p 3 . . . . . . ) { P R O G R A M _ B L O C K ; }
  • 95. How to apply function F U N C T I O N _ N A M E ( p 1 , p 2 , p 3 . . . . . . ) ; / / : r e t u r n v a l u e o r u n d e f i n e d . Simply supply parameters to function.
  • 96. PROGRAM_BLOCK may contain 㫩㫜㫫㫬㫩㫥 keyword, which takes one value as the result of the function. If it's not given, function will return 㫬㫥㫛㫜㫝㫠㫥㫜㫛 instead. v a r s u m O f = f u n c t i o n ( n ) { v a r s u m = ( 1 + n ) * n / 2 ; r e t u r n s u m ; } ; / / : u n d e f i n e d ; s u m O f ( 1 0 0 0 ) ; / / : 5 0 0 5 0 0 v a r s u m O f 2 = f u n c t i o n ( n ) { v a r s u m = ( 1 + n ) * n / 2 ; } ; / / : u n d e f i n e d s u m O f 2 ( 1 0 0 0 ) ; / / : u n d e f i n e d
  • 97. When to define a function 1. You discover duplicate code and common pattern, and you need to abstract it. We've seen it before. 2. You discover the mathematical relation of input and output. v a r f i b o n a c c i = f u n c t i o n ( x ) { i f ( x = = = 1 | | x = = = 2 ) { r e t u r n 1 ; } e l s e i f ( x > 2 ) { r e t u r n f i b o n a c c i ( x - 1 ) + f i b o n a c c i ( x - 2 ) ; } } ; It just a plain translation from the definition of Fibonacci number.
  • 98. Parameter JavaScript functions do not check the number of arguments received. If you supply more arguments than those you define, the remaining will be omitted. If you supply less, the rest will be set as 㫬㫥㫛㫜㫝㫠㫥㫜㫛. v a r f n = f u n c t i o n ( a , b , c ) { r e t u r n a * b * c ; } ; f n ( 1 , 2 , 3 ) ; / / : 6 f n ( 1 , 2 ) ; / / : N a N ( a n y n u m b e r m u l t i p l i e s u n d e f i n e d e q u a l s t o N a N ) f n ( 1 , 2 , 3 , 7 , 9 ) ; / / : 6
  • 99. Default Values JavaScript doesn't support default values of parameters by default, but it can be addressed via: JavaScript evaluates boolean expression in the form of 㫫㫩㫬㫜㫔㫚㫚㫔㫗㫘㫥㫚㫫㫟㫠㫥㫞㫘. In this case, if 㫘 is 㫬㫥㫛㫜㫝㫠㫥㫜㫛, if evaluates as 㫢; v a r f n = f u n c t i o n ( a , b ) { a = a | | 3 ; b = b | | 7 ; r e t u r n a * b ; } ; f n ( ) ; / / : 2 1 f n ( 9 ) ; / / : 6 3
  • 100. Anonymous Function ( )λ Recall when we define a function, we define the function body first and assign it to a variable later. Instead of assigning it to a variable, the function body can be used directly, it's called 㫘㫥㫦㫥㫚㫤㫦㫬㫪㫔㫝㫬㫥㫚㫫㫠㫦㫥 in such context. For example, execute function right after the definition: ( f u n c t i o n ( a , b ) { r e t u r n a * b ; } ) ( 7 , 6 ) ; / / : 4 2
  • 101. Function as Data In JavaScript, you can pass function as data to other function, return function out of function. You can construct your logical components in the unit of functions, and junction them together. It's quite common pattern in JavaScript: using function as function callback.
  • 102. v a r r e p e a t = f u n c t i o n ( f , t i m e s ) { r e t u r n f u n c t i o n ( n ) { v a r v = n ; f o r ( v a r i = 0 ; i < t i m e s ; i = i + 1 ) { v = f ( v ) ; } r e t u r n v ; } ; } ; / / : u n d e f i n e d v a r s q u a r e = f u n c t i o n ( n ) { r e t u r n n * n ; } ; / / : u n d e f i n e d v a r q u a d = r e p e a t ( s q u a r e , 2 ) ; / / : u n d e f i n e d q u a d ( 3 ) ; / / : 8 1 We use square function to make a new function quad which is: quad(x) = square(square(x))
  • 103. Scope In JavaScript, when you invoke a function, you create a local scope. When you access a variable in a function, it first lookups the variables in the scope (parameters, local variables), if it didn't find a one, it lookups outside the functions. (Bubble up)
  • 104. v a r i s P r i m e = f u n c t i o n ( n ) { v a r s q r t O f N = M a t h . s q r t ( n ) ; v a r i s P r i m e = t r u e ; f o r ( v a r i = 2 ; i < s q r t O f N ; i = i + 1 ) { i f ( n % i = = = 0 ) { i s P r i m e = f a l s e ; r e t u r n i s P r i m e ; } } r e t u r n i s P r i m e ; } ; Due to the declaration of 㫠㫪㫙㫩㫠㫤㫜 in the function, all 㫠㫪㫙㫩㫠㫤㫜 occurs in the function act as a concrete variable different from the function name.
  • 105. Hosting Consider the program: 㫝㫥㫗㫘 will be 10? or 100? v a r x = 1 0 ; v a r f n = f u n c t i o n ( ) { r e t u r n x ; v a r x = 1 0 0 ; } ; f n ( ) ; / / : ?
  • 106. 㫬㫥㫛㫜㫝㫠㫥㫜㫛 actually, but why? The code actually looks like this: v a r x = 1 0 ; v a r f n = f u n c t i o n ( ) { v a r x ; / / x i s u n d e f i n e d t h e n . r e t u r n x ; x = 1 0 0 ; } ; f n ( ) ; / / : u n d e f i n e d
  • 107. When you invoke a function, the interpreter scans through your function body and define the variables you declare first (not assigned, yet.) and then it executes line by line. So, in reality, it's a good practice to define your variables at top, then your program logic.
  • 108. Closure v a r x = 1 0 ; v a r f n = f u n c t i o n ( n ) { r e t u r n n * x ; } ; f n ( 1 0 ) ; / / : 1 0 0 n ; / / : u n d e f i n e d x = 1 0 0 0 ; f n ( 1 0 ) ; / / : 1 0 0 0 0 Functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created. Since 㫝㫥 has access to REPL, 㫝㫥's behaviour is dependent on REPL. (if REPL will be modified later)
  • 109. By-Value vs By-Reference When we talk about variable as parameters of the function: By-value: the program will make a copy of variable and operate on the copy. By-Reference: the program will operate directly on the variable. In JavaScript, variables which have primitive type (boolean, number, string) goes by-value, and those with composite types (object, array..) go by-reference.
  • 110. By-Value: v a r f n = f u n c t i o n ( x ) { x = 1 0 0 0 ; r e t u r n x ; } ; / / : u n d e f i n e d v a r n = 1 0 ; / / : u n d e f i n e d f n ( n ) ; / / : 1 0 0 0 n ; / / : 1 0
  • 111. By-Reference: v a r f n = f u n c t i o n ( x ) { x . p u s h ( 0 ) ; r e t u r n x ; } ; / / : u n d e f i n e d v a r c = [ ] ; / / : u n d e f i n e d f n ( c ) ; / / : [ 0 ] c ; / / : [ 0 ]
  • 112. Exercises Recall abs program, choose proper parameters and make it a function. Design a function fn which gets off work: Write a function which takes a function f and produces another function which only works between 9 AM - 5 PM. Your code might work like this: v a r s q u a r e = f n ( f u n c t i o n ( e ) { r e t u r n e * e ; } ) ; s q u a r e ( 2 ) ; / / I t ' s 8 : 5 0 n o w / / : " I ' m o f f w o r k n o w , l e a v e m e a l o n e ! " s q u a r e ( 2 ) ; / / I t ' s 9 : 0 1 n o w / / : 4
  • 113. To do so, you need to know the current time: It's actually a quite common pattern in functional programming, to compose new functions by mixing them together. We'll introduce the concept of object later. v a r c u r r e n t D a t e = n e w D a t e ( ) ; v a r c u r r e n t H o u r = c u r r e n t D a t e . g e t H o u r s ( ) ; c u r r e n t H o u r ; / / : 0 ( i t v a r i e s )
  • 114. Array
  • 115. What does an array look like? v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; / / : u n d e f i n e d p r i m e s / / : [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; p r i m e s [ 3 ] ; / / : 7 p r i m e s [ 8 9 ] ; / / : u n d e f i n e d Index Value 0 2 1 3 2 5 ...
  • 116. Array Like list. Used to represent sequential data. Neither the length nor the types of an array are fixed. However, keep it the same type helps design / use algorithm. Access its value by a given index, where the index starts from 0. where 2 is the index, and 5 is the value. p r i m e s [ 2 ] ; / / : 5
  • 117. Construct Array Either by array literal or array.push method: v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; / / a r r a y l i t e r a l / / : u n d e f i n e d v a r p r i m e s = [ ] ; / / d e f i n e a e m p t y a r r a y / / : u n d e f i n e d p r i m e s . p u s h ( 2 ) ; / / : 1 p r i m e s . p u s h ( 3 ) ; / / : 2
  • 118. Add element to an array The index increases incrementally when new element is added. array.push method return the length of the new-added array. Some use 㫧㫩㫠㫤㫜㫪㫘㫧㫩㫠㫤㫜㫪㫝㫣㫜㫥㫞㫫㫟㫚㫔㫚㫔㫡㫢, which returns the value. p r i m e s . p u s h ( 2 3 ) ; / / : 9 p r i m e s [ 8 ] ; / / : 2 3
  • 119. Remove element from an array Either by array.pop or array.splice method: array.pop(): remove the last item and return it. array.splice(s, c, [items]): remove c items from s, added items if supplied. (return the deleted part.) v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; / / : u n d e f i n e d p r i m e s . p o p ( ) ; / / : 1 9 p r i m e s ; / / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 ] p r i m e s . s p l i c e ( 1 , 2 , 0 , 0 ) ; / / : A r r a y [ 3 , 5 ] p r i m e s ; / / : A r r a y [ 2 , 0 , 0 , 7 , 1 1 , 1 3 , 1 7 ] ;
  • 120. Lookup / Modify the array Remark: we can access the value by a given index: To change its value, simply assign: p r i m e s [ 3 ] ; / / : 7 p r i m e s [ 3 ] = 3 ; / / : 3 ; p r i m e s [ 3 ] ; / / : 3
  • 121. Some properties / methods on Array array.length: returns the length of the array. returns (the maximum index + 1) of the array Stick to array.push or arr[arr.length] v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; / / : u n d e f i n e d p r i m e s [ 8 8 4 9 ] = 9 1 5 2 9 ; / / : 9 1 5 2 9 p r i m e s . l e n g t h ; / / : 8 8 5 0 p r i m e s ; / / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 , < 2 e m p t y s l o t s > , 8 8 4 0 m o r e … ]
  • 122. Some properties / methods on Array array.slice(start, [end]): make a new array as sub-array from the original one start: the start position of the array for sub-array, could be negative (count backward from the end.) end: the end position of the array for sub-array, could be negative. Defaults to the length of array. Don't be confused with array.splice. v a r p r i m e s = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] ; / / : u n d e f i n e d p r i m e s . s l i c e ( 3 , 7 ) ; / / : A r r a y [ 7 , 1 1 , 1 3 , 1 7 ] p r i m e s ; / / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ]
  • 123. Sorting Consider the following program: By default, the array sorts according to each character's Unicode value, converted to String first if not. To make use of array.sort function, we need to supply a comparison function. [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] . s o r t ( ) ; / / : A r r a y [ 1 1 , 1 3 , 1 7 , 1 9 , 2 , 3 , 5 , 7 ]
  • 124. Sorting The comparison function is supplied as parameter of sort function. a and b denotes arbitrary items. The comparison function denotes the relations of two items by: [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] . s o r t ( f u n c t i o n ( a , b ) { r e t u r n ( a - b ) ; } ) ; / / : A r r a y [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] (a − b < 0) → (a < b) (a − b = 0) → (a = b) (a − b > 0) → (a > b)
  • 125. The sort method will swap if the return value is larger than 0. By default it sorts in ascending order. To sort in descending order, simply return 㫗㫙㫔㫜㫔㫘㫘 How the relations are represented in the above function? How you would write a comparison function to make it keep the array the same? (unsorted) [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 ] . s o r t ( f u n c t i o n ( a , b ) { r e t u r n ( b - a ) ; } ) ; / / : A r r a y [ 1 9 , 1 7 , 1 3 , 1 1 , 7 , 5 , 3 , 2 ]
  • 126. Exercises Selection Sort (ascending) For one unsorted array: [6, 9, 7, 2, 3] Compare the first element (6 in the case) with the rest by each, swap them if the first is larger than any in the rest. In the case, 6 will be swapped with 2. Since we knew , and those compared with 6 , we knew those compared with 6 (Transitive relation) 6 > 2 > 6 > 2
  • 127. Selection Sort (ascending) After one iteration, the first one is the smallest in the array. ([2, 9, 7, 6, 3]) Start again from the second element (9 in the case), and the third..., to the end of the array. See visualisation
  • 128. Selection Sort with Comparison Function Refine your sorting algorithm with one function parameter, known as comparison function, which is the same as array.sort
  • 129. Object
  • 130. Object An object is a collection of properties. Properties could be: Primitive types: Number, String, Boolean Composite types: Object Object could be: Function, Array Function in object is called method.
  • 131. Whey do we need object, after all?
  • 132. To define a square in Cartesian coordinates system, we have two different ways: Records four points such as (0, 0), (4, 0), (0, 4), (4, 4) Records the center point (2, 2) and the length of its sides (4) Diagonal is always larger than the side. Two representaions of a square
  • 133. To calculate the area of the square, using the definition 1: v a r p 1 x = 0 ; v a r p 1 y = 0 ; v a r p 2 x = 4 ; v a r p 2 y = 0 ; v a r p 3 x = 0 ; v a r p 3 y = 4 ; v a r p 4 x = 4 ; v a r p 4 y = 4 ; v a r d i s t a n c e = f u n c t i o n ( p 1 x , p 1 y , p 2 x , p 2 y ) { r e t u r n M a t h . s q r t ( M a t h . p o w ( p 1 x - p 2 x , 2 ) + M a t h . p o w ( p 1 y - p 2 y , 2 ) ) ; } ; v a r s q u a r e A r e a = f u n c t i o n ( p 1 x , p 1 y , p 2 x , p 2 y , p 3 x , p 3 y , p 4 x , p 4 y ) { v a r d 1 = d i s t a n c e ( p 1 x , p 1 y , p 2 x , p 2 y ) ; v a r d 2 = d i s t a n c e ( p 1 x , p 1 y , p 3 x , p 3 y ) ; v a r l e n g t h = ( d 1 < = d 2 ) ? d 1 : d 2 ; / / ( d 1 , d 2 m i g h t b e o n l y d i a g o n a l / s i d e r e t u r n l e n g t h * l e n g t h ; } ; s q u a r e A r e a ( p 1 x , p 1 y , p 2 x , p 2 y , p 3 x , p 3 y , p 4 x , p 4 y ) ;
  • 134. One day, your lead programmer came and says: "Hey, let's do that in def 2!" The code is prettier, but every occurrence of old 㫪㫨㫬㫘㫩㫜㫖㫩㫜㫘 need to be modified, along with the coordinates of squares. v a r c 1 x = 2 ; v a r c 2 y = 2 ; v a r s i d e = 4 ; v a r s q u a r e A r e a = f u n c t i o n ( s i d e ) { r e t u r n s i d e * s i d e ; } ;
  • 135. Imagine Find / Replace for few hundred times...
  • 136. Let's make a object of it! In fact, what we REALLY care about is the square, not its coordinates / sides. We want to know the area of the square, right? if we have something like: Let's refine our code then. Wouldn't it be nice v a r s q u a r e A r e a = f u n c t i o n ( s q u a r e ) { . . . . . . } ; s q u a r e A r e a ( s q u a r e ) ; / / : 1 6
  • 137. v a r s q u a r e = { p 1 : { x : 0 , y : 0 } , p 2 : { x : 4 , y : 0 } , p 3 : { x : 0 , y : 4 } , p 4 : { x : 4 , y : 4 } } ;
  • 138. (Cont'd) v a r d i s t a n c e = f u n c t i o n ( p 1 , p 2 ) { r e t u r n M a t h . s q r t ( M a t h . p o w ( p 1 . x - p 2 . x , 2 ) + M a t h . p o w ( p 1 . y - p 2 . y } ; v a r s q u a r e A r e a = f u n c t i o n ( s ) { v a r d 1 = d i s t a n c e ( s . p 1 , s . p 2 ) ; v a r d 2 = d i s t a n c e ( s . p 1 , s . p 3 ) ; v a r l e n g t h = ( d 1 < = d 2 ) ? d 1 : d 2 ; r e t u r n l e n g t h * l e n g t h ; } ; s q u a r e A r e a ( s q u a r e ) ; / / : 1 6
  • 139. Create Object We create object by object literal: object literal: {key: value, [key: value...]} Key is unique. we created a nested object. (since the value of 㫧㫠 is a object and etc.) You can create new property on the fly: v a r o b j = { a : 0 } ; o b j . b = 1 ; o b j ; / / : O b j e c t { a : 0 , b : 1 }
  • 140. Access object We access the value of properties by pointing to their keys, such as: Note: you can access properties in the form of square['p1'], too. (useful when you need to determine key on runtime.) s q u a r e . p 1 . x ; / / : 0 , w h i c h i s e q u a l s t o : v a r p 1 = s q u a r e . p 1 ; p 1 . x ; / / : 0
  • 141. Let's rewrite in Def. 2 Notice the parameters of squareArea is the same as the previous one. v a r s q u a r e = { c 1 : { x : 2 , y : 2 } , s i d e : 4 } ; v a r s q u a r e A r e a = f u n c t i o n ( s ) { r e t u r n s . s i d e * s . s i d e ; } ; s q u a r e A r e a ( s q u a r e ) ; / / : 1 6
  • 142. Methods When you put function into the object: 㫫㫟㫠㫪 is a reference to the object itself. array.sort and such are all object methods. v a r s q u a r e = { c 1 : { x : 2 , y : 2 } , s i d e : 4 , g e t A r e a : f u n c t i o n ( ) { r e t u r n t h i s . s i d e * t h i s . s i d e ; } } ; s q u a r e . g e t A r e a ( ) ; / / : 1 6
  • 143. 㫫㫟㫠㫪 㫫㫟㫠㫪 depends on the current context where function is invoked: Since when the function is invoked, the current scope refers to the function body itself and outer (recall closure), and there is no 㫪㫠㫛㫜 defined. / / N o t i c e w e a s s i g n t h e f u n c t i o n b o d y i n s t e a d o f c a l l i n g i t . v a r a r e a = s q u a r e . g e t A r e a ; a r e a ( ) ; / / : N a N
  • 144. Function vs. Method We put function in a object (method) when it's dependent of the object. A good indicator is the use of 㫫㫟㫠㫪. Of course, it might arise political wars. : ) (Critical thinking, and only the paranoid survive!)
  • 145. Create object based on the existing one. The object is by-reference, so the following don't copy new object. (They refers to the same object.) v a r o b j = { f o o : ' b a r ' } ; v a r n e w O b j = o b j ; n e w O b j . b a z = ' q u x ' ; o b j . b a z ; / / : ' q u x '
  • 146. To construct a new object, we can use: Object.create (ECMAScript 5) 㫥㫜㫮 Keyword function returning new object We sticks to the first for now.
  • 147. v a r o b j = { f o o : m s g , b a z : ' q u x ' } ; v a r o b j 1 = O b j e c t . c r e a t e ( o b j ) ; v a r o b j 2 = O b j e c t . c r e a t e ( o b j ) ; o b j 1 . b a z = ' L a l a l a ' ; o b j 2 . b a z ; / / : ' q u x '
  • 148. Construct Playlist Given the following playlist: Can you choose proper data structure for it? T r a c k N a m e A r t i s t D u r a t i o n ( s ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - G o d O n l y K n o w s T h e B e a c h B o y s 1 7 1 P i a n o M a n B i l l y J o e l 3 3 8 N e w Y o r k , N e w Y o r k F r a n k S i n a t r a 2 0 6 M y W a y F r a n k S i n a t r a 2 7 6 N e w Y o r k , N e w Y o r k C a t P o w e r 1 2 0 D o w n t o w n T r a i n E v e r y t h i n g b u t t h e G i r l 1 8 4 I ' m G o n n a B e ( 5 0 0 M i l e s ) T h e P r o c l a i m e r s 2 1 7 L a V i e E n R o s e C r i s t i n M i l i o t i 1 1 5
  • 149. Since it's a playlist, an array is a reasonable choice. How can we represent one song? Maybe using array: v a r s o n g = [ ' G o d O n l y K n o w s ' , ' T h e B e a c h B o y s ' , 1 7 1 ] ; and access the property by 㫪㫦㫥㫞㫘㫟㫚.... Nah, it sucks. We cannot determine the relation between properties and index directly!
  • 150. Using object: And we can puts it in an array: v a r s o n g = { t i t l e : ' G o d O n l y K n o w s ' , a r t i s t : ' T h e B e a c h B o y s ' , d u r a t i o n : 1 7 1 } ; v a r p l a y l i s t = [ { t i t l e : ' G o d O n l y K n o w s ' , a r t i s t : ' T h e B e a c h B o y s ' , d u r a t i o n . . . . . . ] ;
  • 151. Exercises We can answer questions like: What songs is performed by Frank Sinatra? Going through the list and find those performed by him. Can you sort the playlist by its duration? Recall array.sort method? List all artists who perform New York, New York Going through the list and find those performed the song. How many object exist in the code? 8? Are you sure...
  • 152. Inheritance JavaScript uses prototype-based inheritance, by referring to existing object to extends its behaviours. Each object may has a prototype reference, which points to the object they want to inherit.
  • 153. when you access properties, it searches from itself, then its prototype object. If the object is found and property exists, then it stops. If not, it searches from its prototype object again.... recursively, to 㫘㫙㫡㫜㫚㫫 or failed when it cannot find prototype object. v a r a = { f o o : ' b a r ' } ; v a r b = O b j e c t . c r e a t e ( a ) ; a . i s P r o t o t y p e O f ( b ) ; / / : t r u e O b j e c t . g e t P r o t o t y p e O f ( b ) = = = a ; / / : t r u e , i t r e f e r s t o t h e s a m e m e m o r y l o c a t i o n . b . f o o ; / / : " b a r " b . f o o = ' b a z ' ; b . f o o ; / / : " b a z " , s i n c e b h a s i t s o w n f o o p r o p e r t y n o w , ( w h a t a b o u t a . f o o ? )
  • 154. So, instead of class-based, prototype-based much more like: To see more .about prototype
  • 155. Primitive types: object or not? Recall the definition of object: An object is a collection of properties. str.toUpperCase is a function, and it got a property called toUpperCase, so it's a object!?
  • 156. str.toUpperCase is actually: If you use typeof to check it's type. Warning: typeof could be very deceiving, and typeof is a operator, not a function. ' I t ' s o v e r n o w , t h e m u s i c o f t h e n i g h t ! ' . t o U p p e r C a s e ( ) ; / / : " I T ' S O V E R N O W , T H E M U S I C O F T H E N I G H T ! " / / T h i s i s a c t u a l l y d o n e v i a a w r a p p e r o b j e c t : v a r s t r = n e w S t r i n g ( ' I t ' s o v e r n o w , t h e m u s i c o f t h e n i g h t ! ' ) ; s t r . t o U p p e r C a s e ( ) ; / / : " I T ' S O V E R N O W , T H E M U S I C O F T H E N I G H T ! " t y p e o f s t r ; / / : " o b j e c t " t y p e o f ' I t ' s o v e r n o w , t h e m u s i c o f t h e n i g h t ! ' ; / / : " s t r i n g "
  • 157. Exercises After the accident of Opéra de Paris, the Phantom was on the run. He had an income of 22K and he needed to pay 15K to keep himself alive. Design an phantom object which helps him calculate how much he still had. Design an object representing your mobile, and explain your design.