JS: 3 tips

less than 1 minute read

Follow the Dev Ed, learn 3 new stuffs

**Call back **

Example 1

	Const sayName = (name, cb) => {
		console.log('running some code');
		console.log(`My name is ${name}`);
		cb();
	}
	
	function callback(){
		console.log('This ran at the end');
	}
	
	sayName('Ed', callback);
	
	//result:
	//running some code
	//My name is Ed
	//This ran at the end

Example 2:

consloe.log('first');

setTimeout(() => {
	console.log('from callback');
}, 2000);

console.log('last');

//Result:
//first
//last
//from callback

Explain:

Call stack :

Defination fromMDN: Mechanism for an interpreter to keep track of multiple functions

  • When script calls a function, the interpreter add it to the call stack
  • The function that are called by a function, will add on the top of stack
  • If have two much funciton in stack and run out of space, it result “stack verflow”

Web APIs

  • Web APIs dont go to stack
  • There are large unmber of Web APIs, setTimeout is one of them, it count down the umber and invoke the functions, put functions back to call stack.
  • Everything in Web APIs is running asynchronous

Callback Queue

The invoked Web APIs store in callbakc queue, wait until call stack is empty, no other functions need go to stack, then send functions to call stack.