Summary Note On JavaScript.
Last few days, I have learned many things from many websites as my job preparation.Here is a summary based on my preparation.
String.slice():
It copies a section of a string and return it as a new string without modifying the original string.
Syntax:
string.slice(start,end)
Example:
const str = “Hello Bangladesh”;console.log(str.slice(0,6));//output:Hello
Global isNaN() Vs Number.isNaN():
isNaN is function that checks whether given value is a valid number or not. If the value is invalid number (Not-a-number) then it returns true otherwise it returns false.
Here, the global function isNaN(), first converts the tested value to a number and then evaluate it but Number.isNaN() directly tests it without any conversion.
Example:
console.log(isNaN(new Date().toString()));//string converted to number and return trueconsole.log(Number.isNaN(new Date().toString()));//return false
Array.splice():
This method changes the existing array by removing or replacing the array.
Syntax:
array.splice( index, remove_count, item_list )
Example:
let languages = [‘C++’, ‘Java’, ‘Html’, ‘Python’, ‘C’];// Add ‘javascript’ and ‘Php’ after removing ‘Html’.let removed = languages.splice(2, 1, ‘javascript’, ‘Php’)
Array.join():
This method creates a string by concatenating the array element using an optional separator parameter.
Example:
const arr = [“amar”,”sonar”,”bangla”];console.log(arr.join(“-”));//output: amar-sonar-bangla
Array.shift() and unshift():
Shift() method deletes the first element of an array. Unshift() method add a new element at first index of an array.
Example:
const arr = [“amar”,”sonar”,”bangla”];const del = arr.shift();console.log(arr);//output:[ ‘sonar’, ‘bangla’ ]const add = arr.unshift(“bangladesh”);console.log(arr);//output: [ ‘bangladesh’, ‘sonar’, ‘bangla’ ]
Object.assign():
This method is used to copy one or more source objects to a target object. It takes source objects and a target object as parameters and push the source objects into the target object and display the target object.
Example:
const target = { a: 1, b: 2 };const source = { b: 4, c: 5 };const returnedTarget = Object.assign(target, source);console.log(target);//output: { a: 1, b: 4, c: 5 }console.log(returnedTarget);//output: { a: 1, b: 4, c: 5 }
Here is a warning for deep cloning, If the source value is a reference to an object, it only copies the reference value.
Example:
let obj1 = { a: 0 , b: { c: 0}};let obj2 = Object.assign({}, obj1);console.log(JSON.stringify(obj2)); // { “a”: 0, “b”: { “c”: 0}}obj2.b.c = 3;console.log(JSON.stringify(obj1)); // { “a”: 1, “b”: { “c”: 3}}console.log(JSON.stringify(obj2)); // { “a”: 2, “b”: { “c”: 3}}
Object.create():
This method creates a new object, with the specified prototype. Newly created object can access all the properties of prototype object. It can take an optional parameter to add new properties.
Example:
const fruits = {test:’sour’}const mango = Object.create(fruits, {name:{value:’Rajshahi mango’}});console.log(‘name: ‘+mango.name + ‘, test: ‘+ mango.type)//output: name: Rajshahi mango, test: sour
Object.values() and Object.keys():
These methods return an array with values and keys of the object.
Example:
const object1 = {a: ‘somestring’,b: 42,c: false};console.log(Object.values(object1)); // output:[“somestring”, 42, false]console.log(Object.keys(object1)); //output: [“a”, “b”, “c”]
Object.freeze()
This method freezes an object. A frozen object can no longer be changed;
Example:
const obj = { prop: 42 };Object.freeze(obj);obj.prop = 33;// Throws an error in strict modeconsole.log(obj.prop);// expected output: 42
Math.round():
It returns the value of a number rounded to the nearest integer.
Example:
console.log(Math.round(0.9));//output: 1
Use addition(+) operator to convert a string to number:
There are many way to convert a string to a number. Most easiest way is using (+) operator before the string.
Example:
console.log(+”42"); //output:42
But it has a side effect. It can convert only number type string otherwise it returns NaN, that can be solved by using parseInt and parseFloat function. Like as —
console.log(+”10.2abc”); //output:NaNconsole.log(parseInt(“10.2abc”)); //Output:10console.log(parseFloat(“10.2abc”)); // output:10.2
For Loop:
We can declare a for loop like as-
//for loopconst a = [1,2,3,4,5];for (var i = 0, item; item = a[i];i++) {console.log(`Item-${i+1} = ${a[i]}`);}// Output:// Item-1 = 1// Item-2 = 2// Item-3 = 3// Item-4 = 4// Item-5 = 5
Here item = a[i] is used to check the length of array a.
Careful about array length:
Usually we know that array.length means the number of elements in array. But here is one thing on blow example —
const a = [1,2,3];a[100]=5;console.log(a.length);//output:101
Closure:
A closure is a function that remembers its outer variables and can access them. Whenever JavaScript executes a function, a ‘scope’ object is created to hold the local variables created within that function.
Example:
function makeAdder(a) {return function(b) {return a + b;}}x = makeAdder(5);console.log(x(6));
So when makeAdder() is called, a scope object is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function.
Public static fields:
Public static fields are useful when it needs to used only once per class, not on every class instance. Public static fields are declared using the static keyword. Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.
Example:
class a {static baseField = ‘base class field’}class b extends a {}console.log(b.baseField)// expected output: “base class field”
Public static methods:
The static keyword defines a static method for a class. Static methods aren’t called on instances of the class. Instead, they’re called on the class itself.
Example:
class ClassWithStaticMethod {static staticMethod() {return ‘static method has been called.’;}}const ins = new ClassWithStaticMethod();ins.staticMethod() //invalidconsole.log(ClassWithStaticMethod.staticMethod()); //valid
Form Structure:
Generally, we used to apply form tag to start a form and other fields are apply inside of this tag.
The <fieldset> tag draws a box around the related elements. It is used to group related elements in a form. The text content of the <legend> formally describes the purpose of the <fieldset> it is included inside.
Example:
<form>
<fieldset>
<legend>Fruit juice size</legend>
<p>
<label for=”name”>
Name :<input type=”text” name=”name” id=”name”>
</label>
</p>
</fieldset>
</form>
Multiple labels:
We can put multiple labels on a single widget, but this is not a good idea as some assistive technologies can have trouble handling them. In the case of multiple labels, we should nest a widget and its labels inside a single <label> element.
Let’s consider this example:
<div>
<label for=”username”>Name: <abbr title=”required” aria- label=”required”>*</abbr></label>
<input id=”username” type=”text” name=”username”>
</div>
Cross Browser Testing:
Cross Browser Testing is a process of testing to ensuring that an application works across different browsers perfectly. Each browser interprets the information on the website page in a distinct manner. Hence, some browsers may have insufficient features that is trying to show and make a website look broken on that browser. So it is necessary to verify an application compatibility with different browsers.
Workflow of cross browser testing:
The workflow for testing and bug fixes on a project can be broken down into roughly the following four phases –
i) Initial planning
ii) Development
iii) Testing/discovery
iv) Fixes/iteration
Initial Planning:
Initially you have an overall idea on your project. Then you should start exploring the target audience — what browsers, devices, etc. will the target audience for this site be using? After then you have an idea what technologies you will likely build these features to support different browsers.
Development:
There are multiple general strategies to cross browser development, for example:
ü Get all the functionality working as closely as possible in all target browsers. This may involve writing different code paths that reproduce functionality in different ways aimed at different browsers or using some polypill for any missing support.
ü Accept that some things aren’t going to work the same on all browsers, and provide different (acceptable) solutions in browsers that don’t support the full functionality.
ü Accept that your site just isn’t going to work in some older browsers.
Testing/discovery:
After completing development, you should test new functionality and make sure there are no general issues with your code that are stopping your feature from working.
· Test it in several browser.
· Do some lo-fi accessibility testing for keyboard and screen reader facilities.
· Test on mobile tablets and many small devices.
You can also go further than this, if wished. There are commercial tools available such as Sauce Labs, Browser Stack, LambdaTest, TestingBot, and CrossBrowserTesting that do this kind of thing for you, without you having to worry about the setup, if you wish to invest some money in your testing.Finally test it as a prerelease versions on different browser.
Fixes/iteration:
If you have any bug, you have to fix it by knowing about type of error, devices and browsers versions etc.
Client-side storage:
Nowdays most of the modern web sites are dynamic — they store data on the server using several kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting HTML to the client to be displayed by the user’s browser.
Client-side storage works on similar principles, but has different uses.They use different API to do so.
In early age of development, cookies are used to stored client side data. But at present, they use more effective APIs for storing client-side data than by using cookies. Such as –
1)Web Storage
2)IndexedBD etc.
Coding Style:
Our code writing should be clean and clear to read and debugging properly properly .Some suggestive rules are —
i) No space between function name and parentheses.
ii) A space between parameter.
iii) Curly brace { on the same line, after a space.
iv) An empty betwwen logical blocks
v) Line shouldn’t too long
vi) Horizontal space should be 2 or 4 spaces.
vii) Spaces around a nested call
viii) Give a semicolon after each statement etc.
Throwing our own error:
JavaScript has many built-in constructors for standard errors: Error
, SyntaxError
, ReferenceError
, TypeError
and others. We can use them to create error objects as well.
For instance, in signup system user name is must. Without name it shows an error like as –
///throwing our own errorlet json = ‘{“age”:30}’;try{let user = JSON.parse(json);if(!user.name) throw new SyntaxError(“SyntaxError:name is undefined”);//alert(user.name);} catch(err){console.log(err.message , err.name);}
try-catch-finally:
The finally clause is often used when we start doing something and want to finalize it in any case of outcome. If try block have any error then the work flow like-
try > catch > finally
If try block has no error then it works like-
try > finally
Example:
try {//work} catch (e) {//handle errors} finally {//cleanup the working space}
global-catch:
Let’s imagine we’ve got a fatal error outside of try..catch, and the script died. Like a programming error or some other terrible thing. Node.js has process.on(“uncaughtException”) for that. And in the browser we can assign a function to the special window.onerror property, that will run in case of an uncaught error.
<script>window.onerror = function(message, url, line, col, error) {alert(`${message}\n At ${line}:${col} of ${url}`);};function readData() {badFunc(); // Whoops, something went wrong!}readData();</script>
Custom made errors:
We can create our own error by extending Error class like as –
class Error{constructor(message){this.name = “build-in-error”;}}class CustomError extends Error{constructor(message) {super(message);this.name = “custom error”;}}try{throw new CustomError(“custom message”);} catch (e){console.log(e.message);console.log(e.name);}
DOM, DOM tree and Nodes:
DOM means Document Object Model.Whenever we want to run a website,browser try to create a DOM tree of the page that we want to see.We can control out website style through JavaScript document object.
For instance —
document.body.style.background = ‘red’;
By using this statement we can change webpage background.
The DOM consists of a tree structure of nested nodes, which is often referred to as the ‘DOM tree’.In DOM tree tags are element node, text outside of element is a text node and also have comment node that is not execute during page load.
<!DOCTYPE html><html lang=”en”><head><title>Document</title></head><body><h1>Element Node</h1><! — comment node →</body></html>
Beware: “innerHTML+=” does a full overwrite:
Usually we use += as a shortcut addition but in DOM it means overwrite. In other words, innerHTML+= does this:
i) The old contents is removed.
ii) The new innerHTML is written instead a concatenation of the old and the new one.
Create node and insert in Dom tree by using documentFragment:
A common use for DocumentFragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild() or insertBefore().
function getListContent() {let fragment = new DocumentFragment();for(let i=1; i<=3; i++) {let li = document.createElement(‘li’);li.append(i);fragment.append(li);}return fragment;}ul.append(getListContent());
Modify the document:
Methods to create new nodes:
i) document.createElement(tag) creates an element with the given tag.
ii) document.createTextNode(value) creates a text node (rarely used).
iii) element.cloneNode(deep) clones the element, if deep==true then with all descendants.
Insertion and removal:
i) node.append(…nodes or strings) to append a node at the end
ii) node.prepend(…nodes or strings) is used for preappend a node.
iii) node.before(…nodes or strings) is used to insert right before node.
iv) node.after(…nodes or strings) is used to insert right after node
v) node.replaceWith(…nodes[, strings]) is used to replace node.
vi) node.remove() is used to remove a node.
Classname Vs classlist:
Using “classList”, we can add or remove a class without affecting any others the element may have. But if we assign “className”, it will wipe out any existing classes while adding the new one (or if we assign an empty string it will wipe out all of them).
Assigning “className” can be a convenience for cases where you are certain no other classes will be used on the element, but I would normally use the “classList” methods exclusively.And “classList” also has handy “toggle” and “replace” methods.
Example:
//class listif (checked){listItem.classList.add(‘responded’);}else{listItem.classList.remove(‘responded’);}//classNameif (checked){listItem.className = ‘responded’;}else{listItem.className = ‘’;}
Styles with classes:
Normally we are used to style by using a separated css file. But we can declare CSS classes and style in the HTML tag. There are two general way are —
i) Create a class or id in CSS.
<body class=’bg-color’><h1 id=’heading’>This is the h1 tag</h1><p class=’paragraph’>Lorem ipsum dolor sit amet</p><script>function(){}</script></body>
ii) Write property directly in the html element:
<li style=’font-size: 30px’>Item</li>
Interesting Fact:
2.toString() //error2 .toString() //no error2..toString() //no error(2).toString() //no error
(==) Vs (===):
The equality operator(==) coerces of types in order to compare them. That’s why it is widely regarded as bad practice. To solve this problem JavaScript introduced a new operator called Strict Equality operator (===) that does not perform type coercion between its operands.
if(0 ==”0"){console.log(“true”);}else{console.log(“false”);}//output: trueif(0 ===”0"){console.log(“true”);}else{console.log(“false”);}//output: false
typeOf operator:
It uses to check the type of an object. Let’s see an example —
//typrofconsole.log(typeof(1.2));
But in order to check the type of an object, it is highly recommended to use Object.prototype.toString.
instanceof operator:
The instanceof operator is used to deal with custom made objects that originate from the same JavaScript context like as typeof.It shows unexpected results for native types.
//instanceofconst Foo =()=>{}const Bar =()=>{}Bar.prototype = new Foo();new Bar() instanceof Bar; // truenew Bar() instanceof Foo; // true
here Bar.prototype sets as a function object of Foo, but not to an actual instance of Foo. Take a look below —
Bar.prototype = Foo;new Bar() instanceof Foo; // false
Constructors of Built-In Types:
The constructors of the built in types like Number and String behave differently when being used with the new keyword and without it.
new Number(10) === 10; // False, Object and Number
Number(10) === 10; // True, Number and Number
new Number(10) + 0 === 10; // True, due to implicit conversion
Why Not to Use eval:
The eval function will execute a string of JavaScript code in the local scope and execute any type of code given to it that’s why it is alarming fact for security and performance. Apart from that it only executes in the local scope when it is being called directly and when the name of the called function is actually eval. For instance —
let number = 1;function test() { let number = 2; let copyOfEval = eval; copyOfEval('number = 3'); return number;}test(); // 2number; // 3
undefined and null:
Undefined is a type with exactly one value: undefined.
Here are some examples of when the value undefined is returned:
i) Accessing the (unmodified) global variable undefined.
ii) Accessing a declared but not yet initialized variable.
iii) Implicit returns of functions due to missing return statements.
iv) return statements that do not explicitly return anything
v) Lookups of non-existent properties.
vi) Function parameters that do not have any explicit value passed
vii) Anything that has been set to the value of undefined.
viii) Any expression in the form of void(expression)
There are two way to handle the changes to the value of undefined. Here are these —
// 1)As a local variablevar undefined = 123;(function(something, foo) {var undefined;…})(‘Hello World’, 42);//2) As a global variablevar undefined = 123;(function(something, foo, undefined) {})(‘Hello World’, 42);
Uses of null:
It is used in some JavaScript internals (like declaring the end of the prototype chain by setting Foo.prototype = null), but in almost all cases, it can be replaced by undefined.
setInterval():
While setTimeout only runs the function once, setInterval — as the name suggests — will execute the function every X milliseconds, but its use is discouraged.
When code that is being executed blocks the timeout call, setInterval will still issue more calls to the specified function. This can, especially with small intervals, result in function calls stacking up.
function foo(){// something that blocks for 1 second}setInterval(foo, 100);
In the above code, foo will get called once and will then block for one second.
Delete Operator:
In JavaScript, It’s impossible to delete global variable, function and other constants due to have a DontDelete attribute set. But explicit properties can be deleted easily by using delete operator.
Normal function args also has build in DontDelete attributes. But in case of host objects,it shows unpredictable result.
// global variable:var a = 1; // DontDelete is setdelete a; // falsea; // 1// normal function:function f() {} // DontDelete is setdelete f; // falsetypeof f; // “function”// reassigning doesn’t help:f = 1;delete f; // falsef; // 1// explicitly set property:var obj = {x: 1};obj.y = 2;delete obj.x; // truedelete obj.y; // trueobj.x; // undefinedobj.y; // undefined
Hoisting:
JavaScript hoists declarations. This means that both var statements and function declarations will be moved to the top of their enclosing scope.
bar();const bar = function() {};const someValue = 42;test();function test(data) {}
Name Resolution Order:
All scopes in JavaScript, whatever global or local scope, have a special name this, which refers to the current object. In order to function, arguments refers the arguments that were pass to the function.
For example, when trying to access a variable named foo inside the scope of a function, JavaScript will look up the name in the following order:
i) In case there is a var foo statement in the current scope, use that.
ii) If one of the function parameters is named foo, use that.
iii) If the function itself is called foo, use that.
iv) Go to the next outer scope, and start with #1 again.
Hoisting:
When we declare a var keyword anywhere to declare a variable, it acts as a global variable and that is called hoisting. For example if we declare a value variable inside an if block like as —
//hoistingfunction getValue(condition) {if (condition) {var value = “blue”;return value;} else {// value exists here with a value of undefined}// value exists here with a value of undefined}
But it acts like as —
function getValue(condition) {var value;if (condition) {value = “blue”;// other codereturn value;} else {return null;}
}
Let Vs Const Vs Var:
i) var act as a global variable that can be reassign whenever want.
ii) Let can be accessible and also reassign in declarative scope.
iii) Const can’t reassign that’s why it should initialize during declaration otherwise it takes undefined value. It can accessable in declarative scope only.
Rest parameter:
By using rest parameters we can gather any number of arguments into an array and do what we want with them. Rest parameters should have to be the last argument, because it collects all remaining arguments into an array.
Here is an example —
function xyz(x, y, …z) {console.log(x, ‘ ‘, y); // hey helloconsole.log(z); // [“wassup”, “goodmorning”, “hi”, “howdy”]console.log(z[0]); // wassupconsole.log(z.length); // 4}xyz(“hey”, “hello”, “wassup”, “goodmorning”, “hi”, “howdy”)
Spread operator:
Spread operator does exactly the reverse of rest operator. That means it converts an array elements to individual variables. It has many uses. Some of are —
i) copy an array
ii) Create an array from characters in a string
iii) Add an array to the end of another array
iv) Find the smallest/largest number in an array
v) Merge objects
vi) Destructuring an object and so on.
Let’s illustrate first example —
const arr1 = [1,2,3,4];const arr2 = […arr1];console.log(arr2);
Object Destructuring:
Object destructuring takes individual object property values and assigning them to the variables. For example —
let node = {type: "Identifier",name: "foo"};let { type, name } = node;console.log(type); // "Identifier"console.log(name); // "foo"
Array Destructuring:
Array destructuring syntax is very similar to object destructuring; it just uses array literal syntax instead of object literal syntax
let colors = [ "red", "green", "blue" ];let [ firstColor, secondColor ] = colors;console.log(firstColor); // "red"console.log(secondColor); // "green"
Class-Like Structures in ECMAScript 5:
Before ECMAScript 6,JavaScript has no class, instead of create a custom type approach where creating a constructor and then assigningmethods to the constractors prototype like as —
function PersonType(name) {this.name = name;}PersonType.prototype.sayName = function() {console.log(this.name);};let person = new PersonType(“Nicholas”);person.sayName(); // outputs “Nicholas”console.log(person instanceof PersonType); // trueconsole.log(person instanceof Object); // true
Classes as First-Class Citizens/Functions:
First-class citizen is called an approach where it can be used a class as a parameter of a function then returned from a function, and assigned to a variable. That allows classes to be used in a lot of different ways. For example, they can be passed into functions as arguments —
function createObject(classDef) {return new classDef();}let obj = createObject(class {sayHi() {console.log(“Hi!”);}});obj.sayHi(); // “Hi!”
In this example, the createObject() function is called with an anonymous class expression as an argument, creates an instance of that class with new, and returns the instance. The variable obj then stores the returned instance.
One more example –
let person = new class {constructor(name) {this.name = name;}sayName() {console.log(this.name);}}(“Nicholas”);person.sayName(); // “Nicholas”
Here, creating singletons by immediately invoking the class constructor without leaving a class reference available for inspection.
Computed Member Names:
Class methods and accessor properties can also have computed names. Instead of using an identifier, use square brackets around an expression like as —
//for methodlet methodName = “sayName”;class PersonClass {constructor(name) {this.name = name;}[methodName]() {console.log(this.name);}}let me = new PersonClass(“Nicholas”);me.sayName();//for propertylet propertyName = “html”;class CustomHTMLElement {constructor(element) {this.element = element;}get [propertyName]() {return this.element.innerHTML;}set [propertyName](value) {this.element.innerHTML = value;}}
Inheritance with Derived Classes:
In JavaScript, each class can only be derived from other class. That class is called a superclass, or parent class. The subclass is called derived class or child class.
By using extends, it can be inherit all the properties and method except private properties.
Here is an example —
class Rectangle {constructor(length, width) {this.length = length;this.width = width;}getArea() {return this.length * this.width;}}class Square extends Rectangle {constructor(length) {// same as Rectangle.call(this, length, length)super(length, length);}}var square = new Square(3);console.log(square.getArea()); //9
Object Oriented Programming (OOP):
OOP means object based programming. These concepts allow for the creation of Classes and Objects which lead to a greater degree of Abstraction. Three main concepts which make up OOP are: Encapsulation, Polymorphism, and Inheritance.
Encapsulation:
Encapsulation is the combination of data and operations to create a single structure for more abstraction.
Polymorphism:
Poly means multi and morps means forms that multiple forms. So it is the ability of a function to use it for multiple way.
Inheritance:
Inheritance is the concept of an object inheriting properties from another object.
Event Loop:
The Event Loop monitors the Call Stack and the Callback Queue. If the Call Stack is empty, it will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called Event Loop.Each event is just a function callback.
console.log(‘Hi’);
setTimeout(function cb1() {
console.log(‘cb1’);
}, 5000);
console.log(‘Bye’);
Call Stack:
The Call Stack is a data structure which records basically where in the program we are. If we step into a function, we put it on the top of the stack. If we return from a function, we pop off the top of the stack.
Mainly it follows (LIFO) principle to temporarily store and manage function invocation (call).
Let’s see an example. Take a look at the following code:
function multiply(x, y) {
return x * y;
}
function printSquare(x) {
var s = multiply(x, x);
console.log(s);
}
printSquare(5);
When the engine starts executing this code, the Call Stack will be empty. Afterwards, the steps will be the following:
Pure Function:
Pure functions are a pillar of functional programming that always returns the same result given same parameters. It doesn’t depend on or can’t modify the state of variables out of its scope.
Let’s see an example —
const obj = {a:5};
function pureFunction(a) {
const c = a+ 2;
return c;
}
console.log(pureFunction(obj.a)); //output:7
console.log(pureFunction(5)); //output: 7
Impure Function:
It may affected by outside of its lexical scope.
For instance —
const values = { a: 5 };
function impureFunction(items) {
items.a = items.a + 2;
return items.a;
}
var c = impureFunction(values);
// Now `values.a` is 7, the impure function modifies it.
Higher order function:
A function that take a callback function as a parameter is termed as higher order function. There have numerous types of build-in higher order functions in JavaScript like as mas, find, filter, reduce and so on.
Example:
const names = [“rakib”,”sakib”,”rofiq”];
const res = names.find(name=>name === “sakib”)? “Yes” : “No”;
console.log(res);
Immutability:
An immutable object is an object whose state cannot be modified after it is created. For the immutable data types, we have no way of changing the internal state of the data, so the reference always gets reassigned to a new object.
Example:
var person = new ImmutableMap({name: "Chris", age: 32});
var olderPerson = person.set("age", 33);person.toObject(); // {name: "Chris", age: 32}
olderPerson.toObject(); // {name: "Chris", age: 33}
Function Composition:
Function composition is the process of combining two or more functions to produce a new function.
Say for example, if a composition of functions `f` and `g` can be defined as `f(g(x))`, then it executes innermost function first then respectively outer one.so the execution order is —
`x`>`g`>`f`
Here is an example to clearify the fact —
function h(x) {
return x + 1; //1+1
}
function g(x) {
return x * x; //2*2
}
function f(x) {
return Math.pow(x, 3); //4^3
}
const y = f(g(h(1)));
console.log(y); // 64
Recursion:
Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a threshold value.
var countdown = function(value) {
if (value > 0) {
console.log(value);
return countdown(value - 1);
} else {
return value;
}
};
countdown(10);
Currying:
Currying is a transformation of functions that translates a function from callable as f(a, b, c)
into callable as f(a)(b)(c)
.
Currying doesn’t call a function. It just transforms it. Here is an Example —
function curry(f) {
return function(a) {
return function(b) {
return f(a, b);
}
}
}
function sum(a, b) {
return a + b;
}
let curriedSum = curry(sum);
alert( curriedSum(1)(2) ); // 3
That’s all for now. Bye.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields
https://developer.mozilla.org/en-US/docs/Learn/Forms/How_to_structure_a_web_form
https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage
http://bonsaiden.github.io/JavaScript-Garden/#types/#types
http://bonsaiden.github.io/JavaScript-Garden/#core.eval http://bonsaiden.github.io/JavaScript-Garden/#core.undefined
http://bonsaiden.github.io/JavaScript-Garden/#core.delete
http://bonsaiden.github.io/JavaScript-Garden/#other.timeouts
http://bonsaiden.github.io/JavaScript-Garden/#function.scopes