Javascript Concepts
Javascript Concepts
Operator Precedence
Scope and Hoisting
Difference between for/in and for/of loops
for/in loop
for/of loop
Tagged Template Literals
Javascript Symbols
Objects and Constructors
Default functions on a ‘Function’ object
call() Function
apply() Function
call() vs apply()
bind() Function
this Keyword
... Operator
String to Array
Copy an Array of Primitives
Copy an Array of Objects
Concatenate Arrays
Pass parameters to a Constructor
Shallow Copy on Object Literals
Prototypes & Constructor Functions
Inheritance Chains
Javascript Classes
Closures
Type Arrays
Array Buffer
View
Typed Arrays vs Standard Arrays
ECMA Script 6 (ES6)
New Data Collections
Sets
Weak Sets
Maps
Javascript Concepts 1
Weak Maps
Javascript Modules
Iterators & Iterable
Generator Functions
Yield Delegation
Early Completion of a Generator Function
Error Handling
Javascript Security
Loose Comparison Vulnerability
Code Injection Attack
Points of Attack
Impact of Attack
Things to do
Prototype Pollution
Possible Fixes
Promises in JavaScript
Promises Terminology
Prototype Methods for Promises
Promise Methods
The for await of loop
Operator Precedence
MDN Docs
Global
Function
The functions and variables (declared using var ) can be declared after usage
due to ‘hoisting’. It happens because JS Engines parse the JS files first, and
execute them later. The initial parse lets the JS know where the function
exists.
Javascript Concepts 2
lets the JS Engine know that variables have to be necessarily
'use strict'
'use strict';
const product = {
productId: 120,
name: 'Product Name',
cost: 122.7,
price: 198.4,
calculateProfit: () => this.price - this.cost
};
for/of loop
It iterates over the value of an array or a string an returns the objects inside them.
'use strict';
const products = [
{
productId: 120,
name: 'Product Name 0',
cost: 122.7,
Javascript Concepts 3
price: 198.4,
calculateProfit: () => this.price - this.cost
},
{
productId: 121,
name: 'Product Name 1',
cost: 234.5,
price: 367.9,
calculateProfit: () => this.price - this.cost
},
{
productId: 122,
name: 'Product Name 2',
cost: 97.6,
price: 100,
calculateProfit: () => this.price - this.cost
}
];
'use strict';
Javascript Concepts 4
const highlightedText = (strings, ...values) => {
let final = '';
for (let i = 0; i < strings.length; i++) {
if (i > 0) {
final += `<b>${values[i-1]}</b>`;
}
final += strings[i];
}
return final;
}
Javascript Symbols
let symbol = Symbol("label");
let sameSymbol = Symbol.for("label");
let differentSymbol = Symbol('label');
Always hidden.
Not completely hidden since the Object also has a getPropertySymbol() method.
Javascript Concepts 5
Objects and Constructors
Every Object type has a constructor by default.
If you try to print what it is, it will then print the constructor signature.
console.log(sayHi.call(person1));
console.log(sayHi.call(person2));
Javascript Concepts 6
apply() Function
Same as call
// 3 ways to call
introduction('John', 'student');
introduction.apply(undefined, ['John', 'student']);
introduction.cal(undefined, 'John', 'student');
call() vs apply()
Use apply() only if the arguments are similar, related and/or already in an
array.
bind() Function
Used when we need to use the same function with a different context, but we
do not wish to change the context of the original function like we did with
call() and apply() .
It copies the Function object, binds it to the new object context, and returns
the value.
const person1 = {
name: 'Mary'
getName: () => this.name;
};
const person2 = {
name: 'John'
Javascript Concepts 7
};
this Keyword
Refers to the owner object in case of a method.
Refers to the Global Object in case of a function. BUT ONLY IF ‘use strict’ is
disabled.
... Operator
Expands any iterable object like a String or an Array.
NOT SUPPORTED BY IE or Edge (Edge thing must’ve changed, since they now
work on Chromium).
String to Array
const message = 'This is a random string';
console.log(characters);
Javascript Concepts 8
Copy an Array of Primitives
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
💡 The array is copied. But the underlying objects are not. So if you modify
anything in the existing Object, the original array will also reflect the
change. However, changes to the array will not be propogated.
Concatenate Arrays
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
Javascript Concepts 9
const object1 = {
a: 1,
b: 'b',
c: 1234.6
};
An Object prototype is the object instance from which the object is inherited.
The above two definitions mean that the prototype for both a Function as well
as an Object are actually objects placed in memory. In fact, the function’s
prototype object, becomes the prototype for all object instances created from
it.
Javascript Concepts 10
}
}
Inheritance Chains
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
Object.defineProperty(this, 'fullName', {
get: () => this.firstName + ' ' + this.lastName,
enumerable: true
});
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Javascript Classes
Javascript Concepts 11
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get fullName() {
return this.firstName + ' ' + this.lastName;
}
set fullName(fullName) {
let nameTokens = fullName.split(' ');
this.firstName = nameTokens[0];
this.lastName = nameTokens[1];
}
isAdult() {
return this.age >= 18;
}
}
static fromPerson(person) {
return new Student(perons.firstName, person.lastName, pe
}
enroll(courseId) {
this._enrolledCourses.push(courseId);
}
Javascript Concepts 12
getCourses() {
return this.fullName + ' is enrolled in ' + this._enroll
}
}
Closures
A property for Immediately Invoked Function Expressions (IIFE).
console.log(greeting.getMessage());
Javascript Concepts 13
console.log(counter2()); // 10
console.log(counter2()); // 11
Type Arrays
Array like objects which allow us to access the raw, binary data.
Lots of APIs support them (WebGL, Canvas, Web Audio, Fetch API, et cetera).
Array Buffer
View
Javascript Concepts 14
let testBuffer = new ArrayBuffer(16); // Buffer of 16 bytes
Javascript Concepts 15
view4.setInt8(1, 52);
Weak Sets
Can only contain Objects.
No size property.
Not iterable.
Javascript Concepts 16
💡 The main reason for using a Weak Set is to allow objects that are not
going to be used in the future to be Garbage Collected. Sets don’t allow
that.
Maps
Iterates faster than an Object.
Can have any data type as a key (Object can only have simple data types).
Weak Maps
Keys must be Objects.
Not iterable.
Javascript Modules
Moving data outside of HTML files isn’t enough.
Javascript Concepts 17
Considerations
1. Modules are Singletons.
4. One Module per file (This is why we need a bundler like webpack to
bundle them all up into 1 file)
Exporting Modules
Named Exports
Javascript Concepts 18
const abc = "This is a string";
const def = () => "This is a function";
Default Exports
Aggregating Modules
Importing Modules
Enable Modules
Default Imports
Javascript Concepts 19
Named Imports
Generator Functions
A function that can be paused and resumed at a later time, while having the
ability to pass values to and from the function at each point.
const obj = {
*gen(params) {...}
};
Javascript Concepts 20
The yield keyword is used to signal the pause point to a generator function.
Example
Yield Delegation
Javascript Concepts 21
Allows one host generator to control the iteration of a different generator function
(Can be thought of as ‘composing’ generator functions).
Error Handling
Javascript Concepts 22
Javascript Security
Loose Comparison Vulnerability
Javascript Concepts 23
Do not use == . Always use === .
Javascript Concepts 24
Points of Attack
Impact of Attack
Javascript Concepts 25
Javascript Concepts 26
Things to do
Javascript Concepts 27
Prototype Pollution
Javascript Concepts 28
💡 Java classes do not have static relations. They’re just syntactic sugar on
top of the old Prototype Chain setup logic.
Possible Fixes
Javascript Concepts 29
Promises in JavaScript
A Promise represents the eventual completion (or failure) of an Asynchronous
operation and its resulting value.
Promises Terminology
Fulfilled/Resolved: The promise succeeded. The resolve callback or the
Promise.resolve() method is called usually.
Javascript Concepts 30
.catch()
.finally()
Appends a handler.
💡 The .then() call gets the result of the previous promise. We can use this
to chain Promises together. Every single .then() call will have the results
of the previous .then() call.
Promise Methods
: It simply resolves the Promise and returns whatever you
Promise.resolve()
Promise.all()does not return unless all the promises have moved to a settled
state, then returns the results in the same order in which they were passed.
Javascript Concepts 31
The for await of loop will fire off all the asynchronous functions at the same
time, and will begin to handle them one at a time in the order in which they
return. So it does not wait for all the operations to finish running before it
begins to process them.
const getAsyncOperationResults = [
async () => await asyncFunction1(),
async () => await asyncFunction2(),
async () => await asyncFunction3()
];
Javascript Concepts 32