Skip to main content

The JavaScript Cheatsheet you need in 2020

 

  • This value (context): in a regular function, the value of this has nothing to do with the class on which it was defined; instead, it depends on the object that it was called upon; inside an arrow function this value always equals the this value from the outer function
  • Constructors: regular functions can easily construct objects, while an arrow function cannot be used as a constructor
  • Arguments object: is a special array-like object containing the list of arguments with which the function has been invoked, inside an arrow function the arguments object is resolved lexically: it accesses arguments from the outer function
  • Implicit return: regular functions use the return expression statement — otherwise it will just return undefined, while with arrow functions, if they contain one expression and the function’s curly braces are missing, then the expression is implicitly returned
  • Read more
  • this keyword refers to an object, that object which is executing the current bit of javascript code
  • Every javascript function while executing has a reference to its current execution context, called this — execution context means here is how the function is called
  • To understand this keyword, only we need to know how, when and from where the function is called, does not matter how and where function is declared or defined
  • Read more & see examples
  • Callback: a function which is accessible by another function and invoked after the first function — if that first function completed
  • Read more about callbacks
  • Closure: are created whenever a variable that is defined outside the current scope is accessed from within some inner scope — it gives you access to an outer function’s scope from an inner function
  • To use a closure, simply define a function inside another function and expose it
  • Read more about closures
  • A function that was declared without any function named identifier to refer to it — it is usually not accessible after its initial creation. These functions are created at run time
  • Read more
  • Functions that receive a function as an argument or return a function as output
  • For example, Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are some of the Higher-Order functions built into the language.
  • More here
  • Strict mode enables more rigorous error-checking in your code and makes debugging easier
  • You enable strict mode by adding “use strict”; at the beginning of the file
  • Read more
  • Scope: in a promise, only the promise chain is asynchronous — doesn’t block the execution; with async/await the entire wrapper function is asynchronous
  • Logic: in a promise, synchronous work can be handled in the same callback, and multiple promises can be handled using Promise.all; with async/await the synchronous work needs to be placed outside the callback, and multiple promises can be handled with more simple variables
  • Error handling: Promises: then, catch, finally; Async/await: try, catch, finally
  • See examples here
  • The difference between immutable and mutable: if an item is mutable, when changing the value of the reference variable it will also affect the value of the original referenced variable
  • Primitive data types such as numbers, strings, and Booleans are immutable — it is impossible to change values of those types by changing the reference — you can combine them and derive new values from them, but when you assign a specific value, that value will always remain the same; you can make a variable name point to a new value, but the previous value is still held in memory
  • Mutable is a type of variable that can be changed by its reference — in JS only objects and arrays are mutable: you can change their properties; for example: causing a single object value to have different content at different times
  • Read more and see examples
  • The values are associated with values and not with variables — it can be static or dynamic
  • Static: the variable can hold only one type, like in Java: a variable declared of string can take only a set of characters and nothing else
  • Dynamic: the variable can hold multiple types — like in JS: a variable can take number, chars, etc
  • JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function)
  • JavaScript only hoists declarations, not initializations
  • A simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements
  • Using event delegation it’s possible to add an event handler to an element, wait for an event to bubble up from a child element and easily determine from which element the event originated
  • Examples
  • By using them you can explicitly determine what this should refer to
  • bind can be particularly helpful when you want to use events to access properties of one class within another class
  • call and apply are very similar — they invoke a function with a specified this context, and optional arguments
  • The only difference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array
  • Read more and see examples
  • Objects can be divided into these two main categories, depending on the environment and language
  • Host objects: environment specific — ex. Browser supplies certain objects such as window, node supplies NodeList, etc.
  • Native / Built-in objects: standard objects provided by JS — sometimes referred to as global objects; JS is mainly constructed by these categorized native objects (String, Number, etc)
  • Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions — it returns a new function that expects the next argument inline
  • Transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c )
  • It allows us to easily get partials, avoid passing the same variable multiple times
  • It creates nesting functions according to the number of the arguments of the function so each function receives an argument: if there is no argument, there is no currying.
  • Read more
  • Read more 2
  • In most browsers there is an event loop for every browser tab, to make every process isolated and avoid a web page with infinite loops or heavy processing to block your entire browser
  • The environment manages multiple concurrent event loops, to handle API calls
  • Web Workers run in their own event loop as well
  • You mainly need to be concerned that your code will run on a single event loop, and write code with this thing in mind to avoid blocking it
  • Any JavaScript code that takes too long to return back control to the event loop will block the execution of any JavaScript code in the page, even block the UI thread, and the user cannot click around, scroll the page, and so on
  • Read more
  • Event propagation is a mechanism that defines how events propagate or travel through the DOM tree to arrive at its target and what happens to it afterward
  • In modern browser event propagation proceeds in two phases: capturing, and bubbling phase
  • Capturing: events propagate from the window down through the DOM tree to the target node — only works with event handlers registered with the addEventListener() method when the third argument is set to true
  • Bubbling: In this phase event propagates or bubbles back up the DOM tree, from the target element up to the window, visiting all of the ancestors of the target element one by one — supported in all browsers, and it works for all handlers, regardless of how they are registered e.g. using onclick or addEventListener()
  • Read more
  • Browser storage: data is never transferred to the server & can only be read on client-side; storage limit is about 5MB
  • Session vs local storage: session is only temporary — data is stored until tab/browser is closed; local doesn’t have an expiration date
  • Cons for storage: not secure, limited to strings, danger for XSS
  • Cookie: stores data with expiration date, storage limit about 4KB, is sent to the server for each request, read/write on both client & server side (if HttpOnly then it is inaccessible to client-side scripts)
  • Content Security Policy (CSP) is an HTTP header that allows site operators fine-grained control over where resources on their site can be loaded from.
  • The use of this header is the best method to prevent cross-site scripting (XSS) vulnerabilities.
  • Due to the difficulty in retrofitting CSP into existing websites, CSP is mandatory for all new websites and is strongly recommended for all existing high-risk sites.
  • Read more
  • Cross-Site Scripting (XSS) is an attack that occurs when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user
  • The page provided by the server when someone requests it is unaltered; instead, an XSS attack exploits a weakness in a page that include a variable submitted in a request to show up in raw form in the response
  • Read more about attacks
  • Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin
  • A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own
  • Read more

If you feel like some questions are missing and think they should be there, or if you would like to share your feedback please let me know in the comments!

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape ge

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component