Javascript stuff

by Admin 20. June 2018 01:21

Javascript

What is the Javascript threading model - what are the priorities?

JavaScript does not support multi-threading because the JavaScript interpreter in the browser is a single thread.

JavaScript is single-threaded in the same context, but browser Web APIs are not. 

Also we have possibility of simulating parallelism by using setTimeout function or, with some limitations, 

by the use of the real parallelism provided by WebWorkers.

Event loop

Initial code execution ends once the page is loaded and the initial JavaScript code has run, all event handlers are attached, all AJAX requests are sent and our observables are observing. Why then shouldn’t we just handle all the events we are subscribed to in old-fashioned parallel way? The reason is that we don’t want to change the DOM in parallel: this is because the DOM tree is not thread-safe and it would be a mess if we tried to do it. Because of this limitation, all our JavaScript code should be executed in single thread, while at the same time ensuring that it handles all the events and doesn’t lose any callback. For these reasons we come to the Event loop.

The event loop can be imagined as the following process flow:

ProcessFlow

As described in the picture, the main parts of JavaScript Event loop are:

  • The Call stack, which is a usual call stack that contains all called functions.
  • The Event handlers queue, a queue of event handlers that are waiting to be executed.
  • The Event loop, which is a process that checks whether events handlers queue is not empty and if it is – calls top event handler and removes it from queue.
  • The JavaScript Web APIs: those APIs that are provided by the browser that are responsible for filling the Event handlers queue, providing many features such as the ability to make an AJAX request

  

Does the javascript event loop affect a user typing some text in a textbox.

Event handlers make it possible to detect and react to events happening in our web page. The addEventListener method is used to register such a handler.

Each event has a type ("keydown", "focus", and so on) that identifies it. Most events are called on a specific DOM element and then propagate to that element’s ancestors, allowing handlers associated with those elements to handle them.

When an event handler is called, it is passed an event object with additional information about the event. This object also has methods that allow us to stop further propagation (stopPropagation) and prevent the browser’s default handling of the event (preventDefault).

Pressing a key fires "keydown" and "keyup" events. Pressing a mouse button fires "mousedown", "mouseup", and "click" events. Moving the mouse fires "mousemove" events. Touchscreen interaction will result in "touchstart", "touchmove", and "touchend" events.

Scrolling can be detected with the "scroll" event, and focus changes can be detected with the "focus" and "blur" events. When the document finishes loading, a "load" event fires on the window.

 

 What programming paradigm can you do using javascript?

JavaScript is a multi-paradigm language, supporting imperative/procedural programming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance.

Prototypal Inheritance (objects without classes, and prototype delegation, aka OLOO — Objects Linking to Other Objects), and

 Functional Programming (enabled by lambdas with closure)

 

What is map, reduce and filter (for arrays)

One of the key foundations of functional programming is its use of lists and list operations. In Javascript we have map, filter and reduce, all functions that given an initial list (array of things), transform it into something else, while keeping that same original list intact.

.map()

Let me explain how it works with a simple example. Say you have received an array containing multiple objects – each one representing a person. The thing you really need in the end, though, is an array containing only the id of each person.

// What you have
var officers = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

// What you need
[20, 24, 56, 88]

There are multiple ways to achieve this. You might want to do it by creating an empty array, then using .forEach().for(...of), or a simple .for() to meet your goal.

Let’s compare!

Using .forEach():

var officersIds = [];

officers.forEach(function (officer) {
  officersIds.push(officer.id);
});

Notice how you have to create an empty array beforehand? Let’s see what it looks like when using .map():

var officersIds = officers.map(function (officer) {
  return officer.id
});

We can even be more concise with arrow functions (requires ES6 support, Babel or TypeScript)

const officersIds = officers.map(officer => officer.id);

So how does .map() work? Basically is takes 2 arguments, a callback and an optional context (will be considered as this in the callback) which I did not use in the previous example. The callback runs for each value in the array and returns each new value in the resulting array.

Keep in mind that the resulting array will always be the same length as the original array.

.reduce()

Just like .map().reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.

The accumulator can be pretty much anything (integer, string, object, etc.) and must be instantiated or passed when calling .reduce().

Time for an example! Say you have an array with these pilots and their respective years of experience:

var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
];

We need to know the total years of experience of all of them. With .reduce(), it’s pretty straightforward:

var totalYears = pilots.reduce(function (accumulator, pilot) {
  return accumulator + pilot.years;
}, 0);

Notice that I’ve set the starting value as 0. I could have also used an existing variable if necessary. After running the callback for each element of the array, reduce will return the final value of our accumulator (in our case: 82).

Let’s see how this can be shortened with ES6’s arrow functions:

const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);

Now let’s say I want to find which pilot is the most experienced one. For that, I can use reduce as well:

var mostExpPilot = pilots.reduce(function (oldest, pilot) {
  return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});

I named my accumulator oldest. My callback compares the accumulator to each pilot. If a pilot has more years of experience than oldest, then that pilot becomes the new oldest so that’s the one I return.

As you can see, using .reduce() is an easy way to generate a single value or object from an array.

.filter()

What if you have an array, but only want some of the elements in it? That’s where .filter() comes in!

Here’s our data:

var pilots = [
  {
    id: 2,
    name: "Wedge Antilles",
    faction: "Rebels",
  },
  {
    id: 8,
    name: "Ciena Ree",
    faction: "Empire",
  },
  {
    id: 40,
    name: "Iden Versio",
    faction: "Empire",
  },
  {
    id: 66,
    name: "Thane Kyrell",
    faction: "Rebels",
  }
];

Say we want two arrays now: one for rebel pilots, the other one for imperials. With .filter() it couldn’t be easier!

var rebels = pilots.filter(function (pilot) {
  return pilot.faction === "Rebels";
});

var empire = pilots.filter(function (pilot) {
  return pilot.faction === "Empire";
});

That’s it! And it’s even shorter with arrow functions:

const rebels = pilots.filter(pilot => pilot.faction === "Rebels");
const empire = pilots.filter(pilot => pilot.faction === "Empire");

Basically, if the callback function returns true, the current element will be in the resulting array. If it returns false, it won’t be.

 

 

 

React lifecycle

React component communication

React component lifecycle

C#

What is the difference between a thread and a task

Exceptions in tasks, what happens.

In async and await what does configureawait do.

What memory types are available in C#

How are variables assigned in memory.

What is the Order of magnitude of indexing a dictionary?

Typescript

What is a type assertion

What are the available types of typescript

Architecture:

What are the advantages of a monolith software architecture as opposed microservices

communication of microservices

messaging architecture

Others

Nodejs basics

NoSQL

Messaging

Tags:

Comments are closed

TextBox

Tag cloud

    RecentPosts