Js Notes
Article: A re-introduction to JavaScript
Intro
JS is misunderstood because of its simplicity and the similarity between its name and Java, however, its power lies in its wide application in web and mobile apps.
History
- 1995: created by an engineer at Netscape, Brendan Eich
- 1996: first release with Netscape 2
- JavaScript instead of LiveScript due to ill-fated marketing decision
- JS and java(Microsystem) has little in common
- 1996: later that year, Microsoft release JScript similar to JS
- 1996: ECMAScript 1st edition after Netscape submitted JS to Ecma International
- 1999: ECMASccript 3rd edition
- 2009: Dec. ECMAScript 5th edition
- 2015: Jun. ECMAScript 6th edition
Confusion:
- ECMAScript: short for ‘European Computer Manufacturers Association Script’; it’s a standard for script language derived from JavaScript, ensuring the consistency between Netscape, Microsoft and other Web script implementations
- JavaScript: a widely-used scripting language used in Web pages to affect how they look or behave for users; it shares some similar syntax with Java, e.g. semicolons to terminate a statement, curly braces to delineate code block, looping and iterative structures; however, different vendor, maintained by diff consortium, diff language features such as object orientation and strong typing are major instances the two differ
- TypeScript: open-source, developed by Microsoft, a strict syntactical superset of JS, for development of large applications and transcompiles to JS
The Types
Numbers
“double-precision 64-bit format IEEE 754 values”
- Math method
- parseInt()
parseInt('123', 10); // 123
parseInt('11', 2); // 3
- parseFloat() always uses base 10 unline parseInt()
- NaN
- NaN +5; // NaN
- isNaN(NaN); //true
- special values
Infinity
and-Infinity
- 1/0; // Infinity
- -1/0; // -Infinity
- isFinite(1/0); // false
- isFinite(NaN); // false
Strings
Stings are like objects, they have methods as well
'hello'.length; // 5
'hello'.charAt(0); // "h"
'hello, world'.replace('world', 'mars'); // "hello, mars"
'hello'.toUpperCase(); // "HELLO"
null
a deliberate none-value, only accessable with key word null
undefined
a var hasn’t been assigned yet, undefined
is a const
boolean
with values true
and false
Any value can be converted to a boolean according to the following rules:
- false, 0, empty strings (“”), NaN, null, and undefined all become false.
- All other values become true.
Variables
let, const, var
let
and const
are block-scoped var
const
values are never intended to change
Operators: + - * / % && ||
Bitwise operators: don’t know what they are but will read when needed
Control Structures
basic if else statement
var name = 'kittens';
if (name == 'puppies') {
name += ' woof';
} else if (name == 'kittens') {
name += ' meow';
} else {
name += '!';
}
name == 'kittens meow';
do-while
ensures the loop is run at least once, whereas while
doesn’t
for loop:
for (var i = 0; i < 5; i++) {
// Will execute 5 times
}
for (let value of array) {
// do something with value
// You could also iterate over an array using a for...in loop, however this does not iterate over the array elements, but the array indices. Furthermore, if someone added new properties to Array.prototype, they would also be iterated over by such a loop. Therefore this loop type is not recommended for arrays.
}
for (let property in object) {
// do something with object property
}
ternary operator for conditional expressions:
var allowed = (age > 18) ? 'yes' : 'no';
switch
switch (action) {
case 'draw':
drawIt();
break;
case 'eat':
eatIt();
break;
default:
doNothing();
}
Objects
just like dict
in python
var obj = {
name: 'Carrot',
for: 'Max', // 'for' is a reserved word, use '_for' instead.
details: {
color: 'orange',
size: 12
}
};
obj.details.color; // orange
obj['details']['size']; // 12
function Person(name, age) {
this.name = name;
this.age = age;
}
// Define an object
var you = new Person('You', 24);
// We are creating a new person named "You" aged 24.
Arrays
forEach()
['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) {
// Do something with currentValue or array[index]
});
a.push(item); // to append an item
Arrays come with a number of methods. See also the full documentation for array methods.
Functions
the core to understand JS. functions are objects too. EVERYTHING in JS is an object.
arguments
function add() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
sum += arguments[i];
}
return sum;
}
add(2, 3, 4, 5); // 14
Rest Parameter Syntax: the syntax which suggests the rest of the parameter?
function avg(...args) {
var sum = 0;
for (let value of args) {
sum += value;
}
return sum / args.length;
}
avg(2, 3, 4, 5); // 3.5
However, the arguments passed in should be individual numbers. what if it’s an array?
function avgArray(arr) {
var sum = 0;
for (var i = 0, j = arr.length; i < j; i++) {
sum += arr[i];
}
return sum / arr.length;
}
avgArray([2, 3, 4, 5]); // 3.5
we can also reuse the function avg() :
avg.apply(null, [2, 3, 4, 5]); // 3.5
or using the spread operator
avg(...numbers)
anonymous functions
var avg = function() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
sum += arguments[i];
}
return sum / arguments.length;
};
This enables all kinds of clever tricks, e.g. call them recursively:
var charsInBody = (function counter(elm) {
if (elm.nodeType == 3) { // TEXT_NODE
return elm.nodeValue.length;
}
var count = 0;
for (var i = 0, child; child = elm.childNodes[i]; i++) {
count += counter(child);
}
return count;
})(document.body);
Custom objects
EVERYTHING is object in JS. Functions with capitalised names are like classes, called ‘constructors’ in JS, should be called by new
.
function personFullName() {
return this.first + ' ' + this.last;
}
function personFullNameReversed() {
return this.last + ', ' + this.first;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
}
Object.prototype
Interestingly, you can also add methods to the prototype of built-in JavaScript objects.
var s = new Person('Simon', 'Willison');
s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function
Person.prototype.firstNameCaps = function() {
return this.first.toUpperCase();
};
s.firstNameCaps(); // "SIMON"
Inner functions
If a call function relies only on one or two other functions, it should be nested and become a inner function. An inner function can access the vars in their parent functions’s scope. Inner functions keeps the overall numbers of global functions down, less pollution.
Closures: some excellent introductions
A closure is the combination of a function and the scope object in which it was created. Closures let you save state — as such, they can often be used in place of objects.
function makeAdder(a) {
return function(b) {
return a + b;
};
}
var add5 = makeAdder(5);
var add20 = makeAdder(20);
add5(6); // 11
add20(7); //2 27
more reading:
- Introduction to Object-Oriented JS
apply()
andcall()
, difference and how to use them?apply call bind
explain