Computer Science

Closure | Closure is when a function 'remembers' its lexical scope even when the function is executed outside that lexical scope. It doesn't snapshot values, but preserves access to variables.

var name = "Matt";

var myName =()=>{
  console.log(name);
}

name = "Liam";

myName();

// Liam;

JS closed over the variable name, not the value 'Matt'.

Quick sort | The last number in an array is taken as the pivot point. Anything smaller than it is pushed to the left, greater than it is pushed to the right. The process is repeated until the whole array is sorted.

const input = [10, 8, 2, 1, 6, 3, 9, 4, 7, 5];

Steps:

  1. [2, 1, 3, 4], 5, [10 8, 6, 9, 7]
  2. [2, 1, 3], 4, [ ], 5, [6], 7, [10, 8, 9]
  3. [2, 1], 3, [ ], 4, 5, 6, 7, [8], 9, [10]
  4. [ ], 1, [2], 3, 4, 5, 6, 7, 8, 9, 10

Output:

12345678910

Search in array | There are two ways to search for an element in an array - linear aka sequential search and binary search.

Linear search is how you might normally expect to search. Begin from the head and check each element until you have a hit or finish the list if it isn't there. Binary is more efficient but only works on sorted lists. It cuts the list in half every iteration to narrow the search down.

const numList = [1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 19];

const linearSearch = (x, array) => {
    for (let i = 0; i < array.length; i++) {
        if (x === array[i]) {
            return array[i];
        }
    }
    return "not found"
}
Linear Search

Result:5

Javascript

An execution context in JS consists of two parts. The thread and the memory. The thread is where lines of code gets executed in order. The memory is where variables and their assigned values are stored. Take for example this code.

const x = 5;
const y = 3;

function Add (a, b){
    const result = a + b;
    return result;
}

function Add (x, y);

Yes, the answer is 8 but how did we get there? JS 'threads' through the code from top to bottom one line at a time. In the first line, the variable x is assigned 5. In the second, y is assigned 3. These assignments are stored in memory. In line 4, the Add function is declared and also saved to memory. Up to now, the output (which lies in memory) is still empty. Now that we have all the variables saved, its time to execute them. Jump to the last line, the Add function is called. JS retrieves x and y from memory, stick them in to the Add() function which is also found in the memory, and finally return the result in output - 8! And that's the execution context.