Image for post
Image for post

JavaScript Compilation

The first interesting thing about this book is that it starts off by describing JavaScript as a “compiled” language. It explains that all JavaScript is compiled by the JavaScript “Engine” right before — even milliseconds before — it is executed.

It goes into the compilation process, which is something I know very little about.

The var a = 2; example was helpful. The JavaScript Engine will break down var a = 2;into a separate chunks characters, parse those chunks into what’s called an ‘abstract syntax tree’, then turn that tree into a set of machine instructions to actually create a variable called a (in the compilation phase) and later assign it the value of 2 (in the execution phase).

Undefined vs undeclared

var a;
a //undefined
typeof a // "undefined"
b //Uncaught ReferenceError: b is not defined
typeof b //"undefined"

null vs undefined

Null and Undefined are both data types in JavaScript.

Undefined is a variable that has been declared but NOT assigned a value.

Null as an assignment value.However, when you assign null to a variable, you are declaring that this value is explicitly empty.

To put it simply, JavaScript uses undefined and programmers should use null . you can also assign “undefined” to a variable, but it is NOT recommended.

Image for post
Data Types in JS
  • Javascript doesn’t support IMMUTABILITY, by default. However, it can be made to follow immutability in case of Objects and arrays using so called

concat(), slice(), filter(), map(), reduce(), Object.assign(),

…(spread Operator)

Arrays , Functions are objects

Arrays are Objects. Also, you can add a property to an array! Not that you would ever really need to do this, but still, it hammered home the point that arrays are objects.

Functions have a length

Because functions are objects, they can have properties. I literally had no idea that functions have a length property reflecting the number of parameters it is declared with. Kinda cool!

x = function () {}
x.length //0

y = function (a, b, c) {}
y.length //3

Why “0” is equal to false in JavaScript ?

source: https://www.geeksforgeeks.org/why-0-is-equal-to-false-in-javascript/

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

Hence, "0" == false # true

So, from above it is clear that “0” is equal to false and reason behind this behavior is also clear, but when “0” is tested in if condition then it evaluates to true.

Why “0” is not equal to false in if condition in JS ?

The reason behind this behavior is that JavaScript treats non-empty string as true. First, “0” is converted into its boolean value, by automatic type conversion which is true. Therefore, if statement executes.

Here are some examples — I’ll use pseudo code to demonstrate step-by-step how the coercion algorithm is applied:

Image for post
Image for post

When and why to ‘return false’ in JavaScript?

Return statements, in programming languages, are used to skip the currently executing function and return to the caller function. Return statements may/may not return any value.

Web Developers use ‘return false’ in different ways. During form submission, if a particular entry is unfilled, return false is used to prevent the submission of the form.

When to use PreventDefault( ) vs Return false in JavaScript?

In Javascript, there are two methods- preventDefault() and return false, that are used to stop default browser behaviour but their functionalities and uses are little different. This article shows how these two are different?

Use preventDefault(); if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM.

Map and Set

Now we’ve learned about the following complex data structures:

  • Arrays for storing ordered collections.
  • Objects for storing keyed collections.

But that’s not enough for real life. That’s why Map and Set also exist.

Map

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

  • Object: A data structure in which data is stored as key value pairs. In an object the key has to be a number, string, or symbol. The value can be anything so also other objects, functions etc. A object is an non ordered data structure, i.e. the sequence of insertion of key value pairs is not remembered.
  • ES6 Map: A data structure in which data is stored as key value pairs. In which a unique key maps to a value. Both the key and the value can be in any data type. A map is a iterable data structure, this means that the sequence of insertion is remembered and that we can access the elements in e.g. a for..of loop.

Key differences:

  • A Map is ordered and iterable, whereas an object is NOT ordered and NOT iterable.
  • We can put any type of data as a Map key, whereas objects can only have a number, string, or symbol as a key.
  • A Map inherits from Map.prototype. This offers all sorts of utility functions and properties which makes working with Map objects a lot easier.

For instance:

let map = new Map();map.set('1', 'str1');   // a string key
map.set(1, 'num1'); // a numeric key
map.set(true, 'bool1'); // a boolean key
// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
alert( map.get(1) ); // 'num1'
alert( map.get('1') ); // 'str1'
alert( map.size ); // 3As we can see, unlike objects, keys are not converted to strings. Any type of key is possible.

Iterables

Iterable objects is a generalization of arrays. That’s a concept that allows us to make any object useable in a for..of loop.

Of course, Arrays are iterable. But there are many other built-in objects, that are iterable as well. For instance, strings are also iterable.

If an object isn’t technically an array, but represents a collection (list, set) of something, then for..of is a great syntax to loop over it, so let’s see how to make it work.

In JavaScript, Object s are not iterable unless they implement the iterable protocol. Therefore, you cannot use for…of to iterate over the properties of an object. … keys or Object. entries , to iterate over the properties or entries of an object.

Of course, Arrays are iterable.

Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map , while other types (such as Object ) are not.

IIFEs

Did not realise that an IIFE can be written in two different ways! Super cool (though I prefer the first).

.call()

var foo = {num:1};
var add = function(noToAdd, noToAdd1){
return this.num + noToAdd + noToAdd1;
};
add.call(foo, 98 ,1); # 100

.apply()

var foo = {num:2};
var add = function(a, b, c){
return this.num + a + b + c;
};
var arr = [7,5,4];
add.apply(foo, arr); # 18

.bind()

var foo = {num:2};
var add = function(a, b, c){
return this.num + a + b + c;
};
var arr = [7,5,4];
var sum = add.bind(foo);
# above, sum returns a "bound" function which can be executed lated
sum(arr);
Image for post
Image for post
call vs bind vs apply
God.prototpye = human.__proto__;Child.prototype = Object.create(Father.prototype);Father.call(this, surname, property); # related to Prototypal inheritancesuper(surname, property); # related to Classical inheritance

.Object.create()

When we create Object using “Object.create”, the Object passed as parameter is added to the “prototype” chain of the newly created Object. When user try to access the property from the new Object created, it looks for the prototype chain available to the new Object. The JavaScript Object can traverse “prototype” chain using “__proto__” property.

The “userInfo” object passed to Object.create function was added to “__proto__” property of the new Object.

.reduce()

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Reducing an Array to the Sum of its Elements

Every programmer has had to do this at some point, and if you didn’t use reduce your solution probably looked something like this:

let arr = [1, 2, 3, 4, 5]
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
};
console.log(sum) // 15

Here is how you would do that using Array.reduce:

let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((prev, cur) => prev + cur, 0)
console.log(sum) // 15

First let’s just quickly identify what is going into the function. For reference, here is the definition of the Array.reduce:

Array.prototype.reduce(cb(prev, cur, idx, arr)[, initialValue])

Must read at https://medium.com/javascript-in-plain-english/what-is-array-reduce-4409d9706f27

sort Integers

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});

// Sort the numbers in the array in ascending order

Number to String / String to Number

// Amateur approach ❌
let x = 15;
let str = x.toString(); // number to string
let num = Number(str); // string to number
// Pro approach ✅
let x = 15;
let str = x + ""; // number to string
let num = +str; // string to number

inline if

// Amateur approach ❌
if(isActive){
callMethod1();
} else {
callMethod2();
}
// Pro approach ✅
isActive ? callMethod1() : callMethod2()

inline if else

// Amateur approach ❌
if(isActive){
console.log("not recommended");
}
// Pro approach ✅
isActive && console.log("recommended");

ternary operator

// Amateur approach ❌
let hungry = true;
let eat;
if(hungry === true){
eat = "yes";
} else {
eat = "no";
}
// Pro approach ✅
let hungry = true;
let eat = hungry === true ? "yes" : "no";
Image for post
Image for post

ARRAY to OBJECT

// Amateur approach ❌
let arr = ["val1", "val2", "val3"];
let arrObject = {};
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== undefined) {
arrObject[i] = arr[i];
}
}
// Pro approach ✅
let arr = ["val1", "val2", "val3"];
let arrToObject = { ...arr };

OBJECT to ARRAY

// Amateur approach ❌
let numbers = {
one: 1,
two: 2
};
let keys = [];
for (let number in numbers) {
if (numbers.hasOwnProperty(number)) {
keys.push(number);
}
}
// key = ["one", "two"]
// Pro approach ✅
let numbers = {
one: 1,
two: 2
};
let key = Object.keys(numbers); // key = ["one", "two"]
let value = Object.values(numbers); // value = [1,2]
let entries = Object.entries(numbers);
// entries = [ ["one" : 1], ["two":2] ]
Image for post
Image for post

check for an array

Here’s a Code Recipe to check whether a variable or value is either an array or not. You can use the Array.isArray() method. For older browser, you can use the polyfill.

const arr = ["1", "anil", "2", "kumar"];// newer browser
Array.isArray(arr);
// older browser
Object.prototype.toString.call(arr) === '[object Array]';

Last Item in an array

let arr = [0,1,2,3];
arr.slice(-1);
// [3];

Truncate an array

let arr = [0,1,2,3,4,5,6];
arr.length = 3;
//[0,1,2]

3 Ways to Remove Array Duplicates

const arr = [0,1,2,3,4,2,3];// 1.  "Set"
[...new Set(arr)]
// 2. "Filter"
arr.filter((item, index) => array.indexOf(item) === index);
// 3. "Reduce"
arr.reduce((unique, item) =>
unique.includes(item) ? unique : [...unique, item], []);
Image for post
Image for post

Capitalize the First Letter Of A String In JavaScript

string.charAt(0).toUpperCase() + string.slice(1);
Image for post
Image for post
Promises in JS
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
PROTOTYPES in JS
Image for post
Image for post
God.prototype === human.__proto__; //true
Image for post
Chrome Browser Architecture + V8 Engine
Image for post
Image for post
Normal Execution
Image for post
Image for post
Async: the file can be downloaded while the HTML document is still parsing. Once it has been downloaded, the parsing is paused for the script to be executed.
Image for post
Image for post
defer: even if the file is fully downloaded long before the document is finished parsing, the script is not executed until the parsing is complete.

In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user STOPS firing the event.

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be EXECUTED ONLY ONCE in a given time interval.

Image for post
Image for post
Closures in JS
Image for post
Image for post
CORS issue
Image for post
Image for post
Different ways to handle Asynchronous code in JS

Promises are generally used for easier handling of Asynchronous operations or blocking code, for example, file operations, API calls, DB calls, IO calls, etc. in the so called synchronous programming language called JavaScript.

Only in the promise constructor block you do not have to explicitly return a resolve/reject. Apart from that, in the consecutive then methods, every value and promise chained needs to be returned, for accessing it further down the block.

Async/await is a new way to write Asynchronous code. Previous alternatives for asynchronous code are callbacks and promises.

The word “async” before a function means one simple thing: a function always returns a promise.

◉ Concepts of Functional Programming:

  • Pure functions
  • Recursion
  • Immutability
  • High Order Functions + Functions are first class.
  • Referencial Transparency

◉ Characteristics of RESTFUL Api:

  • client-server
  • Stateless
  • Cacheable
  • supports both JSON & XML and others.

Memory leaks in JS:

  • Accidental GLOBAL variable
  • Closures
  • Lingering DOM references to Removed Elements

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store