0% found this document useful (0 votes)
17 views

Javascript Concepts

Uploaded by

catika9594
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Javascript Concepts

Uploaded by

catika9594
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

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

Scope and Hoisting


Only two scopes:

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.

Traditional, undeclared variables are actually appended to the window object.

Javascript Concepts 2
lets the JS Engine know that variables have to be necessarily
'use strict'

declared, and to not append stray variables to window . It is ignored by older


browsers.

Difference between for/in and for/of loops


for/in loop
It iterates over an object and returns the keys present in it.

'use strict';

const product = {
productId: 120,
name: 'Product Name',
cost: 122.7,
price: 198.4,
calculateProfit: () => this.price - this.cost
};

for (const key in product) {


console.log("'" + key + "' = " + product[key]);
}

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
}
];

for (const product of products) {


console.log(JSON.stringify(product));
}

'use strict';

const message = 'This is a random string';

for (const char of message) {


console.log(char);
}

Tagged Template Literals

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;
}

const literalText = highlightedText `This is a ${highlightedText

Javascript Symbols
let symbol = Symbol("label");
let sameSymbol = Symbol.for("label");
let differentSymbol = Symbol('label');

console.log(symbol === sameSymbol); // true


console.log(symbol === differentSymbol); // false

They are unique.

Always hidden.

We can never find out why.

Can be used as keys in an object.

Useful if we want that property to be a secret, as they property will never


show up when we call getPropertyNames() on an Object.

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.

Comparing objects compares the memory addresses instead of values.

Default functions on a ‘Function’ object


call() Function

const person1 = { name: 'John', age: 22 };


const person2 = { name: 'Mary', age 19 };

const sayHi = () => 'Hi, ' + this.name;

console.log(sayHi.call(person1));
console.log(sayHi.call(person2));

Javascript Concepts 6
apply() Function
Same as call

Takes an array as an argument.

The array is then denatured to split into a list of arguments.

const introduction = (name, profession) =>


'My name is ' + name + ' and I am a ' + profession;

// 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.

Otherwise use call() .

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
};

const getNameCopy = person1.getName.bind(person2);


console.log(getNameCopy()); // John

this Keyword
Refers to the owner object in case of a method.

Refers to an empty object if it is run in a constructor function.

Refers to the Global Object in case of a function. BUT ONLY IF ‘use strict’ is
disabled.

Refers to the receiving element in case of an event.

Refers to the reference of the object passed, if call() or apply() is used.

... Operator
Expands any iterable object like a String or an Array.

Used to pass multiple arguments to a function.

Always used on right side of the = in an expression.

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';

const characters = [...message];

console.log(characters);

Javascript Concepts 8
Copy an Array of Primitives
const arr1 = [1, 2, 3];
const arr2 = [...arr1];

Copy an Array of Objects

💡 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'];

const arr3 = [...arr1, ...arr2];

Pass parameters to a Constructor


const date1 = new Date(2022, 04, 04);

const dateFields = [2022, 04, 04];


const date2 = new Date(...dateFields);

💡 Same syntax for a normal function too.

Shallow Copy on Object Literals


Works the same way as the Object.assign() method.

Javascript Concepts 9
const object1 = {
a: 1,
b: 'b',
c: 1234.6
};

const object2 = { ...object1 };

Prototypes & Constructor Functions


A Function prototype is the object instance that will become the prototype for
all objects created using the function as a constructor.

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.

function Person(firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

const person = new Person('John', 'Doe');

console.log(Person.prototype === person.__proto__); // true

function Person(firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;
prototype: { // This edits the function's prototype
age: 29

Javascript Concepts 10
}
}

const person = new Person('John', 'Doe');

console.log(person.age); // 29 (It is the same for all Objects o

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
});
}

function Student(firstName, lastName, age) {


Person.call(this, firstName, lastNamge, age);
this._enrolledCourses = [];

this.enroll = courseId => this._enrolleCourses.push(courseId


this.getCourses = () => this._enrolledCourses;
}

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;
}
}

class Student extends Person {


constructor(firstName, lastName, age) {
super(firstName, lastName, age);
this._enrolledCourses = [];
}

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).

An IIFE is immediately cleaned up and moved out of scope upon execution.

A closure allows us to hold on to a reference even after execution.

const greeting = (function () {


let message = 'Hello';

let getMessage = () => message;

return { //This object will get assigned to greeting


getMessage: getMessage
}
})();

console.log(greeting.getMessage());

A more useful example would be:

const setupCounter = val => () => val++;

const counter1 = setupCounter(0);


console.log(counter1()); // 0
console.log(counter1()); // 1

const counter2 = setupCounter(10);

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.

Faster performance than regular array.

Lots of APIs support them (WebGL, Canvas, Web Audio, Fetch API, et cetera).

Uses Array buffers and views to expose the data.

Array Buffer

let testBuffer = new ArrayBuffer(16); // Buffer of 16 bytes

View

Javascript Concepts 14
let testBuffer = new ArrayBuffer(16); // Buffer of 16 bytes

let view1 = new Int8Array(testBuffer);


view1[0] = 32;
console.log(view1); // Logs 16 different number, first is 32, ne

let view2 = new DataView(testBuffer); // Creates a Generic data


/* It actually uses the previous array we'd defined to set the d
This is because it's the same buffer as before */
view2.setInt8(2, 43);
console.log(view2.getInt8(0)); // Returns 32

// Only gives us 3 positions, starting from index 7


let view4 = new DataView(testBuffer, 7, 3);

Javascript Concepts 15
view4.setInt8(1, 52);

// Logs 16 different number, first is 32, 3rd is 43, 9th is 52,


console.log(view1);

Typed Arrays vs Standard Arrays

ECMA Script 6 (ES6)


New Data Collections
Sets
Ignores duplicates.

Weak Sets
Can only contain Objects.

No primitive data types.

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).

It can guarantee the Insertion order.

Inherits from an Object, so has all the properties of an Object.

Weak Maps
Keys must be Objects.

Not iterable.

Not enumerable (no size property).

Objects are held “weakly” (Allows Garbage Collection).

Javascript Modules
Moving data outside of HTML files isn’t enough.

The data is still available in the global scope.

To hide them without Modules, we’d need Immediately Invoked Function


Expressions (IIFE).

The IIFEs work, but are not readable.

Not supported by IE and the Samsung (Android) Web View.

Javascript Concepts 17
Considerations
1. Modules are Singletons.

2. Properties are bound to the module

3. Exports are static at runtime

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

export const abc = "This is a string";


export const def = () => "This is a function";

Javascript Concepts 18
const abc = "This is a string";
const def = () => "This is a function";

export {abc, def};

Default Exports

export const abc = "This is a string";


export default const def = () => "This is a function";

const abc = "This is a string";


const def = () => "This is a function";

export {abc as default, def};

Aggregating Modules

const abc = "This is a string";


const def = () => "This is a function";

export {abc as default, def};


export {namedImport} from './otherModule.js'

Importing Modules
Enable Modules

<script type="text/javascript" rel="script" src="app.js" t

Default Imports

import abc from './localModule.js';

Javascript Concepts 19
Named Imports

import { abc } from './localModule.js';


import { def as xyz } from './secondLocalModule.js';

Iterators & Iterable


Iterables must implement the @@iterator method.

Iterables must have a Symbol.iterator (it is a well known Javascript iterator).

Examples: Arrays, Sets, Maps, et cetera.

The for/of loop internally calls the Symbol.iterator

const arr = [1, 2, 3, 4, 5];


const it = arr[Symbol.iterator]();

console.log(it.next()); // { value: 1, done: false }

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.

function *generator {...}


function * generator {...}
function* generator {...}

const obj = {
*gen(params) {...}
};

Executing the generator function returns an iterator. When we call it.next() ,


the function begins to execute.

Javascript Concepts 20
The yield keyword is used to signal the pause point to a generator function.

Example

A possible use case for Generator Functions is to make externally cancellable


Async Calls.

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).

Early Completion of a Generator Function

Error Handling

Javascript Concepts 22
Javascript Security
Loose Comparison Vulnerability

Javascript Concepts 23
Do not use == . Always use === .

Always use 'use strict' .

Verify the type of untrusted data items.

Code Injection Attack

Javascript Concepts 24
Points of Attack

Impact of Attack

Javascript Concepts 25
Javascript Concepts 26
Things to do

Javascript Concepts 27
Prototype Pollution

Since class relations are static, they can’t change on Runtime.

Prototypes are dynamic, and can be changed.

Javascript Concepts 28
💡 Java classes do not have static relations. They’re just syntactic sugar on
top of the old Prototype Chain setup logic.

const user = { name: 'Full Name' };


const malicious = { isAdmin: true }; // Should not be set for al

user.__proto__ = malicious; // Prototype pollution. Leads to esc

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.

Rejected: The promise failed. The reject callback or the Promise.reject()

method is called usually.

Pending: The promise has not been fulfilled or rejected yet.

Settled/Done: The promise has either been fulfilled or rejected.

Prototype Methods for Promises


.then()

Appends a fulfilment handler to the Promise.

Returns a new Promise.

Javascript Concepts 30
.catch()

Appends a rejection handler to the Promise.

Returns a new Promise.

.finally()

Appends a handler.

This is always called.

Returns a new Promise.

💡 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()

pass into the Resolve method.

: It simply rejects the Promise and returns whatever you pass


Promise.reject()

into the Reject Method.

Promise.all() : It accepts a list of Promises, and runs them in parallel. It then


waits for all of them to be resolved, before returning an array of all the results.

💡 The Promise.all() function can be combined with the async/await


functionality to await the results of multiple asynchronous operations.

The for await of loop


We can use this call instead of Promise.all() when using the async/await type of
pattern. There’s a fundamental difference though.

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()
];

for await (const operationResult of getAsyncOperationResults) {


// Do Something
}

Javascript Concepts 32

You might also like