JavaScript Notes — 2
Closure, this, Equality, Object Inheritance, __proto__, Class
In JS, we can also return a function from a function.
function outer (param1) {
let a1 = 10;
function inner (param2) {
let a2 = 20;
console.log(param1, a1, param2, a2); // LINE A
}
return inner;
}
let x = outer ('lunch'); // LINE B
x ('dinner'); // LINE CAmong Line A, B and C, guess what will be the order of execution?
The correct order will be: Line B, then C, then A.
Closure
Scopes available at the birthplace of a function are acquired by the function (infinite nesting supported). But if current scope has a variable and another variable with the same name is defined in child scope, then, the child variable will shadow the outer variable in its own scope. This is known as shadowing and it holds true for all: let , const , var.
Most functional programming languages (like Haskell) support the concept of closure.
arguments object
arguments object can be used to access parameters passed to a function.
function hello(){
console.log(arguments[0]);
}
hello("Message");
// Output: Messagefunction func(){
console.log(arguments[0] + arguments[1] + arguments[2]);
}
func(5, 10, 15);
// Output: 30Note: Closure property is not valid for arguments object. It means that in a given scope, using argumentsobject, we can only access the parameters which was passed to the current function only, and not of outer functions.
this keyword
In C++, we can’t use this keyword outside object or inside static methods because those methods do not belong to any object.
In JavaScript, we can run this without class however.
In regular functions thethis keyword represents the object that called the function, which could be the window, the document, a button or whatever. If this is inside a function and the function is inside an object, it will refer to the object.
With arrow functions thethis keyword always represents the object that defined the arrow function.
Regular function:
function hello (){
console.log(this);
};
// if window object calls the function: // outputs window
// if button object calls the function: // outputs buttonArrow function:
let hello = "";
hello = () => {
console.log(this);
}
// if window object calls the function: // outputs window
// if button object calls the function: // still outputs window
// because the arrow func was
// defined at windowxAnother example:
Regular function:
function func1 (){
console.log(this);
};
let obj1 = {
x : func1
};
obj1.x();
// obj1.x is a function, which can be called
// this inside regular function - - > refers to object where it was called
// Code above outputs: { x: [Function: func1] }
// which is nothing but obj1Arrow function:
let func2 = () =>{
console.log(this);
}
let obj2 = {
y: func2
}
obj2.y(); // Outputs Window, the obj where the arrow func was definedIf there was something like obj.b.func() then this inside func would point to object b.
Equality in JavaScript
Abstract Equality Comparator ( == )
Checks value of data types. If data types are different then typecasting is performed to change the data types to a common data type and then values are checked.
Note: Usually in different data types, things get converted to integer or to Primitive in case of Objects.
Exception to keep in mind:
console.log( '5' + 1 ); // expected 6, but outputs 51Because + (plus symbol) is overloaded in javascript to work like this only. Otherwise, string usually gets converted to integer, when working with integers.
For example:
console.log('5' - 1); // 4
console.log('5' * 2); // 10Examples of Abstract Equality Comparator:
0 == ''; // Evaluates to trueExplanation of above example: Empty string upon conversion to number gives 0.
Number(''); // This will output 0.Another example:
false == 'false'; // Evaluates to falseSince the data types are different (boolean and string), Abstract Equality Comparator tries to convert both of them into a common data type.
boolean false gets converted to integer 0.
Whereas, string 'false' getsconverted to NaN (Not a number) because any non-empty string when converted to integer gives NaN.
Since, 0 is not equal to NaN. Our answer is false.
Note: Any whitespace like '' , '\n' , '\t' when converted to number, gives 0. But when comparing them using == , they are treated as single character string literal (although '\n' and '\t' are escape sequences) and thus since they get treated as same data types and their values as different. So, the following examples evaluate to false:
'' == '\n'; // false
'' == '\t'; // false
'\n' =='\t'; // falsea==b and b==c , doesn’t implie that a==c in JavaScript. This is Non Transitive property.
Strict Equality Comparator ( === )
Checks for both value and type. No conversion takes place.
0=== ''; // Evaluates to false. Since their type is different.Comparing Arrays
In JavaScript, values in Primitive Data Type is Actual Value. Whereas, values in Non-Primitive Data Type is a Pointer which points where the data is.
Arrays and Objects are Non-Primitive data types.
[1,2] == [1,2] // Evaluates to falseThe above example evaluates to false, because LHS represents an array and RHS represents another array. These two arrays are different. When we perform comparison, the values don’t get compared but the pointers for these two arrays. Since, these are two different arrays, there pointers are different.
But if we do like:
let arr = [1, 2] ;
let arr2 = arr ;
arr2 == arr ; // Evaluates to true because now the pointers are pointing at the same locationIn fact, whenever arr_a == arr_b , it means we are talking about the same array. Or if obj_a == obj_b , it means we are talking about the same object.
Object Inheritance
let obj1 = {
a: 10,
b: 20
};
let obj2 = Object.create(obj1) ; // OBJECT TO OBJECT INHERITANCE
// CREATES A NEW EMPTY OBJECT obj2
// obj2 IS INHERITING FROM obj1
obj2 == obj1; // Evaluates to false. Since, these are different objects.__proto__
Points to the original object from which we inherited. __proto__ is only to be used for debugging purposes and never for production code.
Get Sriram’s stories in your inbox
Join Medium for free to get updates from this writer.
In the above example if we do:
obj2.__proto__ == obj1; // Evaluates to true.
obj2.a ;
// tries to find a in obj2.
// if not found, will try to find in obj2.__proto__
// if not found, will try to find in obj2.__proto__.__proto__
// goes on, until __proto__ becomes nullNote: Every object has a default __proto__ of its own.
So if we have obj1 in global scope and we created obj2 inheriting from it.
obj2.__proto__ is obj1.
obj2.__proto__.__proto__ is default __proto__ of obj1 , which is not Null.
obj2.__proto__.__proto__.__proto__ will be null.
Example to understand how obj2 can access elems of obj1 but don’t have them on its own:
let obj1 = {
a: 10,
b: 20
} ;
let obj2 = Object.create(obj1) ; // obj2 inherits from obj1
obj2.c = 30 ;
obj2.d = 40 ;
let obj3 = Object.create(obj2) ; // obj3 inherits from obj2
// obj1 - - > Object { a : 10 , b : 20 }
// obj2 - - > Object { c : 30 , d : 40 }
// obj3 - - > Object { }
// Even though obj3 is empty. We can access c, d, a, b from it
console.log(obj3.d) ; // Output: 40What if obj1 has key a in it and in obj2 we add another key a?
Will it shadow the a of obj1? Yes it will.
Example to understand it:
// Suppose, obj1 is - - > { a : 10 }
// And obj2 is a blank object which inherits from obj1.
// obj2 - - > { }
obj2.a ; // Will output 10 as we understood in the earlier example.
// But what if we do this?
obj2.a ++ ;
// It means: obj2.a = obj2.a + 1 ;
// So, obj2.a = 10 + 1
// Now what happens is that in obj2 'a' gets created.
// obj2 - - > { a : 11 }
// obj1 - - > { a : 10 }These functions are in window object having global scope which converts any input to the corresponding type:
String , Boolean , Number , Array , Object , Function.
For e.g.
String(22); // '22'
Number('22'); // 22
let f = Function(); // Creates an empty Anonymous function
// Similar to - - > // let f = function ()
Array(5) // An array created with 5 empty slots
Array(2, 4, 6) // [2, 4, 6]
// To create an Array with one numeric value:
let x = Array (1) ;
x[0] = 5 ;
// To create an Array with one value which is not numeric, we can create directly
Array (true) ;
// or,
Array ("meow") ;Note: Look at the below example:
let str = String();
let obj = Object();
console.log(str.__proto__.__proto__ == obj.__proto__); // trueOther than Object , if we would have used any other function like Number , Boolean , Array , Function , in place of String in the above example, it would still give the same result.
It means that all those functions inherit from Object.prototype and Object.prototype inherits from Null.
i.e.
All strings created using String() inherit from String.prototype
All numbers created using Number() inherit from Number.prototype
All booleans created using Boolean() inherit from Boolean.prototype and so on.
And String.prototype , Number.prototype , OBoolean.prototype , etc. they all inherit from Object.prototype
Que. String , Boolean , Number etc. are functions but we don’t see them contain prototypes. Where are they defined and how were we able to use String.prototype etc.?
Ans. All of them are functions. And all functions are objects. And object can have key value pairs. And we can add values in objects later on also.
Example:
function func1 () {
console.log( "A random function" ) ;
}
func1.a = "10"; // This is validSimilarly, prototype can be added in String , Number , Boolean etc. later on.
Note: Any object which inherits from Function.prototype can be called with parantheses.
Important points:
Que. What will be the output of this?
typeof Object.create(Boolean.prototype);Ans. We can guess that our answer is something which inherits from Boolean.prototype and as we saw earlier, booleans inherit from Boolean.prototype. So, we expect the answer to be boolean. But we get answer: object.
Learning 1: If two entities have same .__proto__ it doesn’t mean, that we will get same output when we do typeof on them.
Learning 2: Object.create() only creates object.
let x = Object.create (Boolean.prototype) ;
x.__proto__ == bool.__proto__ ; // true
typeof x == typeof bool ; // falseResults of typeof are limited: String , Boolean , Number , Object , Function.
Array also comes in Object.
If we can reach the scope where a built-in function is defined. We can re-define it.
Example:
let str = String(222222);
let str2 = String(333333);
console.log(typeof str.charAt(4)) ; // string
console.log(typeof str.charAt) ; // function
// Attempting to redefine the default function
str.charAt = function ( ) { return 'a' ; } // Doesn't work
console.log ( str.charAt == str2.charAt ) ; // Gives true
/*
It means that str.chatAt and str2.chatAt is pointing to same function.
So, function charAt is definitely not present in either str or str2,
otherwise any other would not have been able to access it.
So, we use .__proto__ to find where charAt is defined
On console we write:
str.__proto__.charAt ; // gives something
str.__proto__.__proto__.charAt ; // gives undefined
It means the function is in str.__proto__, which is String.prototype.
Now, we can change the definition:
*/
String.prototype.charAt = function () {
return ' x ' ;
}
// The code above works.But the following code doesn’t work. Even though str.__proto__ == String.prototype
str.__proto__.charAt = function() {
return 'x';
}Explanation: __proto__ sometimes doesn’t work as intended because as we noted earlier, it is only to be used for debugging purposes and never for production code.
Similarly, default functions of String like slice , splice , replace , substr can be redefined from String.prototype. And Array.prototype or Number.prototype can be used to redefine default functions of Array or Number .
Example of storing definition of an existing function of Array into a separate variable and redefining it:
// Declaring new function joinOriginal and giving it the existing definition of join
Array.prototype.joinOriginal = Array.prototype.join;
// Changing the definition of join
Array.prototype.join = function () {
console.log('Join called on', this);
return this.joinOriginal(...arguments);
}To release memory being used by a variable, we use delete keyword.
window.x = 10 ;
console.log (x) ; // 10
delete window.x ;
console.log (x) ; // undefinedClasses
Introduced in ECMA Script 2015 (popularly known as ES 6). It is syntactic sugar : just to aid people coming from C++/Java background. It’s not a new feature. It adds support for new syntax. If classes are removed from language, there would be no effect on the functionalites of the language.
typeof Class is function.
If a is inherited from a function/class:a.__proto__ is equal to (class/fn from where a is defined/inherited).prototype
But if a is inherited from a regular object:a.__proto__ is equal to obj from where a is inherited
Example:
class Person {
constructor (a, b) {
this.name = a ;
this.age = b ;
}
};
let p = new Person ('John Doe' , 23) ;
console.log(p.__proto__ == Person.prototype); // true
console.log(p.__proto__.__proto__ == Object.prototype); // trueWhen we create a class, a prototype of the class is also created, which inherits from Object.prototype. And the object of the class inherits from that created prototype.
Inside a class, we can define a function, without using function keyword.
Example:
class Person {
constructor (name , age) {
this.name = name ;
this.age = age ;
}
isAdult () { // see this
return this.age >= 18 ;
}
} ;
let p1 = new Person ( 'kamal' , 27 ) ;
console.log (p1.isAdult()) ; // true
let p2 = new Person ( 'meow', 17 ) ;
console.log (p2.isAdult()) ; // falseInheritance in JS
class Person {
constructor (name , age) {
this.name = name ;
this.age = age ;
}
isAdult () {
return this.age >= 18 ;
}
} ;
class Student extends Person {
constructor (name, age, grade){
// Mendatory to call super() in subclass constr and ABOVE `this`
super (name, age) ;
this.grade = grade ;
}
} ;
let s1 = new Student ("Harry Potter", 13, 5) ;
let s2 = new Student ("Harri Puttar", 14, 6) ;
s1.isAdult() ; // Outputs false. It is to be noted that JS doesn’t support Class to Class inheritance. So how did inheritance take place in the above example?
The answer is due to the relationship between their prototypes, not because of Class to Class inheritance.
s1.__proto__ // Student.prototype
s1.__proto__.__proto__ // Person.prototype
s1.__proto__.__proto__.__proto__ // Object.prototype







