Please enable JavaScript.
Coggle requires JavaScript to display documents.
Advanced working with functions - Coggle Diagram
Advanced working with functions
Recursion and stack
Two ways of thinking
Iterative thinking: the for loop
Recursive thinking: simplify the task and call self
A recursive solution is usually shorter than an iterative one.
The process
The current context is “remembered” on top of the stack.
The new context is created for the subcall.
When the subcall is finished – the previous context is popped from the stack, and its execution continues.
Any recursion can be rewritten as a loop. The loop variant usually can be made more effective.
A recursively-defined data structure is a data structure that can be defined using itself.
Rest parameters and spread syntax
Rest parameters ...
A function can be called with any number of arguments, no matter how it is defined.
function sum(a, b)
sum(1, 2, 3, 4, 5)
it work but it only take a and b into funtion
The rest parameters must be at the end
function showName(firstName, lastName, ...titles){}
The “arguments” variable
a special array-like object named arguments that contains all arguments by their index.
Arrow functions do not have "arguments"
it will take argument from the outer “normal” function.
arguments are available in function
arguments.length
arguments[0]
arguments[1]
Spread syntax
spread turns array into a list of arguments
use the spread syntax to turn the string into array of characters
let str = "Hello";
alert( [...str] ); // H,e,l,l,o
difference between Array.from(obj) and [...obj]
The spread syntax works only with iterables.
Array.from operates on both array-likes and iterables.
Copy an array/object
array
let arrCopy = [...arr];
alert(JSON.stringify(arr) === JSON.stringify(arrCopy)); // true
alert(arr === arrCopy); // false (not same reference)
note
array-like object and iterable it's not an array and not support array medthod.
The old "var"
“var” has no block scope
If a code block is inside a function, then var becomes a function-level variable
it's mean cann't visible outside function
Reason: because a long time ago in JavaScript, blocks had no Lexical Environments
“var” tolerates redeclarations
“var” variables can be declared below their use
var variables are defined from the beginning of the function, no matter where the definition
Declarations are hoisted, but assignments are not.
IIFE
Function Expression is created and immediately called
the code executes right away and has its own private variables.
immediately-invoked function expressions”
parentheses to tell JavaScript that we mean a Function Expression (wrap code)
Global object
provides variables and functions that are available anywhere
name
Brower: Window
Node.js: global
Other: other name
Using for polyfills
use the global object to test for support of modern language features.
In-browser, unless we’re using modules, global functions and variables declared with var become a property of the global object.
store values in the global object only if they’re truly global for our project
keep their number at minimum.
Function object, NFE
functions are objects.
The “name” property
a function’s name is accessible as the “name” property
Object methods have names too
The “length” property
“length” that returns the number of function parameters
rest parameters are not counted.
Custom properties
can also add properties of our own.
A property is not a variable
Variables are not function properties and vice versa
Named Function Expression
let sayHi = function func(who)
name of sayHi: 'func'
The "new Function" syntax
syntax
let func = new Function ([arg1, arg2, ...argN], functionBody);
let sum = new Function('a', 'b', 'return a + b');
if only one argument it will understand functionBody
new Function
allows to turn any string into a function
Closure
Functions created with new Function, have [[Environment]] referencing the global Lexical Environment, not the outer one.
Therefore closure not work with new Function
Usually, a function remembers where it was born in the special property [[Environment]]. It references the Lexical Environment from where it’s created
Scheduling
setTimeout
syntax
let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
allows us to run a function once after the interval of time.
note: Pass a function, but don’t run it
Canceling with clearTimeout
let timerId = setTimeout(() => alert("never happens"), 1000);
clearTimeout(timerId);
setInterval
syntax
let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Canceling with clearInterval
let timerId = setInterval(() => alert('tick'), 2000);
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);
Nested setTimeout
Nested setTimeout allows to set the delay between the executions more precisely than setInterval.
The nested setTimeout guarantees the fixed delay.
Garbage collection and setInterval/setTimeout callback
When a function is passed in setInterval/setTimeout, an internal reference is created to it and saved in the scheduler. It prevents the function from being garbage collected, even if there are no other references to it.
For setInterval the function stays in memory until clearInterval is called.
Zero delay setTimeout
When we using timeout it automatic not synchonous
Arrow functions
Do not have this
Do not have arguments
Can’t be called with new
They also don’t have super