SlideShare a Scribd company logo
1 of 79
JavaScript 200
Intermediate JavaScript
by Milan Adamovsky
http://milan.adamovsky.com ◆ http://www.hardcorejs.com
Prerequisites
• Fundamentals of language
• Familiarity with syntax
• Distinction between DOM and JS
• Awareness of prototype and scope
• Basic understanding of this
Goals
• Progressive complexity
• Eye on performance
• Familiarity with subtleties
• Explanation of some of the internals
• Awareness of new ways of doing things
Roadmap
• How to better control our code’s flow
• How the code handles information
• How information is resolved
• How to practically apply advanced features
• Introduction to more advanced topics
Data Structures
Refresher Quiz
• What is an identifier?
• What are valid characters in identifiers?
• What type system does the language use?
• What are the primitives?
• What primitives are mutable?
Immutability
• Most primitives are immutable
• Type undefined is erroneously mutable
• Objects are mutable
• Literals are immutable
• Some array methods mutate, some don’t
Hoisting
• Identifier is known to scope before value
• Function names hoist after variables
• Value of variables never hoist
• Declaration of functions always hoist
• Reflect hoisting in coding style
Example
function myFunction()
{
if (!x)
console.log('undefined')
else
console.log('x : ', x);
var x = "";
function x()
{
console.log('inside x function');
}
}
myFunction();

x : function x()
{
console.log('inside x function');
}
Performance
• Primitives are best
• Arrays are second best
• Objects are worst
• Keep nesting to a minimum
• Indexes better alternatives to nesting
Example
var family = {
father : {
first : 'joe',
last : 'doe'
},
mother : {
first : 'jane',
last : 'doe'
}
};
var father = {
first : 'joe',
last : 'doe'
},
mother = {
first : 'jane',
last : 'doe'
};
Benchmark
• http://jsperf.com/registry-design
• Strategic approach to data structures
• Different approach, different performance
• Shows nested objects are worst
• Suggests multiple objects best
Reminders
• Use typeof to determine type of variable
• Use instanceOf to determine class type
• Types via typeof are returned as strings
• Type of null is ‘object’
• Type of NaN is ‘number’
Conditionals
Refresher Quiz
• What is logic flow?
• What different ways can we control it?
• What is a comparison operator?
• What is the triple equal operator?
• What does every condition resolve for?
Logic Flow
• if, if...else, if...else if...else
• Ternary operator (?:)
• Logical operators (||, &&, !)
• Switch statement
• Loops
Effective Conditions
• Avoid unnecessary checks
• Order conditions from most to least likely
• Nest ifs to avoid redundant checks
• Optional braces for single statements
• Avoid function calls in conditions
call to multiply

Example
function multiply()
{
console.log('call to multiply');
return 100 * 100;
}
if (multiply() < 100)
console.log('lt 100');
else if (multiply() < 100 && multiply() === 1000)
console.log('lt 100 and equal to 1000');
else if (multiply() > 100 && multiply() < 100)
console.log('gt 100 and lt 100');
else if (multiply() > 100 || multiply() < 100)
console.log('gt 100 or lt 100');
else
console.log('how did we get here?');

call to multiply
call to multiply
call to multiply
call to multiply
call to multiply
gt 100 or lt 100
call to multiply

Example
function multiply()
{
console.log('call to multiply');
return 100 * 100;
}
var result = multiply();
if (result < 100)
if (result === 1000)
console.log('lt 100 and equal to 1000');
else
console.log('lt 100');
else if (result > 100)
console.log('gt 100');
else
console.log('how did we get here?');

call to multiply
gt 100
Creative Uses
• Use logical operators for defaults values
• Use ternary operator for assignments
• Use ifs for logic flow
• Nest ternary operators
• Replace conditions with maps
Example
function namePerson(firstName, lastName)
{
firstName = firstName || "Unknown",
lastName = lastName || "Doe";
console.log("Person's name is: ", firstName, lastName);
}
namePerson();
namePerson("Joe");
namePerson("", "Doeson");
namePerson("Bob", "Doeson");

Person's name is:
Person's name is:
Person's name is:
Person's name is:

Unknown Doe
Joe Doe
Unknown Doeson
Bob Doeson
Example
var x = (firstCondition)
? (trueFirstCondition)
? firstConditionTrueValue
: firstConditionFalseValue
: falseFirstConditionValue;
var y;
if (firstCondition)
if (trueFirstCondition)
y = firstConditionTrueValue;
else
y = firstConditionFalseValue;
else
y = falseFirstConditionValue;
Objects
Object Literals
• Lightweight
• No prototype of its own
• No private variables
• Non-inheritable
• Faster than an instantiated object
Example
var x = {
first : "one",
second : "two"
};
x.prototype.test = "Test!";

TypeError: Cannot set property 'test' of undefined
Example
Object.prototype.third = "three";
var x = {
first : "one",
second : "two"
},
y = {};
console.log(x);
console.log(y);

Object {first: "one", second: "two", third: "three"}
Object {third: "three"}
Example
Object.prototype.third = "three";
var x = {
first : "one",
second : "two"
},
y = {};
console.log(delete x.third);
console.log(x);
console.log(delete Object.prototype.third);
console.log(x);

true
Object {first: "one", second: "two", third: "three"}
true
Object {first: "one", second: "two"}
Instantiated Objects
• Use of new operator
• Comes with its own prototype
• Has a constructor
• Ideal for Object Oriented Programming
• Permits proper encapsulation
Example
function MyClass()
{
var myName = "Joe";
}
MyClass.prototype.test = "Test";
var x = new MyClass(),
y = {};
console.log(x);
console.log(y);

MyClass {test: "Test"}
Object {}
Exercise
function MyClass()
{
var myName = "Joe";
}
Object.prototype.test = "Test 1"
MyClass.prototype.test = "Test 2";
var x = new MyClass();
x.test = "Test 3";
console.log(x);

MyClass {test: "Test 3", test: "Test 2", test: "Test 1"}
Careful
• Ensure parent object always exists
• Careful not to cause looping references
• Accidental array to object coercions
• Resist extending Object prototype
• IE errors on trailing commas in literals
Example
var x = {
y : null
};
x.y = x;
Object {y: Object}
What can be done
• Dynamic keys introduced via [ ]
• Dot notation is optional
• Use of delete to remove keys
• Use of in to determine if key exists
• Enumerate keys using in
Example
var x = {
"name" : "Joe"
};
console.log(x.name);
console.log(x['name']);
var newKey = "arbitrary";
x[newKey] = "value";
x;

Joe
Joe
Object {name: "Joe", arbitrary: "value"}
Look ahead
• ES5 offers Object.create()
• Upcoming property descriptors
• Getters and setters
• Proxy API in ES6
• ES5 gives access to keys via Object.keys()
Scope
Refresher
• Global and functional
• No block scope
• The let keyword is not part of ES5
• Skipping var globalizes identifier
• Scope chain
Scope Types
• Lexical scope can be resolved lexically
• Dynamic scope doesn’t exist
• Lexical and global not mutually exclusive
• Name binding applies with call() and apply()
• Dynamics present with with() and eval()
Why to know
• Understand how variables are resolved
• Optimize code by reducing lookups
• Clarify understanding of closures
• Identify potential memory leaks
• Detect potential name resolution conflicts
Exercise
function A(a)
{
function B(b)
{
function C(c)
{
console.log(a);
}
C();
}
B();
}
var a = "Joe";
A(a);

Joe
Functions
Review
• Declarations
• Expressions
• Constructor
• Anonymous functions
• Type of function
Nesting
• Limit nesting to one level if possible
• Each level introduces a link in scope chain
• Deteriorates performance
• Careful of inadvertent nestings
• Avoid wherever possible
Example
function A(a)
{
B(a);
}
function B(a)
{
C(a);
}
function C(a)
{
console.log(a);
}
A("Joe");

output if any
Declarations
• Best performance
• Always hoist name and definition
• Must be a source-element
• Converts to expression for non-sourced
• Using function statement
Example
A();
function A()
{
console.log('A');
B();
if (!true)
{
function B()
{
console.log('B 2');
}
}
}
function B()
{
console.log('B 1');
}

A
B2
Expressions
• Usually anonymous
• Variable is a reference to function
• Named expressions useful for tracing
• Name accessible within function only
• Using function operator
Example
var referenceAx = function Ax()
{
console.log(Ax);
};
referenceAx();
Ax();

function Ax()
{
console.log(Ax);
}
ReferenceError: Ax is not defined
Arguments
• Always passed by value
• There is no by reference
• Always optional
• Always accessible via arguments
• Array-like object but not an array
Example
function prove(objectliteral)
{
objectliteral.key = true;
objectliteral = undefined;
}
var objectliteral = {key: false};
prove(objectliteral);
objectliteral.key;

true
Example
function prove(objectliteral)
{
var myaddress = objectliteral;

// let's copy the value of the argument that supposedly
// contains the address.

objectliteral.key = true;
objectliteral = null;
myaddress.key = 1;

//
//
//
//

now we should be modifying the key of the objectliteral's address
which the objectliteral variable no longer has since we wiped it.
Since we now have the address, we can reference the key of that
object.

}
var objectliteral = {key: false};
prove(objectliteral);
objectliteral.key;

1
Memoization
• Reduces need for redundant calculations
• Cache derived values where possible
• Maintain easy-to-access registries
• Use getters and setters for control
• Weigh use of closures versus conditions
Example
function resolveNumber()
{
var result = 100 * 100;
resolveNumber = function ()
{
return result;
};
return resolveNumber(result);
}
console.log(resolveNumber);
console.log(resolveNumber());
console.log(resolveNumber);

function resolveNumber()
{
var result = 100 * 100;
resolveNumber = function () { return result; };
return resolveNumber(result);
}
10000
function () { return result; }
Prototype
Concept
• Defines an object
• Inheritable to inherited objects
• Propagates to all new and existing objects
• Has a constructor property
• Good way to extend objects
Prototype chain
• Resolve availability of method or property
• Similar to scope chain
• Each link traversal incurs cost
• Reduce inheritance for better performance
• Final link is null
Bad practice
• Do not extend native object prototypes
• Poor use of inheritance
• Looping without use of hasOwnProperty
• Carelessly extending an object
• Don’t forget to reset constructor
Closures
Concept
• Shared variables between multiple scopes
• Extends variable life beyond a scope’s end
• Inner scope can access outer scope
• Outer scope cannot access inner scope
• Locks up memory until freed
Example
function A(x)
{
var b = 1;
return function B()
{
debugger;
return x;
};
}
var c1 = A(1);
c1;

function B()
{
debugger;
return x;
}
Expressions
Overview
• Executed left-to-right
• Comma-separate multiple expressions
• Returns value of last expression
• Expressions always return a value
• Two types of expressions
Regex
When to use
• Match patterns in text
• Can be used with split()
• Also available with replace()
• Weigh performance versus complexity
• Time is of the essence
Advanced features
• Flags
• Captures
• Lookahead
• Negated lookahead
• Negated character set
Example
var pattern = ".{1}s*[a-z]+";
var re = new RegExp("[0-9]" + pattern + "$", "gi");
var regex = /d{2}s*[A-Z]/gi;
console.log("33v 45d".match(regex));
console.log("4@jK".match(re));
console.log(/(Joe +)(?=Doe)/.test("Joe Doe"));
console.log(/(Joe) +(?=Doe)/.test("Joe Bob"));

["33v", "45d"]
["4@jK"]
true
false
Common use cases
• Determine valid phone number
• Determine valid e-mail address
• Extract specific values from a string
• Parse CSV data
• Check for existence of content
Patterns
Good to know
• Understand how DOM and JS interact
• Memory leaks between DOM and JS
• DOM transactions are costly
• Patterns in JS can help with DOM
• Patterns for DOM better use jQuery
Observer pattern
• Used to decouple cause and effect
• Trigger event unaware of effect
• Event handlers respond to event
• Similar to publish / subscribe pattern
• Many frameworks use it already
MVC pattern
• Model, View, Controller
• Separation of concerns
• Comes in different flavors
• Ideal candidate to mix with Observer
• Promotes use of templates
Effective Coding
Coding Style
• Standardization improves quality
• Uses Java’s naming convention de facto
• Camel casing of identifiers
• Uppercase first letter to suggest a Class
• Alphabetize function definitions
Resources
Garbage collection
• Uses a mark and sweep strategy
• Assign a null value to help clean up
• Use of delete to help clean up
• Consistency helps with performance
• Proprietary GarbageCollect() not so good
Debugging
Use of features
• Breakpoints
• Call stack
• The debugger statement
• Acceptable uses of alert()
• Acceptable uses of console API
Console API
• Bad idea to override console
• Use of console.log() to navigate objects
• Use of different console methods
• Using console.warn() shows up in-code
• Easy to shim
Connect
• Thank you for your time
• Connect with me on LinkedIn
• Join the Hardcore JavaScript community
• Read my blog
• Contact me via e-mail

More Related Content

What's hot

Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP LanguageAhmed Ali
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless Jared Roesch
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Javameysholdt
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming PatternsVasil Remeniuk
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About RubyKeith Bennett
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-CKazunobu Tasaka
 
Zend%20Certification%20REVIEW%20Document
Zend%20Certification%20REVIEW%20DocumentZend%20Certification%20REVIEW%20Document
Zend%20Certification%20REVIEW%20Documenttutorialsruby
 
Python internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandPython internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandirpycon
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroAdam Crabtree
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 

What's hot (20)

Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP Language
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 
Javascript
JavascriptJavascript
Javascript
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Java
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About Ruby
 
About Python
About PythonAbout Python
About Python
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
Zend%20Certification%20REVIEW%20Document
Zend%20Certification%20REVIEW%20DocumentZend%20Certification%20REVIEW%20Document
Zend%20Certification%20REVIEW%20Document
 
Python internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandPython internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvand
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 

Similar to Intermediate JavaScript

A Deep Dive into Javascript
A Deep Dive into JavascriptA Deep Dive into Javascript
A Deep Dive into JavascriptTiang Cheng
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The LanguageEngage Software
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreWeb Zhao
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
Things that every JavaScript developer should know by Rachel Appel at FrontCo...Things that every JavaScript developer should know by Rachel Appel at FrontCo...
Things that every JavaScript developer should know by Rachel Appel at FrontCo...DevClub_lv
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuerycolinbdclark
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
An Overview of the Java Programming Language
An Overview of the Java Programming LanguageAn Overview of the Java Programming Language
An Overview of the Java Programming LanguageSalaam Kehinde
 

Similar to Intermediate JavaScript (20)

A Deep Dive into Javascript
A Deep Dive into JavascriptA Deep Dive into Javascript
A Deep Dive into Javascript
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The Language
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
Things that every JavaScript developer should know by Rachel Appel at FrontCo...Things that every JavaScript developer should know by Rachel Appel at FrontCo...
Things that every JavaScript developer should know by Rachel Appel at FrontCo...
 
Type Checking JavaScript
Type Checking JavaScriptType Checking JavaScript
Type Checking JavaScript
 
Lua pitfalls
Lua pitfallsLua pitfalls
Lua pitfalls
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
C++ overview
C++ overviewC++ overview
C++ overview
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
An Overview of the Java Programming Language
An Overview of the Java Programming LanguageAn Overview of the Java Programming Language
An Overview of the Java Programming Language
 

Recently uploaded

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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 

Recently uploaded (20)

Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 

Intermediate JavaScript

  • 1. JavaScript 200 Intermediate JavaScript by Milan Adamovsky http://milan.adamovsky.com ◆ http://www.hardcorejs.com
  • 2. Prerequisites • Fundamentals of language • Familiarity with syntax • Distinction between DOM and JS • Awareness of prototype and scope • Basic understanding of this
  • 3. Goals • Progressive complexity • Eye on performance • Familiarity with subtleties • Explanation of some of the internals • Awareness of new ways of doing things
  • 4. Roadmap • How to better control our code’s flow • How the code handles information • How information is resolved • How to practically apply advanced features • Introduction to more advanced topics
  • 6. Refresher Quiz • What is an identifier? • What are valid characters in identifiers? • What type system does the language use? • What are the primitives? • What primitives are mutable?
  • 7. Immutability • Most primitives are immutable • Type undefined is erroneously mutable • Objects are mutable • Literals are immutable • Some array methods mutate, some don’t
  • 8. Hoisting • Identifier is known to scope before value • Function names hoist after variables • Value of variables never hoist • Declaration of functions always hoist • Reflect hoisting in coding style
  • 9. Example function myFunction() { if (!x) console.log('undefined') else console.log('x : ', x); var x = ""; function x() { console.log('inside x function'); } } myFunction(); x : function x() { console.log('inside x function'); }
  • 10. Performance • Primitives are best • Arrays are second best • Objects are worst • Keep nesting to a minimum • Indexes better alternatives to nesting
  • 11. Example var family = { father : { first : 'joe', last : 'doe' }, mother : { first : 'jane', last : 'doe' } }; var father = { first : 'joe', last : 'doe' }, mother = { first : 'jane', last : 'doe' };
  • 12. Benchmark • http://jsperf.com/registry-design • Strategic approach to data structures • Different approach, different performance • Shows nested objects are worst • Suggests multiple objects best
  • 13. Reminders • Use typeof to determine type of variable • Use instanceOf to determine class type • Types via typeof are returned as strings • Type of null is ‘object’ • Type of NaN is ‘number’
  • 15. Refresher Quiz • What is logic flow? • What different ways can we control it? • What is a comparison operator? • What is the triple equal operator? • What does every condition resolve for?
  • 16. Logic Flow • if, if...else, if...else if...else • Ternary operator (?:) • Logical operators (||, &&, !) • Switch statement • Loops
  • 17. Effective Conditions • Avoid unnecessary checks • Order conditions from most to least likely • Nest ifs to avoid redundant checks • Optional braces for single statements • Avoid function calls in conditions
  • 18. call to multiply Example function multiply() { console.log('call to multiply'); return 100 * 100; } if (multiply() < 100) console.log('lt 100'); else if (multiply() < 100 && multiply() === 1000) console.log('lt 100 and equal to 1000'); else if (multiply() > 100 && multiply() < 100) console.log('gt 100 and lt 100'); else if (multiply() > 100 || multiply() < 100) console.log('gt 100 or lt 100'); else console.log('how did we get here?'); call to multiply call to multiply call to multiply call to multiply call to multiply gt 100 or lt 100
  • 19. call to multiply Example function multiply() { console.log('call to multiply'); return 100 * 100; } var result = multiply(); if (result < 100) if (result === 1000) console.log('lt 100 and equal to 1000'); else console.log('lt 100'); else if (result > 100) console.log('gt 100'); else console.log('how did we get here?'); call to multiply gt 100
  • 20. Creative Uses • Use logical operators for defaults values • Use ternary operator for assignments • Use ifs for logic flow • Nest ternary operators • Replace conditions with maps
  • 21. Example function namePerson(firstName, lastName) { firstName = firstName || "Unknown", lastName = lastName || "Doe"; console.log("Person's name is: ", firstName, lastName); } namePerson(); namePerson("Joe"); namePerson("", "Doeson"); namePerson("Bob", "Doeson"); Person's name is: Person's name is: Person's name is: Person's name is: Unknown Doe Joe Doe Unknown Doeson Bob Doeson
  • 22. Example var x = (firstCondition) ? (trueFirstCondition) ? firstConditionTrueValue : firstConditionFalseValue : falseFirstConditionValue; var y; if (firstCondition) if (trueFirstCondition) y = firstConditionTrueValue; else y = firstConditionFalseValue; else y = falseFirstConditionValue;
  • 24. Object Literals • Lightweight • No prototype of its own • No private variables • Non-inheritable • Faster than an instantiated object
  • 25. Example var x = { first : "one", second : "two" }; x.prototype.test = "Test!"; TypeError: Cannot set property 'test' of undefined
  • 26. Example Object.prototype.third = "three"; var x = { first : "one", second : "two" }, y = {}; console.log(x); console.log(y); Object {first: "one", second: "two", third: "three"} Object {third: "three"}
  • 27. Example Object.prototype.third = "three"; var x = { first : "one", second : "two" }, y = {}; console.log(delete x.third); console.log(x); console.log(delete Object.prototype.third); console.log(x); true Object {first: "one", second: "two", third: "three"} true Object {first: "one", second: "two"}
  • 28. Instantiated Objects • Use of new operator • Comes with its own prototype • Has a constructor • Ideal for Object Oriented Programming • Permits proper encapsulation
  • 29. Example function MyClass() { var myName = "Joe"; } MyClass.prototype.test = "Test"; var x = new MyClass(), y = {}; console.log(x); console.log(y); MyClass {test: "Test"} Object {}
  • 30. Exercise function MyClass() { var myName = "Joe"; } Object.prototype.test = "Test 1" MyClass.prototype.test = "Test 2"; var x = new MyClass(); x.test = "Test 3"; console.log(x); MyClass {test: "Test 3", test: "Test 2", test: "Test 1"}
  • 31. Careful • Ensure parent object always exists • Careful not to cause looping references • Accidental array to object coercions • Resist extending Object prototype • IE errors on trailing commas in literals
  • 32. Example var x = { y : null }; x.y = x; Object {y: Object}
  • 33. What can be done • Dynamic keys introduced via [ ] • Dot notation is optional • Use of delete to remove keys • Use of in to determine if key exists • Enumerate keys using in
  • 34. Example var x = { "name" : "Joe" }; console.log(x.name); console.log(x['name']); var newKey = "arbitrary"; x[newKey] = "value"; x; Joe Joe Object {name: "Joe", arbitrary: "value"}
  • 35. Look ahead • ES5 offers Object.create() • Upcoming property descriptors • Getters and setters • Proxy API in ES6 • ES5 gives access to keys via Object.keys()
  • 36. Scope
  • 37. Refresher • Global and functional • No block scope • The let keyword is not part of ES5 • Skipping var globalizes identifier • Scope chain
  • 38. Scope Types • Lexical scope can be resolved lexically • Dynamic scope doesn’t exist • Lexical and global not mutually exclusive • Name binding applies with call() and apply() • Dynamics present with with() and eval()
  • 39. Why to know • Understand how variables are resolved • Optimize code by reducing lookups • Clarify understanding of closures • Identify potential memory leaks • Detect potential name resolution conflicts
  • 40. Exercise function A(a) { function B(b) { function C(c) { console.log(a); } C(); } B(); } var a = "Joe"; A(a); Joe
  • 42. Review • Declarations • Expressions • Constructor • Anonymous functions • Type of function
  • 43. Nesting • Limit nesting to one level if possible • Each level introduces a link in scope chain • Deteriorates performance • Careful of inadvertent nestings • Avoid wherever possible
  • 44. Example function A(a) { B(a); } function B(a) { C(a); } function C(a) { console.log(a); } A("Joe"); output if any
  • 45. Declarations • Best performance • Always hoist name and definition • Must be a source-element • Converts to expression for non-sourced • Using function statement
  • 46. Example A(); function A() { console.log('A'); B(); if (!true) { function B() { console.log('B 2'); } } } function B() { console.log('B 1'); } A B2
  • 47. Expressions • Usually anonymous • Variable is a reference to function • Named expressions useful for tracing • Name accessible within function only • Using function operator
  • 48. Example var referenceAx = function Ax() { console.log(Ax); }; referenceAx(); Ax(); function Ax() { console.log(Ax); } ReferenceError: Ax is not defined
  • 49. Arguments • Always passed by value • There is no by reference • Always optional • Always accessible via arguments • Array-like object but not an array
  • 50. Example function prove(objectliteral) { objectliteral.key = true; objectliteral = undefined; } var objectliteral = {key: false}; prove(objectliteral); objectliteral.key; true
  • 51. Example function prove(objectliteral) { var myaddress = objectliteral; // let's copy the value of the argument that supposedly // contains the address. objectliteral.key = true; objectliteral = null; myaddress.key = 1; // // // // now we should be modifying the key of the objectliteral's address which the objectliteral variable no longer has since we wiped it. Since we now have the address, we can reference the key of that object. } var objectliteral = {key: false}; prove(objectliteral); objectliteral.key; 1
  • 52. Memoization • Reduces need for redundant calculations • Cache derived values where possible • Maintain easy-to-access registries • Use getters and setters for control • Weigh use of closures versus conditions
  • 53. Example function resolveNumber() { var result = 100 * 100; resolveNumber = function () { return result; }; return resolveNumber(result); } console.log(resolveNumber); console.log(resolveNumber()); console.log(resolveNumber); function resolveNumber() { var result = 100 * 100; resolveNumber = function () { return result; }; return resolveNumber(result); } 10000 function () { return result; }
  • 55. Concept • Defines an object • Inheritable to inherited objects • Propagates to all new and existing objects • Has a constructor property • Good way to extend objects
  • 56. Prototype chain • Resolve availability of method or property • Similar to scope chain • Each link traversal incurs cost • Reduce inheritance for better performance • Final link is null
  • 57. Bad practice • Do not extend native object prototypes • Poor use of inheritance • Looping without use of hasOwnProperty • Carelessly extending an object • Don’t forget to reset constructor
  • 59. Concept • Shared variables between multiple scopes • Extends variable life beyond a scope’s end • Inner scope can access outer scope • Outer scope cannot access inner scope • Locks up memory until freed
  • 60. Example function A(x) { var b = 1; return function B() { debugger; return x; }; } var c1 = A(1); c1; function B() { debugger; return x; }
  • 62. Overview • Executed left-to-right • Comma-separate multiple expressions • Returns value of last expression • Expressions always return a value • Two types of expressions
  • 63. Regex
  • 64. When to use • Match patterns in text • Can be used with split() • Also available with replace() • Weigh performance versus complexity • Time is of the essence
  • 65. Advanced features • Flags • Captures • Lookahead • Negated lookahead • Negated character set
  • 66. Example var pattern = ".{1}s*[a-z]+"; var re = new RegExp("[0-9]" + pattern + "$", "gi"); var regex = /d{2}s*[A-Z]/gi; console.log("33v 45d".match(regex)); console.log("4@jK".match(re)); console.log(/(Joe +)(?=Doe)/.test("Joe Doe")); console.log(/(Joe) +(?=Doe)/.test("Joe Bob")); ["33v", "45d"] ["4@jK"] true false
  • 67. Common use cases • Determine valid phone number • Determine valid e-mail address • Extract specific values from a string • Parse CSV data • Check for existence of content
  • 69. Good to know • Understand how DOM and JS interact • Memory leaks between DOM and JS • DOM transactions are costly • Patterns in JS can help with DOM • Patterns for DOM better use jQuery
  • 70. Observer pattern • Used to decouple cause and effect • Trigger event unaware of effect • Event handlers respond to event • Similar to publish / subscribe pattern • Many frameworks use it already
  • 71. MVC pattern • Model, View, Controller • Separation of concerns • Comes in different flavors • Ideal candidate to mix with Observer • Promotes use of templates
  • 73. Coding Style • Standardization improves quality • Uses Java’s naming convention de facto • Camel casing of identifiers • Uppercase first letter to suggest a Class • Alphabetize function definitions
  • 75. Garbage collection • Uses a mark and sweep strategy • Assign a null value to help clean up • Use of delete to help clean up • Consistency helps with performance • Proprietary GarbageCollect() not so good
  • 77. Use of features • Breakpoints • Call stack • The debugger statement • Acceptable uses of alert() • Acceptable uses of console API
  • 78. Console API • Bad idea to override console • Use of console.log() to navigate objects • Use of different console methods • Using console.warn() shows up in-code • Easy to shim
  • 79. Connect • Thank you for your time • Connect with me on LinkedIn • Join the Hardcore JavaScript community • Read my blog • Contact me via e-mail

Editor's Notes

  1. The two primitives that are mutable in 1.5 are undefined and null. This was fixed in ES5.
  2. The two primitives that are mutable in 1.5 are undefined and null. This was fixed in ES5. A developer is not expected to remember what types are resolved to as it may vary in engines - always rely on engine to check. Example is typeof /s/ === ‘function&apos;; works in FF as per ES5 but not in Chrome
  3. What is type coercion?
  4. We will explore these in an upcoming slide. There is also try/catch you could use to control the logic flow. Ternary operator is also known as conditional operator.
  5. Each check takes resources Move function calls outside of condition and reference its output
  6. We will explore refactor in next slide
  7. Here we see how we refactored it Only one function call Function call cached to var Check against var Nest conditions to reduce condition check cycles
  8. Here we show boolean operator to be used for default values in a function
  9. Compare nested ternary construct and if construct
  10. Tell there will be more on prototype later Give a brief intro to prototype It inherits the global Object prototype
  11. Here we see it does not have its own prototype
  12. Here we see how a literal inherits the Object prototype
  13. Here we see how delete works on a property of an object We also see that delete returns true Internally there is a Variable Object that keeps track of what is delete-able
  14. Show example of prototype on instantiated object Notice the prototype is extended on the class - not the object We can see myName is not accessible via x
  15. Think keys are unique? They are this simply shows the prototype chain - not the actual keys of the object. x.test would return what? Test 3 - why? Question: How would we get x.test to return Test 1 again?
  16. Mention IE crashes if key is reserved keyword
  17. Proxy API will allow for catch-all functions
  18. We will get back to scope chain a little later
  19. Dynamic scope not available but dynamics present in the sense of cannot determine lexical scope at parsing time.
  20. Here we want to show the scope chain and how it resolve “a”
  21. Here we can see that when we don’t nest, we can still avoid nesting by simply passing arguments - which is a better way to go.
  22. Show how the function B 2 is not a source-element so it should not hoist. Chrome shows B 2 and FireFox shows B 1
  23. Here we see that referenceAx returns a reference to the Ax() function but calling Ax() won’t work because Ax is only recognized from within Ax() Thus referenceAx !== referenceAx() in spite of them looking identical
  24. If we would pass by reference, the last statement (objectliteral = undefined) would wipe out the objectliteral - but it doesn&apos;t! Interestingly enough when we do modify a key, it will properly modify the key of the given object. This suggests that the parameter contains the value of the address of the object so that when we reference the key, we go to the address and modify the given key. However, if we assign a new value to the variable that contains the address we simply overwrite the value with our new value - effectively losing the reference to the object. Another way to illustrate this point, look at the example
  25. Inspect the b variable when debugger statement hits. This will show that it’s been GC’d. Add a reference to b and we will see it doesn’t GC it.
  26. Two types of expressions are those that assign a value and those that just have a value.