- Find out from where a function is being called
- Get the stack trace for an error
- Invoke a Callback function
- Measure code execution time
- Set a default value for a JavaScript function parameter
If we add this to a function, it will show a Stack Trace.
console.log( ( new Error() ).stack );
try {
...
}
catch( oEx ) {
console.log( oEx.message )
console.log( oEx.stack );
}
If we have a callback function:
var fCallback = function () {};
Instead of invoking the function directly:
fCallback();
We use the .call() function to pass the current object to the function, making it available inside the callback:
fCallback.call( this );
We can use the performance.now()
function like this:
var t0 = performance.now();
// Some code here to measure its execution time
var t1 = performance.now();
console.log( 'Execution time was: ' + ( t1 - t0 ) + " ms" );
In this example we want the default value for the sampleParamter
to be false
:
function sampleFunction( sampleParameter ) {
sampleParameter = typeof sampleParameter !== 'undefined' ? sampleParameter : false;
}