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

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...