Advanced ES5
Part -2
Week 1
Day 5
Builtin Modules
- Boolean
- Date
- Error
- Function
- JSON
- Math
- Number
- NaN
- Infinity
The Boolean object is an object wrapper for a boolean value.
Boolean
Syntax
new Boolean([value])
Parameters
value
Optional. The initial value of the Boolean object.
- The value passed as the first parameter is converted to a boolean value, if necessary.
- If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.
- All other values, including any object or the string "false", create an object with an initial value of true.
- Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.
- Any object of which the value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.
var x = new Boolean(false);
if (x) {
// this code is executed
}
Do not use a Boolean object to convert a non-boolean value to a boolean value. Instead, use Boolean as a function to perform this task:
var x = Boolean(expression); // preferred
var x = new Boolean(expression); // don't use
Properties
- Boolean.length
Length property whose value is 1.
- Boolean.prototype
Represents the prototype for the Boolean constructor.
Date
- Creates a JavaScript Date instance that represents a single moment in time.
- Date objects are based on a time value that is the number of milliseconds since 1 January 1970 UTC.
Unix time (also known as POSIX time[citation needed] or UNIX Epoch time) is a system for describing a point in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.
var date1 = new Date('December 17, 1995 03:24:00');
// Sun Dec 17 1995 03:24:00 GMT...
var date2 = new Date('1995-12-17T03:24:00');
// Sun Dec 17 1995 03:24:00 GMT...
console.log(date1 === date2);
// expected output: false;
console.log(date1 - date2);
// expected output: 0
JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object;
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
value
- Integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).
dateString
- String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).
Date.now()
- Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
Date.parse()
- Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC, with leap seconds ignored.
Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
Date.UTC()
- Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.
Function
- The Function constructor creates a new Function object.
- Calling the constructor directly can create functions dynamically, but suffers from security problems.
var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));
// expected output: 8
Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function which returns true.
Function.prototype.apply()
- Calls a function and sets its this to the provided value, arguments can be passed as an Array object.
Function.prototype.bind()
- Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.
Function.prototype.call()
- Calls (executes) a function and sets its this to the provided value, arguments can be passed as they are.
Function.length
- Specifies the number of arguments expected by the function.
Function.name
- The name of the function.
Function.prototype.bind()
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
var module = {
x: 42,
getX: function() {
return this.x;
}
}
var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
var boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
Syntax: function.bind(thisArg[, arg1[, arg2[, ...]]])
Function.prototype.call()
The call() method calls a function with a given this value and arguments provided individually.
Syntax: function.call(thisArg, arg1, arg2, ...)
function greet() {
var reply = [
this.animal,
'typically sleep between',
this.sleepDuration
].join(' ');
console.log(reply);
}
var obj = {
animal: 'cats', sleepDuration: '12 and 16 hours'
};
greet.call(obj);
// cats typically sleep between 12 and 16 hours
Function.prototype.apply()
The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
Note: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
var numbers = [5, 6, 2, 3, 7];
var max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
var min = Math.min.apply(null, numbers);
console.log(min);
// expected output: 2
Syntax: function.apply(thisArg, [argsArray])
JSON
- The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON.
- It can't be called or constructed, and aside from its two method properties, it has no interesting functionality of its own.
- JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null.
- It is based upon JavaScript syntax but is distinct from it:
- some JavaScript is not JSON,
- and some JSON is not JavaScript.
JSON.parse()
- Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
JSON.stringify()
- Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
Math
Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.
Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static.
Math.E
- Euler's constant and the base of natural logarithms, approximately 2.718.
Math.LN2
- Natural logarithm of 2, approximately 0.693.
Math.LN10
- Natural logarithm of 10, approximately 2.303.
Math.log2(x)
- Returns the base 2 logarithm of a number.
Math.max([x[, y[, …]]])
- Returns the largest of zero or more numbers.
Math.min([x[, y[, …]]])
- Returns the smallest of zero or more numbers.
Math.pow(x, y)
- Returns base to the exponent power, that is, baseexponent.
Math.random()
- Returns a pseudo-random number between 0 and 1.
- The Number type has exactly 18437736874454810627 (that is, 2^64−2^53+3) values, representing the double-precision 64-bit format IEEE 754-2008 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic,
- except that the 9007199254740990 (that is, 253−2) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special NaN value.
There are two other special values, called positive Infinity and negative Infinity.
Concurrency and Event Loop
Stack
Heap
-
Event Loop *
"Run-to-completion"
Zero delays
Multiple runtimes
Never blocking
Stack
Function calls form a stack of frames.
function foo(b) {
var a = 10;
return a + b + 11;
}
function bar(x) {
var y = 3;
return foo(x * y);
}
console.log(bar(7));
//returns 42
When calling bar, a first frame is created containing bar's arguments and local variables.
When bar calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables.
When foo returns, the top frame element is popped out of the stack (leaving only bar's call frame).
When bar returns, the stack is empty.
Heap
Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory.
Never blocking
A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks.
Handling I/O is typically performed via events and callbacks, so when the application is waiting for an
IndexedDB query to return or an XHR request to return, it can still process other things like user input.
Segment 2
Introduction to FP
- The design of the imperative languages is based directly on the von Neumann architecture
- Efficiency is the primary concern, rather than the suitability of the language for software development
- The design of the functional languages is based on mathematical functions
- A solid theoretical basis that is also closer to the user, but relatively unconcerned with the architecture of the machines on which programs will run
- treats computation as evaluation of mathematical functions (and avoids state)
- data and programs are represented in the same way
- functions as first-class values
- – higher-order functions: functions that operate on, or create, other functions
- – functions as components of data structures
- lambda calculus provides a theoretical framework for describing functions and their evaluation
- it is a mathematical abstraction rather than a programming language
Principles of Programming
Functional Programming
In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
In computer science, imperative programming is a programming paradigm that uses statements that change a program's state.
const doubleMap = numbers => {
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
return doubled;
};
console.log(doubleMap([2, 3, 4])); // [4, 6, 8]
const doubleMap = numbers => numbers.map(n => n * 2);
console.log(doubleMap([2, 3, 4])); // [4, 6, 8]
Why is it Useful?
There are many possible answers to this question, but generally speaking:
- The abstract nature of functional programming leads to considerably simpler programs;
- It also supports a number of powerful new ways to structure and reason about programs.
total = 0;
for (i = 1; i <= 10; ++i)
total = total+i;
sum [1..10]
- Programs are easy to write because the system relieves the user from dealing with many tedious implementation considerations such as memory management, variable declaration, etc .
- Programs are concise (typically about 1/10 of the size of a program in non-FPL)
- Programs are easy to understand because functional programs have nice mathematical properties (unlike imperative programs) .
- Functional programs are referentially transparent , that is, if a variable is set to be a certain value in a program; this value cannot be changed again. That is, there is no assignment but only a true mathematical equality.
What is a function?
A function is a
-
relation
-
between input values
-
to output values
Side Effects
A side effect is any application state change that is observable outside the called function other than its return value. Side effects include:
- Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain)
- Logging to the console
- Writing to the screen
- Writing to a file
- Writing to the network
- Triggering any external process
- Calling any other functions with side-effects
Benefits of stateless programs
- Idempotent (pure) functions
- Order of evaluation not defined
- Lazy evaluation possible
- Optimizations
- Concurrent processing
- Easier to test and debug
- Side effects can’t be eliminated, but can be isolated (monads)
FP Concepts
Pure Functions
Functions as First Class Citizens
Higher Order Functions
Lazy Evaluation
A function should be pure
Pure means that given the same inputs a function should always return the same output, it's deterministic.
It has no side-effects
Let's put emphasis on always again. It means that those are not considered pure:
IO operations
Web requests,
Anything that can throw an exception
Higher Order Functions
A function is called higher-order if it takes a function as an argument or returns a function as a result.
The Map Function
The higher-order library function called map applies a function to every element of a list.
map :: (a -> b) -> [a] -> [b]
> map (+1) [1,3,5,7]
[2,4,6,8]
Lazy Evaluation
In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed
The benefits of lazy evaluation include:
- The ability to define control flow (structures) as abstractions instead of primitives.
- The ability to define potentially infinite data structures. This allows for more straightforward implementation of some algorithms.
- Performance increases by avoiding needless calculations, and error conditions in evaluating compound expressions.
- Function composition is the process of combining two or more functions to produce a new function.
- Composing functions together is like snapping together a series of pipes for our data to flow through.
Function Composition
Put simply, a composition of functions `f` and `g` can be defined as `f(g(x))`, which evaluates from the inside out — right to left. In other words, the evaluation order is:
- `x`
- `g`
- `f`
const toSlug = input => encodeURIComponent(
input.split(' ')
.map(str => str.toLowerCase())
.join('-')
);
console.log(toSlug('JS Cheerleader'));
// 'js-cheerleader'
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const toSlug = compose(
encodeURIComponent,
join('-'),
map(toLowerCase),
split(' ')
);
console.log(toSlug('JS Cheerleader'));
// 'js-cheerleader'
Pure functional programming in Javascript
If we wanted to program in a pure functional manner in Javascript we can set the following rules:
- No assignment i.e. changing the value of something already created with = (var statements with = are fine)
- No for or while loops (use recursion instead)
- Freeze all objects and arrays (since modifying an existing object or array would be a stateful expression)
- Disallow Date (since it always produces a new value no matter what the inputs are)
- Disallow Math.random (same reason as Date)
Style Guides
What are Style Guides
Some Common Best Practices
AirBnB
Google
Standard JS
GitHub
Advanced ES5 Part-2 (Week 1, Day 5)
By Amal Augustine
Advanced ES5 Part-2 (Week 1, Day 5)
- 194