What is the order in which the following texts are logged via console.log ?

console.log('1 - start');
setTimeout(() => console.log('2 - setTimeout1'), 0);
Promise.resolve('Success')
    .then(()=> console.log('3 - promise1'))
    .then(()=> console.log('4 - promise2'));
setTimeout(() => console.log('5 - setTimeout2'), 0);
console.log('6 - end');

Output

1 - start// statement is executed directly in the script (first "Run script" task)
5 - end // part of the first "Run script" task gets executed too
3 - promise1 // placed in microTasks queue and executed between tasks, after first "Run script" task is ready
4 - promise2 // microtask added  during previous microtask execution  and executed immediately
2 - setTimeout1 // callback execution scheduled in another task in the "macroTasks" queue (also task queue), executed in the next interation of the event-loop
5 - setTimeout2 // callback execution scheduled in another task in the task queue, executed in the next iteration of event-loop

Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

First with “normal” functions:

//closures and higher order function
function salute(salutation) {
  return function(firstName) {
    return function(lastName) {
      console.log(`hi ${salutation} ${firstName} ${lastName}`)
    }
  }
}

salute('Mr.')('John')('Wick')

//output
hi Mr. John Wick

The shorter variant with arrow functions:

const saluteArrowFunction = (salutation) => (firstName) => (lastName) => console.log(`hi ${salutation} ${firstName} ${lastName}`);

saluteArrowFunction ('Mr.')('Johnny')('Cage')

//output
hi Mr. Johnny Cage

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Via hoisting, memory is allocated to the variable var1, but it is not initialised by the time the closure is executed

function one() {
  function two() {
    console.log(`closure var1 - ${var1}`);
  }

  three();
  var var1 = 'var1';
}

one();

//output
hoisting var1 - undefined

But if we use setTimeout(), by the time callback closure function is executed var1 will have been initialised and its value is printed:

function one() {
 setTimeout(function() {
  console.log(`closure var1 - ${var1}`);
 }, 0);
  var var1 = 'var1';
}

one();

//output
closure var1 - var1

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Still confused about how passing variables in Javascript functions works? So was I, until recently. It took me some effort to understand, and I’d like to share my understanding with an example.

First try guessing the outcome of the following javascript snippet

Input

const number = 1983
const string = 'Adrian'
let obj1 = {
  value: 'obj1'
}
let obj2 = {
  value: 'obj2'
}
let obj3 = obj2;

let obj4 = ['a'];


function change(numberParam, stringParam, obj1Param, obj2Param, obj4Param) {
    console.log('\nSTART logs in function');

    numberParam = numberParam * 10;
    stringParam = 'Ionut';
    console.log('numberParam - ', numberParam);
    console.log('stringParam - ', stringParam);

    console.log('obj1Param.value in function before obj1Param = obj2Param assignment - ', obj1Param.value);
    obj1Param = obj2Param;
    console.log('obj1Param.value in function after obj1Param = obj2Param assignment - ', obj1Param.value);

    console.log('obj2Param.value in function before obj2Param.value change - ', obj2Param.value);
    obj2Param.value = 'changed'; // obj1Param.value = 'changed'; would yield the same result
    console.log('obj1Param.value in function after obj2Param.value change - ', obj1Param.value);
    console.log('obj2Param.value in function after obj2Param.value change - ', obj2Param.value);

    //obj4Param = ['b'];
    obj4Param.push('b');
    console.log('obj4Parma - ', obj4Param);

    console.log('END logs in function \n');
}

change(number, string, obj1, obj2, obj4);

console.log('number final - ', number);
console.log('string final - ', string);
console.log('obj1.value final - ', obj1.value);
console.log('obj2.value final - ', obj2.value);
console.log('obj3.value final - ', obj3.value);
console.log('obj4 final - ', obj4);

Before you read the output I suggest you read the explanation of Call by sharing on Wikipedia, which is the best explanation on the topic I found.

Output

START logs in function
numberParam -  19830
stringParam -  Ionut
obj1Param.value in function before obj1Param = obj2Param assignment -  obj1
obj1Param.value in function after obj1Param = obj2Param assignment -  obj2
obj2Param.value in function before obj2Param.value change -  obj2
obj1Param.value in function after obj2Param.value change -  changed
obj2Param.value in function after obj2Param.value change -  changed
obj4Parma -  ["b"]
END logs in function

number final -  1983
string final -  Adrian
obj1.value final -  obj1
obj2.value final -  changed
obj3.value final -  changed
obj4 final -  ["a"]

Ok, so what’s going on?

  • number and string primitives are “boxed”1 in Number and String objects2 before passing. Boxed objects are always a copy of the value object, hence new objects (Number and String) are created in memory with the same primitive values. In the function execution (scope) they get “unboxed”, their value is changed and placed in the new memory space, but once the function is over the new space in memory is cleared, with the original remaining unaffected.
  • a copy reference to obj1 and obj2 is passed to the function, pointing to the same address of the “original” objects in memory (call by sharing)3. With the obj1Param = obj2Param assignment in the function, both obj1Param and obj2Param to the original obj2 object in memory, so when changing its property obj2Param.value = 'changed' it will also be visible outside of the function scope, after it is terminated. obj1Param.value = 'changed' would have had the same effect after the assignment.
  • what about obj4? obj4param is also a copy reference to the obj4 object (remember in Javascript arrays are objects), but with the obj4Param = ['b'] assignment it’s pointing now to a newly created object (the ['b'] array object), which is visible only in the function’s scope and is destroyed when the function is over. Thus, it has no effect on the original object. On the other hand, a statement like obj4param.push('b') would have changed the original array and would display a  ["a", "b"] value.

Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Project: codever - File: searchbar.component.ts

Here used the success method with IziToastSettings

import iziToast, { IziToastSettings } from 'izitoast';

removeSearch(search: Search, e: MouseEvent) {
  e.preventDefault();
  e.stopPropagation();

  const indexSavedSearch = this.getIndexSavedSearch(search.searchDomain, search.text);

  const deletedSearch = this._userData.searches.splice(indexSavedSearch, 1)[0];
  this.userDataStore.updateUserData$(this._userData).subscribe(() => {
    console.log('Removed search ' + search.text + ' from domain ' + search.searchDomain);
    const iziToastSettings: IziToastSettings = {
      title: `"${deletedSearch.text}" deleted from "${deletedSearch.searchDomain}" search history `,
      timeout: 3000,
      position: 'bottomRight'
    }
    iziToast.success(iziToastSettings);
  });
}


Reference - https://izitoast.marcelodolza.com/#Methods


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏