Week 1
Day 5
The Boolean object is an object wrapper for a boolean value.
Syntax
new Boolean([value])
Parameters
value
Optional. The initial value of the Boolean object.
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
Length property whose value is 1.
Represents the prototype for the Boolean constructor.
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
dateString
Date.now()
Date.parse()
Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
Date.UTC()
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()
Function.prototype.bind()
Function.prototype.call()
Function.length
Function.name
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[, ...]]])
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
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.parse()
JSON.stringify()
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
Math.LN2
Math.LN10
Math.log2(x)
Math.max([x[, y[, …]]])
Math.min([x[, y[, …]]])
Math.pow(x, y)
Math.random()
There are two other special values, called positive Infinity and negative Infinity.
Stack
Heap
Event Loop *
"Run-to-completion"
Zero delays
Multiple runtimes
Never blocking
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.
Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory.
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.
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]
There are many possible answers to this question, but generally speaking:
total = 0;
for (i = 1; i <= 10; ++i)
total = total+i;
sum [1..10]
A side effect is any application state change that is observable outside the called function other than its return value. Side effects include:
Pure Functions
Functions as First Class Citizens
Higher Order Functions
Lazy Evaluation
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
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]
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:
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:
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:
What are Style Guides
Some Common Best Practices
AirBnB
Standard JS
GitHub