/ Gists / toString()
On gists

toString()

JavaScript

index.js Raw #

// https://medium.com/@asierr/javascripts-function-prototype-tostring-just-got-useful-here-s-how-bc617fd7222c

function greet(name) {
  return `Hello, ${name}`;
}

console.log(greet.toString());

// result
"function greet(name) {\n  return `Hello, ${name}`;\n}"



// any usage
const fn = x => x * 2;
const body = fn.toString();

if (body.includes('x * 2')) {
  console.log('Safe to optimize!');
}


/*
Limitations
Doesn’t work on native functions (e.g., Math.max.toString() returns "function max() { [native code] }")
Some minifiers may still mangle formatting
Not recommended for secure comparisons (function source can be identical but semantically different)
*/