Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Awesomeness of JavaScript…almost
1. Awesomeness of JavaScript…almost
Twitter: #quintons
Github id: quintons
‘The most misunderstood language has become the worlds most
popular programming language’
Douglas Crockford – JavaScript architect, yahoo
‘JavaScript like the browsers is starting to move again’
Alex Russell – Software engineer, Chrome team and (ECMA) TC39 representative
2. Agenda
• In the beginning
• Objects, Functions
• Overview of Scope
• Overview of JS primitives and properties
• Gotchers!
• Questions…?
3. Agenda…for later
• Inheritance and the class’less language
• Prototypical (differential) inheritance
• Best Practices
• Modulising
• Multithreading with Webworkers
• Frameworks what they can offer
• Pollyfills, and how to use them
• Etc….
10. JavaScript is everywhere…
• Built into every PC
• Building Mobile apps
• Titainum,
• PhoneGap,
• Sencha Touch,
• jQuery mobile etc…
• Server side – Rhino, NodeJs, Apache Sling, etc…
• Every Browser
11. Proliferation of JS frameworks…
Frameworks using MVC
• Backbone.js • JavaScriptMVC
• Spine.js • SproutCore
• Choco.js • Cappuccino
• Agility.js • Google Web Toolkit (GWT)
• Jamal.js • Google Closure
• PureMVC • Ember
• TrimJunction • Etc…
14. Objects, Functions
• Run to completion
• No multithreading (almost)
• No type testing
• All objects are mutable
• Classless language – differential inheritance.
• functions and closures – data hiding/private state
15. Objects, Functions
• Data hiding
function count(){
var counter = 0;
var increment = function(){
counter += 1;
}
return function(){
increment() // increments counter
console.log(counter);
}
}
var inc = count();
inc(); // returns 1
inc(); // returns 2
16. Objects, Functions
• Functions are first class
• Can be passed as an argument
• Can be returned from a function
• Can be assigned to a variable
• Can be stored in an object or array
• arguments passed by value
• Function objects inherit from ‘Function.prototype’
18. Objects, Functions
• Function
• Defined with the Function constructor
var func = new Function("x", "y", "return x * y");
• A function declaration
function func(x, y){
return x * y;
}
• A function expression
var func = function(x, y){
return x * y;
}
19. Objects, Functions
• Function - A function declaration can be called before its
declaration.
// will work
foo();
function func(){
// code...
}
// won't work - hoisting!
func();
var func = function(){
// code
}
20. Objects, Functions
• Function - A function declaration can be called before its
declaration.
// will work
foo();
function func(){
// code...
}
// won't work - hoisting!
func();
var func = function(){
// code
}
…Why?….
21. Objects, Functions
• Function
• hoisting of variables.
(function(){
function func(){
// code
}
func()
})
(function(){
var func = undefined;
func() // returns 'undefined'
func = function(){
// code
}
})
22. Objects, Functions
• Example of a first class function
function collection(func){
var items = [];
return function(){
items[items.length] = func;
return items;
}
}
function item(name){
return 'item name is ' + name;
}
var coll = collection(item('item 1'));
var items = coll()
console.log(items[0])
23. Objects, Functions
• Functions – arguments object
• Not a true array
var args = Array.prototype.slice.call(arguments);
• …for example
(function(){
var args = Array.prototype.slice.call(arguments);
var arr = [1, 2, 3, 4, 5, 6];
console.log(args.slice(2)); // returns [3, 4, 5, 6]
console.log(arr.slice(2)); // again…returns [3, 4, 5, 6]
}(1, 2, 3, 4, 5, 6))
24. Objects, Functions
• Functions – arguments object
• arguments only available inside a function
var addNumbers = function(){
var val = 0;
for(var i = 0; i < arguments.length; i++){
val += arguments[i];
}
return val;
}
addNumbers(10, 10, 10) // 30
• If too few arguments are passed, the remaining will be
undefined
25. Objects, Functions
• Functions – arguments
• Little sugar – ES3/5 usage
function newMethod(val){
return 5 * val
}
• ES6 (Harmony) proposal
function newMethod(val = 10){
return 5 * val;
}
27. Objects, Functions
• Every property has a unique key string associated
to that object.
var val = Object['uniqueName']
var val = Object.uniqueName
Object['uniqueName'] = val;
Object.uniqueName = val;
delete Object['uniqueName'];
delete Object.uniqueName;
• Make an instance of an object use the ‘new’
keyword
var variable = new Constructor(arg1, arg2, …);
28. Objects, Functions
• Constructor
function Storage(){
var data = [];
this.getData = function(index){
return data[index];
}
this.addData = function(obj){
data[data.length] = obj;
}
}
var cords = new Storage();
cords.addData({x: 40, y: 10});
console.log(cords.getData(0).x); // 40
console.log(cords.constructor); // 'Storage()'
32. Closures/scope and this
• I do ‘this’ and you do that…
• ‘this’ keyword refers to the owner of the object that is
invoked
• ‘this’ allows a method to know what object it is
concerned with
• Without ‘this’ prototypical inheritance would not be
possible.
33. Closures/scope and this
• I do ‘this’ and you do that…continued
• function declaration/expression – ‘this’ assigned to the
global scope
• function as a method – ‘this’ assigned to the object
containing the function
• Inner function - ‘this’ does not get access to the outer
function’s ‘this’
34. Closures/scope and this
• I do ‘this’ and you do that…continued
function Counter(){
var that = this;
this.message = null;
this.count = function(msec){
setTimeout(function(){
that.showMessage('hello')
}, msec)
}
this.showMessage = function(msg){
console.log(this.message);
}
}
var obj = new Counter();
obj.message = 'help!';
obj.count(1000);
35. Closures/scope and this
• I do ‘this’ and you do that…continued
• You can change the context of what the object ‘this’
refers to.
function Logged(){
this.log = function(message){
console.log(message)
}
}
function Item(){
Logged.call(this)
}
var newItem = new Item();
newItem.log('Ow my god an Error!') // writes out .message
36. Closures/scope and this
• Only function creates scope, no block scope {}
/* no block level scope */
var arr = [1];
var x = 'something';
for(var i = 0; i < arr.length; i++){
var x = 'another thing';
}
console.log(x) // x === 'another thing'
var arr = [1];
var x = 'something';
for(var i = 0; i < arr.length; i++){
(function(){
var x = 'another thing';
})
}
console.log(x) // x === 'something'
37. Closures/scope and this
• ES5 to the rescue!...
var arr = [1];
var x = 'something';
for(var i = 0; i < arr.length; i++){
let x = 'another thing';
}
console.log(x) // x === 'something'
var arr = [1];
var x = 'something';
for(var i = 0; i < arr.length; i++){
let (x = 20, y = 20){
console.log(x + y); // === 40
};
}
console.log(x) // x === 'something'
39. Primitives
• Numbers
• 1 type, 64 bit floating point (aka ‘double’)
• Associative Law does not hold true – ‘when dealing
only with addition or only with multiplication we get
the same result regardless of the order in which we do
the operations’
a = 0.1; b = 0.2; c = 0.3;
(a + b) + c === a + (b + c) = false;
(a + b) + c = 0.6000000000000001;
a + (b + c) = 0.6;
41. Primitives
• Numbers (…and more)
• All numbers inherit from Number.prototype
• Numbers first class objects
• A number can be stored in a variable
• A number can be passed as a parameter
• A number can be returned from a function
• A number can be stored in an object
43. Primitives
• parseInt/parseFloat
• Converts values into a number
• Converting string to a number stops at first non-
numerical character
parseInt('485px') === 485
parseInt('08') === 0
/* to resolve use 'base 10' */
parseInt('08', 10) === 8
parseInt('ABC', 10) === NaN
• parseFloat() defaults to base 10
45. Primitives
• String
• A sequence of 0 or more 16bit Unicode characters
• Strings are immutable
/* Does NOT work */
var foo = 'red';
foo[0] = 't';
console.log(foo); // still returns 'red'
/* Does work */
var foo = 'red'
var replaceAt = function(str, index, c){
return str.substr(0, index) + c + str.substr(index+c.length);
}
var foo = replaceAt(foo, 0 't') // foo is now 'ted'
46. Primitives
• String (…continued)
• String literals can use single or double quotes
• Multilines – evil!
var str = "this is
a multiline
string!"
• Converting number to a string
var str1 = num.toString();
var str2 = new String(num);
47. Primitives
• String (…and more)
• Convert string to a number
var num1 = +str;
var num2 = Number(str);
• String.length
• ‘length’ property is the number of 16bit characters
in a string
• All extended (outside of UCS-2) characters are
counted as length of 2
51. Primitives
• String methods (…continued)
• trim() – what about ES3?
var str = $.trim(' str '); // JQuery
var str = dojo.trim(' str '); // Dojo
if(!String.prototype.trim !== 'function'){
String.prototype.trim = function(){
return this.replace(/^s+|s+$/g, '');
}
}
var str = ' str '.trim();
52. Special Type of Object
• Array
• Array inherits from ‘Object’
• Length of an array auto incremented
• No type required for each value
• Array.length
• Always 1 larger than the highest index
• Looping use a for loop
• Do not use a for…in loop with Arrays
53. Special Type of Object
• Array
• Array inherits from ‘object’
• Length of an array auto incremented
• No type required for each value
• Array.length
• Always 1 larger than the highest index
• Looping use a for loop
• Do not use a for…in loop with Arrays
…Why?….
54. Special Type of Object
• Array (…continued)
• For in loop…
‘Array’ inherits from ‘Object’
var obj = ['val', 2]
Object.prototype.people = {
val: function(){}
}
for(key in obj){
if(obj.hasOwnProperty(key)){
console.log(obj[key]);
}
}
55. Special Type of Object
• Array (…continued)
• Array literals
• An array literal uses []
• It can contain any number of values of any type
foo[foo.length] = val; // assign value
var val = foo[0]; // retriving a value
• Deleting elements
• Removes the element but leaves a hole
56. Special Type of Object
• Array (…continued)
• Deleting elements….creates a hole
var foo = [1, 2, 3, 4, 5]
delete foo[2];
// foo = [1, 2, undefined, 4, 5]
var delIndexArray = foo.splice(2,1);
// foo = [1, 2, 4, 5];
// delIndexArray = [3]
• Arrays are not true arrays – inherits from ‘Object’
var myArray = [];
(typeof myArray === 'object') // true
57. Special Type of Object
• Array (…continued)
• Are you an array?
if(Array.isArray !== 'function'){
Array.isArray = function(arr){
return Object.prototype.toString.call(arr) === '[object
Array]';
}
}
var arr = [1, 2, 3, 4, 5, 6];
console.log(Array.isArray(arr)); // returns true
$.isArray(arr); // (jQuery) returns true
dojo.isArray(arr); (dojo) // returns true
$type(arr) // (Mootools) returns 'array'
58. Special Type of Object
• Date
• …..too many methods to list! (48)
• Y2K compliant – was not initially
60. Watch out!
• Accidental collision with keywords used as properties
var word_count = [];
/* accidental collision fails with word 'constructor' */
function wordCount(word){
if(word_count[word]){
word_count[word] += 1;
}else{
word_count[word] = 1;
}
}
function wordCount (word){
if(typeof word_count[word] === 'number'){
word_count[word] += 1;
}else{
word_count[word] = 1;
}
}
61. Watch out!
• For…in
• functions that inherit from prototype are included in
the for..in enumeration
• NaN
• Special number – Not a Number
• NaN is evil
NaN + 5 == NaN;
• Use isNaN() to test for NaN
62. Watch out!
• NaN (…continued)
• NaN === NaN = false
• NaN !== NaN = true
• Silent Errors – automatic semicolon insertion
return // <- returns 'undefined'
{
var foo = 'hello'
}
• Switch statement, will fall through if no break statement is
declared
63. Watch out!
• Immediately invocable function expression
function(){
// code
}(); // syntax error! can't be immediately invoked
(function(){
// code
}());
• Infinity/-Infinity
• 1/0 === Infinity
• -1/0 === -Infinity
• Test for Infinity/-Infinity use isFinite()
64. Watch out!
• Relying on type coercion is not a good idea.
null == undefined // true
false == undefined // false
false == 'false' // false
'' == '0' // false
0 == '' // true
0 == '0' // true
• Always use ‘===‘ not ‘==‘
null === undefined // false
false === undefined // false
false === 'false' // false
'' === '0' // false
0 === '' // false
0 === '0' // false
65. Watch out!
• Operators and Concatenation
var val = "3" + 0; // '30'
var val = 6 + 3 + "4" // '94'
var val = 6 + 3 + parseInt("4") // 13
1993 at National Center for Super Computing Applications – created mosaic (1st popular browser)1994 Jim clark (founder of Silicon Graphics) setup company Mosaic CorporationSued for name – changed to Netscape Corporation– created Netscape Navigator
1995 Netscape Hired Brendon Ike - (working at Silicon Graphics), Scripting language ‘Mocha’ (Scheme, Java, Self)Became LiveScript - Server/Client scriptingDecember 1995 licensing agreement with SunLiveScript -> JavaScript
Microsoft reversed engineered JavaScript – became JscriptNetscape went to W3C for standard (no show) Netscape Landed at European Computer Manufacturers Association (ECMA)Unfortunately -> Microsoft on Committee (standards body)JavaScript – Registered Trade Mark.name came to be ECMAScript (ECMAScript 262)
Wanted Standard name, name came to be ECMAScript (ECMAScript 262)1997 – ES11999 – ES34th Edition Abandoned2009 – ES52013 – ES6 (ES Harmony)
Function –behavior containing data NOT data containing behaviour
255 arguments – max length.
Maps – JSONArrays act like Maps
Most important for ‘Prototypical Inheritance’The unfortunate name – hard to talk about
- in a browser that is the Window object
> As said before “‘this’ keyword refers to the owner of the object that is invoked”
George Boole - 1854 in his book ‘An investigation of the Laws of Thought’.
UCS-2 internally, not quite UTF-16Any character coming under UCS-2, outside of UTF-16 maybe counted as length === 2
New String() is GC’edString literals are NOT GC’ed
If word is ‘Constructor’ fails – already contains word inherited from Object.ECMA Specification states ‘a browser maker can add new properties to any prototype’