Special Concepts about JavaScript & MongoDB
--
Now JavaScript is everywhere. Millions of webpages are built on JavaScript. Below are some special facts that all web developers should know about JS.
Prototypes
In JavaScript prototype object is used when creating objects, for inheritance and adding methods to a JavaScript class.
In JavaScript, every function and object have a property named prototype by default. we can access the prototype property of a “Student” constructor function as follow.
function Student () {
this.name = ‘John’,
this.age = 23
}
const person = new Student();
console.log(Student.prototype);
Since the prototype property has no value at the moment, it shows an empty object { … }.
In JavaScript, a prototype can be used to add properties and methods to a constructor function. And objects inherit properties and methods from a prototype.
function Student () {
this.name = 'John',
this.age = 23
}
const stu1 = new Student();
const stu2 = new Student();
Student.prototype.gender = 'male';
console.log(Student.prototype);
// inheriting the property from prototype
console.log(stu1.gender);
console.log(stu2.gender);
//OUTPUT
{ gender: “male” }
Male
Male
Also we can add new methods to a constructor function using prototype. And we can access the prototype property of a constructor function from an object.
function Student () {
this.name = 'John'
}
// adding a prototype
Student.prototype.age = 20;
// creating object
const stu = new Student();
// accessing prototype property
console.log(stu.__proto__); // { age: 20 }
In the above example, a “stu” object is used to access the prototype property using _proto_.
‘this’
Unlikely other languages in JavaScript ‘this’ keyword acts differently.
To access a property of an object from within a method of the same object, you need to use the this keyword.
const student = {
name: ‘John’,
age: 20,
// accessing name property by using this.name
greet: function() { console.log(‘The name is’ + ‘ ‘ + this.name); }
};
student.greet();//output — The name is John
And function inside of an object can access its variable in a similar way as a normal function would.
const student = {
name: ‘John’,
age: 30,
greet: function() {
let surname = ‘Doe’;
console.log(‘The name is’ + ‘ ‘ + this.name + ‘ ‘ + surname); }
};
student.greet();//output — The name is John Doe
1. this Inside Global Scope
When this
is used alone, this
refers to the global object
2. this Inside Function
When this
is used in a function, this
refers to the global object
3. this Inside Constructor Function
In JavaScript, constructor function are used to create objects. When a function is used as a constructor function, this refers to the object inside which it is used.
4. this Inside Object Method
When this is used inside an object’s method, this refers to the object it lies within.
5. this Inside Inner Function
When you access this inside an inner function (inside a method),this refers to the global object.
6. this Inside Arrow Function
Inside the arrow function, this refers to the parent scope. Arrow function do not have their own this. When you use this inside an arrow function, this refers to its parent scope object. When the arrow function is used with this, it refers to the outer scope.
7. this Inside Function with Strict Mode
When this is used in a function with strict mode, this is undefined. When using this inside a function with strict mode, you can use JavaScript Function call().
Closure
In JavaScript closure is used to encapsulate variables into a function and restrict access to it from the outside. In JavaScript, a closure is function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope.
JavaScript closures in a loop
for (var index = 1; index <= 3; index++) {
setTimeout(function () {
console.log(‘after ‘ + index + ‘ second(s):’ + index);
}, index * 1000);
}/* OUTPUT
after 4 second(s):4
after 4 second(s):4
after 4 second(s):4*/
When we wanted to do in the loop is to copy the value of “ i “
in each iteration at the time of iteration to display a message after 1, 2, and 3 seconds.
The reason for this same message after 4 seconds is that the callback passed to the “setTimeout()”
a closure. It remembers the value of “ i ”
from the last iteration of the loop, which is 4.
In addition, all three closures created by the for loop share the same global scope access the same value of “ i “
.
To fix this issue, need to create a new closure scope in each iteration of the loop.
There are two popular solutions: IIFE & let
keyword.
1) Using the IIFE solution
In this solution, use an Immediately Invoked Function Expression (IIFE) because an IIFE creates a new scope by declaring a function and immediately execute it.
for (var index = 1; index <= 3; index++) {
(function (index) {
setTimeout(function () {
console.log(‘after ‘ + index + ‘ second(s):’ + index);
}, index * 1000);
})(index);
}/* OUTPUT
after 1 second(s):1
after 2 second(s):2
after 3 second(s):3*/
2) Using let
keyword in ES6
In ES6, can use the let
keyword to declare a variable that is block-scoped.
If use the let
keyword in the for loop, it will create a new lexical scope in each iteration. In other words, we will have a new index
variable in each iteration.
In addition, the new lexical scope is chained up to the previous scope so that the previous value of the index
is copied from the previous scope to the new one.
for (let index = 1; index <= 3; index++) {
setTimeout(function () {
console.log(‘after ‘ + index + ‘ second(s):’ + index);
}, index * 1000);
}/* OUTPUT
after 1 second(s):1
after 2 second(s):2
after 3 second(s):3*/
Callback and promises
JavaScript is asynchronous. All I/O operations in JavaScript is implemented to be asynchronous by nature. Reason for this is JavaScript being a single threaded language if an I/O operations holds the thread till it get completed JavaScript won’t perform well as a programming language. But asynchronous operation introduce difficulty when we need to do synchronous processing using data.
Callbacks
In order to perform asynchronous processing than waiting for a function to complete its execution, a process is told to call another function when the result is ready. This “other function” is called the callback. It is passed as an argument to any asynchronous function.
Callback Hell
Even though the callback-based solution seemed a good option for asynchronous programming in JavaScript, it introduces other problems. A single callback will be attached to a single asynchronous function. However, by nesting asynchronous functions, we could introduce a callback hell.
Promises
ES6 introduced Promises, which provided a clearer syntax that chains asynchronous commands as a series. This is more readable than callbacks and does not result in a callback-hell.
A Promise is a JavaScript object with a value that may not be available at the moment when the code line executes. These values are resolved at some point in the future. It allows to write asynchronous code more synchronously. A promise can have three states: Pending (not fulfilled or rejected), Fulfilled (Operation is successful), Rejected (Operation is unsuccessful).
MongoDB
MongoDB is a source-available, cross-platform, document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is developed by MongoDB Inc.
Advantages of MongoDB over RDBMS
· Schema less
· No complex joins
· Ease of scale-out
· Tuning
· Conversation/ mapping of application objects to database objects not needed
· Uses internal memory for storing the working set, enabling faster access of data
Basic Syntax in MongoDB (Usage — Syntax)
Create database/return the existing database — use DATABASE_NAME
check your currently selected database — db
check your databases list — Show dbs
drop a database — db.dropDatabase()
create a collection — db.createCollection(name, options)
drop a collection — db. COLLECTION_NAME.drop()
insert data into MongoDB —db.DATABASE_NAME.insertOne()
query data from MongoDB — db.DATABASE_NAME.findOne()
update data into DB — db.DATABASE_NAME.updateOne(SELECTION_CRITERIA, UPDATED_DATA)
remove a data from DB — db.DATABASE_NAME.deleteOne(DELLETION_CRITTERIA)
sort records — db.DATABASE_NAME.find().sort({KEY:1})
Aggregation from MongoDB — db. DATABASE_NAME.aggregate([{$stage:{expression:{accumulator}}}])