SlideShare una empresa de Scribd logo
1 de 73
Front-end Fundamentals
      Session 1:
   Javascript Core
       Zhao Wenbo
As far as the customer is
concerned, the interface
     is the product.
Richness of
User Experience
What's Javascript
•   Cross-platform
•   Object-oriented
•   Scripting language
•   Interpreted language
•   Standardized by ECMA-262
•   Created in 1995 by Brendan Eich
•   First named LiveScript then Javascript
Hello World Example
​<?doctype html>
 <html>
   <head>
     <title>Hello World Example</title>
   </head>
   <body>
     <script type="text/javascript">
       alert('Hello World');
     </script>
   </body>
 </html>​​

View Demo
Hello World Example 2
​<?doctype html>
 <html>
   <head>
     <title>Hello World Example</title>
   </head>
   <body>
     <script type="text/javascript">
       console.log('Hello World');
     </script>
   </body>
 </html>
​
View Demo
Syntax
•   Javascript syntax comes from Java and C.
•   Javascript is case-sensitive.
•   Statement ends with semicolon;
•   Comment starts with //
•   Multiple line comments embraced with /* */
•   Assign value with =
    ...
Control structures
•   Compound statements , … -
•   if ( … ) else , … -
•   result = condition ? expression : alternative;
•   switch ( … ) , … -
•   for ( … ) , … -
•   while ( … ) , … -
•   do , … - while ( … )
•   try , … - catch (e) , … -
Basic data types
•   Number
•   Boolean
•   String
•   null
•   undefined
•   Object
    – Array
    – Function

    View Demo
Numbers
Numbers literal
•   var x = 5;
•   var y = 3.1415;
•   var z = 0xFF;
•   x = -15e9;
•   x = new Number(5);
Arithmetic
•   var x = 2;
•   var y = 5;
•   x+y x-y x*y x/y x%y
•   x++ y--
•   x += 8     y *= 10

View Demo
Advanced mathematical
              functions
• Math
  –   PI
  –   E
  –   sin()
  –   floor()
  –   ceil()
  –   random()
  –   abs()

View Demo
Special Numbers
• Infinity
   – 1/0 == Infinity
   – -1/0 == -Infinity
   – isFinite(1/0)
• NaN
   – console.log(13 / 'Yahoo!' )
   – 13 / 'Yahoo!' == NaN ?
   – isNaN(12 * 'mobile')

   View Demo
Parse number from string
• parseInt()
  – parseInt('320px')
  – parseInt(7.9)
  – parseInt('FF')
  – parseInt('FF', 16)
• parseFloat()
  – parseFloat('3.2million')

  View Demo
Formatting output of numbers
• toString()
  – convert a number to string
  – (8).toString(2)
• toFixed()
  – (15365).toFixed(3)
  – Math.PI.toFixed(2)

  View Demo
String
String literal
• var s1 = "this is a string";
• var s2 = '<img src="logo.png" />';
• var s3 = new String("Yahoo!");
Most used operations
• Use + to concatenate strings
  – var s = "hello" + "world";
  – s += 'mobile search';
  – s = s.concat("abc");
• Get string length
  – "yahoo".length //5
• Get character in specific position
  – "abcd"[2] //c
  – "abcd".charAt(2) //c
Search a substring
• indexOf() / lastIndexOf()
  – "This is a test".indexOf('is') //2
  – "This is a test".lastIndexOf('is') //5
  – "This is a test".indexOf('abc') //-1
Get substring
• substr(start [, length])
   – "mobile search".substr(7, 3) //sea
   – "mobile search".substr(7) //search
   – "mobile search".substr(-3, 3) //rch
• substring(index1 [, index2])
   – "mobile search".substring(0, 3) //mob
   – "mobile search".substring(3, 0) //mob
   – "mobile search".substring(-3, 0) //empty string
• slice(index1 [, index2])
   – same as substring except negative index is valid
Boolean
Boolean
• true
• false
• new Boolean(true)
null &
undefined
differences between null &
           undefined
• null
  – a special object
  – empty value
• undefined
  – a variable or property that hasn't been assigned

  View Demo
Audo data type conversion
• Auto data type conversion is performed when
  the data type is unexpected.
  – "the answer is " + 42
  – "42" * 2
Conversion to string
Type        Result

undefined   "undefined"

null        "null"

Boolean     "true" or "false"

Number      "NaN", "Infinity", "153.23", "2.8e10", "-5"

Object      Call toString method of the object


View Demo
Conversion to number
Type        Result
undefined   NaN
null        0
            true to 1;
Boolean
            false to 0;
            "Infinity" to Infinity;
String      "1.56" to 1.56;
            Other strings to NaN;
Object      NaN

View Demo
Conversion to bool
Type        Result

undefined   false

null        false

String      empty string to false; other to true

Number      0 and NaN to false; other to true

Object      true


View Demo
== and ===
•   undefined == null ?
•   {a:1} == {a:1} ?
•   "5" == 5 ?
•   "0" == false
•   new String("yahoo") == "yahoo" ?
•   new String("y") == new String("y") ?

View Demo
typeof
• get data type of variable
  – typeof null
  – typeof undefined
  – typeof 1
  – typeof []
  – typeof Math.random
  – type of {}

  View Demo
Array
Array literal
• var a = ["dog", "cat", "hen"];
• var b = new Array("dog", "cat");
  – b[2] = "hen";
  – b[3] = 1.4;
  – b[4] = [1, 2, 3];
length property
• var a = [1, 2, 3];
   – a.length == 3
• a[100] = 5;
   – a.length == ?
• a.length = 0;

   View Demo
Array iteration
• for (var i = 0; i < a.length; i++) { ... a[i] ... }
• for (var i = 0, j = a.length; i < j; i++) { ... a[i] ... }
• for (var i in a) { ... a[i] ... }

View Demo
push & pop
• push()
  – append element to the end
  – return array length
• pop()
  – remove last element
  – return removed element

  View Demo
shift & unshift
• shift()
   – remove first element
   – return removed element
• unshift
   – insert element to the beginning
   – return array length

   View Demo
join & split
• array.join()
   – [1, 2, 3].join("|") -> "1|2|3"
   – [1, 2, 3].join() -> "1,2,3"
• string.split
   – "a b c".split(" ") -> ["a", "b", "c"]
   – "yahoo".split() -> ["yahoo"]
concat
• concat()
  – var a = [1, 2, 3];
  – a.concat([4, 5]); //[1, 2, 3, 4, 5]
  – a.concat([6, 7], 8, 9)
slice & splice
• slice(index1, index2)
  – get a sub-array
• splice(index, count, add1, add2 ...)
  – perform surgery on array
  – replace some elements with new elements

  View Demo
reorder array
• sort()
• reverse()
Object
Object literal
•   create empty object
•   var a = new Object();
•   var a = { };
•   object with properties
    var a = {
      "age": 20,
      "name": "Jerry"
    }
get & set property
• var a = {};
• set property
  – a['name'] = 'Jerry';
  – a.age = 20;
• get property
  – "He is " + a.name
  – "He is " + a['age'] + " years old"

  View Demo
prototype
• every object is linked to a prototype object
  from which it can inherit properties
• all objects created from object literal are
  linked to Object.prototype.
• all arrays are linked to Array.prototype

View Demo
object itration
• Use for ... in
• loop all properties of the object, including that
  extends from prototype
• how to get properties excluding inherited
  from prototype?

View Demo
constructor
• a reference to the function who create the
  object
• var o = {}; var b = false;
  – o.constructor === Object
  – b.constructor === Boolean

  View Demo
Function
function literal
function f(x, y) {
       return x + y;
}
var f = function(x, y) {
       return x - y;
}
var f = new Function("x", "y", "return x * y");

View Demo
arguments
• In a function, object "arguments" means
  parameters passed to the function

View Demo
this
• in function, "this" is the object who call the
  function

View Demo
function as Class
function Person(name, age) {
      this.name = name;
      this.age = age;
}
var p = new Person("Adam", 20);

create a new Object, point "this" to that object.

View Demo
call & apply
• f.call(thisObj, arg1, arg2, …)
   – call function f with parameters arg1, arg2 …
   – this point to thisObj
• f.apply(thisObj, *arg1, arg2, …+)
   – same as call
   – different ways to pass arguments

   View Demo
bind
• bind a function and an object using the "bind"
  method of the function

View Demo
variable scope
• NO block scope
• has function scope
  – variable defined in a function is not visible outside
    the function
  – variable defined in a function is visible ANYWHERE
    within the function

  View Demo
anonymous function
• (function (){ ... })();

View Demo
passing by reference/value
• primitive variables pass by value
  – null, undefined, number, bool, string
• objects pass by reference
  – object, array, function


View Demo
first class function
•   can be stored in variable and data structures
•   can be passed as parameter
•   can be returned as result
•   can be constructed at run-time
•   has intrinsic identity
function is object
• function can be refered by a variable
• function has properties
• you can set property for a function

View Demo
function as parameter
• function can be passed as parameter
• a function as parameter is called "callback"

• View Demo 1
• View Demo 2
function as return value
• function can be returned
• function returned still have access to variables
  of the function it's defined within
• function together with a referencing
  environment for non-local variables is called
  "Closure"

View Demo
module pattern
• hide private members
• expose pubic methods

View Demo
inheritance in Javascript
• prototypal inheritance
• pseudo-classical inheritance
Date
Date & time
•   new Date()
•   new Date("December 22, 2012 03:24:00")
•   new Date(2012, 12, 22)
•   new Date(2012, 12 ,22 ,3 , 24, 0)

View Demo
Regular Expression
Regular expression literal
• var r = /abd+/ig
• var r = new RegExp("abd+", "img")
RegExp functions
•   regexp.exec(str)
•   regexp.test(str)
•   string.match(regexp)
•   string.search(regexp)
•   string.replace(regexp, replacement)
•   string.split(regexp)

Further reading
Further reading
• Learning advanced Javascript
• Mozilla developer network – Javascript
Books
CC images used
•   http://www.flickr.com/photos/bright/106000370/
•   http://www.flickr.com/photos/oskay/472097903/
•   http://www.flickr.com/photos/ashleyrosex/2450534945/
•   http://www.flickr.com/photos/wolfnowl/6187621227/
•   http://www.flickr.com/photos/chberge/4122421509/
•   http://www.flickr.com/photos/greenmambagreenmamba/183
    2165324
•   http://www.flickr.com/photos/20792787@N00/53071820/
•   http://www.flickr.com/photos/snapsi42/3385220387
•   http://www.flickr.com/photos/amandarudkin/321429630
•   http://www.flickr.com/photos/teddy-rised/3998772594/

Más contenido relacionado

La actualidad más candente

Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testingScott Wlaschin
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeManoj Kumar
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8Christian Nagel
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOJorge Vásquez
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaznkpart
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 

La actualidad más candente (20)

Java generics
Java genericsJava generics
Java generics
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Core C#
Core C#Core C#
Core C#
 
An introduction to property based testing
An introduction to property based testingAn introduction to property based testing
An introduction to property based testing
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Deriving Scalaz
Deriving ScalazDeriving Scalaz
Deriving Scalaz
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
ppopoff
ppopoffppopoff
ppopoff
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 

Similar a Front end fundamentals session 1: javascript core

Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovyIsuru Samaraweera
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 

Similar a Front end fundamentals session 1: javascript core (20)

Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Javascript
JavascriptJavascript
Javascript
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
 
Js
JsJs
Js
 
Command Liner with Scala
Command Liner with ScalaCommand Liner with Scala
Command Liner with Scala
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 

Último

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Front end fundamentals session 1: javascript core

  • 1. Front-end Fundamentals Session 1: Javascript Core Zhao Wenbo
  • 2. As far as the customer is concerned, the interface is the product.
  • 4.
  • 5. What's Javascript • Cross-platform • Object-oriented • Scripting language • Interpreted language • Standardized by ECMA-262 • Created in 1995 by Brendan Eich • First named LiveScript then Javascript
  • 6.
  • 7. Hello World Example ​<?doctype html> <html> <head> <title>Hello World Example</title> </head> <body> <script type="text/javascript"> alert('Hello World'); </script> </body> </html>​​ View Demo
  • 8. Hello World Example 2 ​<?doctype html> <html> <head> <title>Hello World Example</title> </head> <body> <script type="text/javascript"> console.log('Hello World'); </script> </body> </html> ​ View Demo
  • 9. Syntax • Javascript syntax comes from Java and C. • Javascript is case-sensitive. • Statement ends with semicolon; • Comment starts with // • Multiple line comments embraced with /* */ • Assign value with = ...
  • 10. Control structures • Compound statements , … - • if ( … ) else , … - • result = condition ? expression : alternative; • switch ( … ) , … - • for ( … ) , … - • while ( … ) , … - • do , … - while ( … ) • try , … - catch (e) , … -
  • 11. Basic data types • Number • Boolean • String • null • undefined • Object – Array – Function View Demo
  • 13. Numbers literal • var x = 5; • var y = 3.1415; • var z = 0xFF; • x = -15e9; • x = new Number(5);
  • 14. Arithmetic • var x = 2; • var y = 5; • x+y x-y x*y x/y x%y • x++ y-- • x += 8 y *= 10 View Demo
  • 15. Advanced mathematical functions • Math – PI – E – sin() – floor() – ceil() – random() – abs() View Demo
  • 16. Special Numbers • Infinity – 1/0 == Infinity – -1/0 == -Infinity – isFinite(1/0) • NaN – console.log(13 / 'Yahoo!' ) – 13 / 'Yahoo!' == NaN ? – isNaN(12 * 'mobile') View Demo
  • 17. Parse number from string • parseInt() – parseInt('320px') – parseInt(7.9) – parseInt('FF') – parseInt('FF', 16) • parseFloat() – parseFloat('3.2million') View Demo
  • 18. Formatting output of numbers • toString() – convert a number to string – (8).toString(2) • toFixed() – (15365).toFixed(3) – Math.PI.toFixed(2) View Demo
  • 20. String literal • var s1 = "this is a string"; • var s2 = '<img src="logo.png" />'; • var s3 = new String("Yahoo!");
  • 21. Most used operations • Use + to concatenate strings – var s = "hello" + "world"; – s += 'mobile search'; – s = s.concat("abc"); • Get string length – "yahoo".length //5 • Get character in specific position – "abcd"[2] //c – "abcd".charAt(2) //c
  • 22. Search a substring • indexOf() / lastIndexOf() – "This is a test".indexOf('is') //2 – "This is a test".lastIndexOf('is') //5 – "This is a test".indexOf('abc') //-1
  • 23. Get substring • substr(start [, length]) – "mobile search".substr(7, 3) //sea – "mobile search".substr(7) //search – "mobile search".substr(-3, 3) //rch • substring(index1 [, index2]) – "mobile search".substring(0, 3) //mob – "mobile search".substring(3, 0) //mob – "mobile search".substring(-3, 0) //empty string • slice(index1 [, index2]) – same as substring except negative index is valid
  • 25. Boolean • true • false • new Boolean(true)
  • 27. differences between null & undefined • null – a special object – empty value • undefined – a variable or property that hasn't been assigned View Demo
  • 28. Audo data type conversion • Auto data type conversion is performed when the data type is unexpected. – "the answer is " + 42 – "42" * 2
  • 29. Conversion to string Type Result undefined "undefined" null "null" Boolean "true" or "false" Number "NaN", "Infinity", "153.23", "2.8e10", "-5" Object Call toString method of the object View Demo
  • 30. Conversion to number Type Result undefined NaN null 0 true to 1; Boolean false to 0; "Infinity" to Infinity; String "1.56" to 1.56; Other strings to NaN; Object NaN View Demo
  • 31. Conversion to bool Type Result undefined false null false String empty string to false; other to true Number 0 and NaN to false; other to true Object true View Demo
  • 32. == and === • undefined == null ? • {a:1} == {a:1} ? • "5" == 5 ? • "0" == false • new String("yahoo") == "yahoo" ? • new String("y") == new String("y") ? View Demo
  • 33. typeof • get data type of variable – typeof null – typeof undefined – typeof 1 – typeof [] – typeof Math.random – type of {} View Demo
  • 34. Array
  • 35. Array literal • var a = ["dog", "cat", "hen"]; • var b = new Array("dog", "cat"); – b[2] = "hen"; – b[3] = 1.4; – b[4] = [1, 2, 3];
  • 36. length property • var a = [1, 2, 3]; – a.length == 3 • a[100] = 5; – a.length == ? • a.length = 0; View Demo
  • 37. Array iteration • for (var i = 0; i < a.length; i++) { ... a[i] ... } • for (var i = 0, j = a.length; i < j; i++) { ... a[i] ... } • for (var i in a) { ... a[i] ... } View Demo
  • 38. push & pop • push() – append element to the end – return array length • pop() – remove last element – return removed element View Demo
  • 39. shift & unshift • shift() – remove first element – return removed element • unshift – insert element to the beginning – return array length View Demo
  • 40. join & split • array.join() – [1, 2, 3].join("|") -> "1|2|3" – [1, 2, 3].join() -> "1,2,3" • string.split – "a b c".split(" ") -> ["a", "b", "c"] – "yahoo".split() -> ["yahoo"]
  • 41. concat • concat() – var a = [1, 2, 3]; – a.concat([4, 5]); //[1, 2, 3, 4, 5] – a.concat([6, 7], 8, 9)
  • 42. slice & splice • slice(index1, index2) – get a sub-array • splice(index, count, add1, add2 ...) – perform surgery on array – replace some elements with new elements View Demo
  • 45. Object literal • create empty object • var a = new Object(); • var a = { }; • object with properties var a = { "age": 20, "name": "Jerry" }
  • 46. get & set property • var a = {}; • set property – a['name'] = 'Jerry'; – a.age = 20; • get property – "He is " + a.name – "He is " + a['age'] + " years old" View Demo
  • 47. prototype • every object is linked to a prototype object from which it can inherit properties • all objects created from object literal are linked to Object.prototype. • all arrays are linked to Array.prototype View Demo
  • 48. object itration • Use for ... in • loop all properties of the object, including that extends from prototype • how to get properties excluding inherited from prototype? View Demo
  • 49. constructor • a reference to the function who create the object • var o = {}; var b = false; – o.constructor === Object – b.constructor === Boolean View Demo
  • 51. function literal function f(x, y) { return x + y; } var f = function(x, y) { return x - y; } var f = new Function("x", "y", "return x * y"); View Demo
  • 52. arguments • In a function, object "arguments" means parameters passed to the function View Demo
  • 53. this • in function, "this" is the object who call the function View Demo
  • 54. function as Class function Person(name, age) { this.name = name; this.age = age; } var p = new Person("Adam", 20); create a new Object, point "this" to that object. View Demo
  • 55. call & apply • f.call(thisObj, arg1, arg2, …) – call function f with parameters arg1, arg2 … – this point to thisObj • f.apply(thisObj, *arg1, arg2, …+) – same as call – different ways to pass arguments View Demo
  • 56. bind • bind a function and an object using the "bind" method of the function View Demo
  • 57. variable scope • NO block scope • has function scope – variable defined in a function is not visible outside the function – variable defined in a function is visible ANYWHERE within the function View Demo
  • 58. anonymous function • (function (){ ... })(); View Demo
  • 59. passing by reference/value • primitive variables pass by value – null, undefined, number, bool, string • objects pass by reference – object, array, function View Demo
  • 60. first class function • can be stored in variable and data structures • can be passed as parameter • can be returned as result • can be constructed at run-time • has intrinsic identity
  • 61. function is object • function can be refered by a variable • function has properties • you can set property for a function View Demo
  • 62. function as parameter • function can be passed as parameter • a function as parameter is called "callback" • View Demo 1 • View Demo 2
  • 63. function as return value • function can be returned • function returned still have access to variables of the function it's defined within • function together with a referencing environment for non-local variables is called "Closure" View Demo
  • 64. module pattern • hide private members • expose pubic methods View Demo
  • 65. inheritance in Javascript • prototypal inheritance • pseudo-classical inheritance
  • 66. Date
  • 67. Date & time • new Date() • new Date("December 22, 2012 03:24:00") • new Date(2012, 12, 22) • new Date(2012, 12 ,22 ,3 , 24, 0) View Demo
  • 69. Regular expression literal • var r = /abd+/ig • var r = new RegExp("abd+", "img")
  • 70. RegExp functions • regexp.exec(str) • regexp.test(str) • string.match(regexp) • string.search(regexp) • string.replace(regexp, replacement) • string.split(regexp) Further reading
  • 71. Further reading • Learning advanced Javascript • Mozilla developer network – Javascript
  • 72. Books
  • 73. CC images used • http://www.flickr.com/photos/bright/106000370/ • http://www.flickr.com/photos/oskay/472097903/ • http://www.flickr.com/photos/ashleyrosex/2450534945/ • http://www.flickr.com/photos/wolfnowl/6187621227/ • http://www.flickr.com/photos/chberge/4122421509/ • http://www.flickr.com/photos/greenmambagreenmamba/183 2165324 • http://www.flickr.com/photos/20792787@N00/53071820/ • http://www.flickr.com/photos/snapsi42/3385220387 • http://www.flickr.com/photos/amandarudkin/321429630 • http://www.flickr.com/photos/teddy-rised/3998772594/