Posts

Showing posts from 2017

What is Closure ?

Image
A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function’s scope, and (3) global variables. Here is an example : var globalVar = "xyz"; (function outerFunc(outerArg) { var outerVar = 'a'; (function innerFunc(innerArg) { var innerVar = 'b'; console.log( "outerArg = " + outerArg + "\n" + "innerArg = " + innerArg + "\n" + "outerVar = " + outerVar + "\n" + "innerVar = " + innerVar + "\n" + "globalVar = " + globalVar); })(456); })(123); In the above example, variables from innerFunc , outerFunc , and the global namespace are all in scope in the innerFunc . The above code will therefore produce the following output: out

What is IIFE in Javascript ?

An  IIFE  is an anonymous function that is created and then immediately invoked. It's not called from anywhere else (hence why it's anonymous), but runs just after being created. It has nothing to do with any event-handler for any events (such as  document.onload ). The first pair of parentheses  ( function(){...} )  turns the code within (in this case, a function) into an expression, and the second pair of parentheses  (function(){...}) ()  calls the function that results from that evaluated expression. This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other  normal  function) are not visible outside its scope. ( function (){ // all your code here // ... })(); // foo is unreachable here (it’s undefined)

Defining Constant in Javascript

Prior to javascript ES6, there was no way to define constants, so one have to write their own custom way to write constants. So, here are two ways to define constant that are mutable i.e, which can'nt be reassigned. 1. Using Const (ES6) : - const MAX_NUM = 10; This  const  means that you can't reassign it to any other value. Check the  compatibility notes  to see if your targeted browsers are supported. 2. Using defineProperty And we can use throughout our application. (function() {     var locarVar;     Object.defineProperty(window, ' MAX_NUM ', {         get: function() {             return locarVar;         },         set: function(val) {             locarVar = window. MAX_NUM  || val;         }     }); }()); MAX_NUM = 10; MAX_NUM = 12; //  Cannot redefine property: MAX_NUM console.log(MAX_NUM); // 10

Immutable Objects with Javascript

We create immutable objects, so that no one can change during the app's lifecycle. By default, all Javascript types, except objects, define immutable values Now what happen, when you copy an object obj1 into another object obj2 , & then when you change/add/remove property from obj1 , it also affected original object obj1 . E.g : var obj1 = { a : 5, b :  7 }; var obj2 = obj1; obj2.a  = 7; //console.log(obj1); => { a : 7, b : 7} For overcoming these javascript behaviour or to create Immutable objects which doesn't mutate cloning, we have following ways : - 1. This Simple Hack : - var obj2 = JSON.parse(JSON.stringify(obj1)); Now, obj2.a  = 7; //console.log(obj1); => { a : 5, b : 7} 2.  Object.definePropety()   Using Javascript's defineProperty we can create non configurable and/or hidden properties inside objects. This way we can be sure that a developer can't mess with our code or hide from them info about our structures that they don'

Inheritance in Javascript (ES6)

INHERITANCE : The  extends  keyword is used in  class declarations  or  class expressions  to create a class which is a child of another class. class ChildClass extends ParentClass { ... } The  extends  keyword can be used to subclass custom classes as well as built-in objects. The  .prototype  of the extension must be an  Object  or  null . Examples : -  Using  extends -  Please click on this link   https://googlechrome.github.io/samples/classes-es6/index.html  for a better example. Using  extends  with built-in objects -  class myDate extends Date { constructor ( ) { super ( ) ; } getFormattedDate ( ) { var months = [ 'Jan' , 'Feb' , 'Mar' , 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug' , 'Sep' , 'Oct' , 'Nov' , 'Dec' ] ; return this . getDate ( ) + '-' + months [ this . getMonth ( ) ] + '-' + th

Constructor in Javascript ES6

CONSTRUCTOR : constructor([arguments]) { ... } The  constructor  method is a special method for creating and initializing an object created with a  class .  There can only be one special method with the name "constructor" in a class. A Syntax error will be thrown, if the class contains more than one occurrence of a constructor  method. A constructor can use the  super  keyword to call the constructor of a parent class. If you don't specify a constructor method, a default constructor is used. Example : -  Please click on this link   https://googlechrome.github.io/samples/classes-es6/index.html  for a better example.

Static methods in Javascript ES6

Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility functions. Calling static methods  1. From another static method : In order to call a static method within another static method of the same class, you can use the  this  keyword. class StaticMethodCall { static staticMethod ( ) { return 'Static method has been called' ; } static anotherStaticMethod ( ) { return this . staticMethod ( ) + ' from another static method' ; } } StaticMethodCall . staticMethod ( ) ; // 'Static method has been called' StaticMethodCall . anotherStaticMethod ( ) ; // 'Static method has been called from another static method' 2.  From class constructor and other methods :  Static methods are not directly accessible using the  this  keyword from non-static methods. You need to call them using the class name:  CLASSNAME.STATIC

How can you secure your HTTP cookies against XSS attacks?

XSS occurs when the attacker injects executable JavaScript code into the HTML response. To mitigate these attacks, you have to set flags on the  set-cookie HTTP header: HttpOnly  - this attribute is used to help prevent attacks such as cross-site scripting since it does not allow the cookie to be accessed via JavaScript. secure  - this attribute tells the browser to only send the cookie if the request is being sent over HTTPS. So it would look something like this:  Set-Cookie: sid=<cookie-value>; HttpOnly . If you are using Express, with  express-cookie session , it is working by default.

What is the difference between sessionstorage, localstorage and Cookies?

sessionStorage, localStorage and Cookies all are used to store data on the client side. Each one has its own storage and expiration limit. localStorage : stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data or manually deletion. sessionStorage : similar to localStorage but expires when the browser closed (not the tab). Cookie : stores data that has to be sent back to the server with subsequent requests. Its expiration varies based on the type and the expiration duration can be set from either server-side or client-side (normally from server-side). Cookies are primarily for  server-side  reading (can also be read on client-side), localStorage and sessionStorage can only be read on  client-side.

Why is node.js not suitable for heavy CPU apps?

Node is, despite its asynchronous event model, by nature single threaded. When you launch a Node process, you are running a single process with a single thread on a single core. So your  code  will not be executed in parallel, only I/O operations are parallel because they are executed asynchronous. As such, long running CPU tasks will block the whole server and are usually a bad idea. Given that you just start a Node process like that, it is possible to have multiple Node processes running in parallel though. That way you could still benefit from your multithreading architecture, although a single Node process does not. You would just need to have some load balancer in front that distributes requests along all your Node processes. Another option would be to have the CPU work in separate processes and make Node interact with those instead of doing the work itself.