I have the following piece of code:
function initValidation() { // irrelevant code here function validate(_block){ // code here } }
Is there any way I can call the validate()
function outside the initValidation()
function? I've tried calling validate()
but I think it's only visible inside the parent function.
Generally defining a function inside another function is to scope it to that function and you can't call a nested function in JavaScript. You have to do something inside in outer funciton to make inner funciton available outside it. You will need to return the inner function call.
To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.
Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators.
no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.
function initValidation() { // irrelevant code here function validate(_block){ console.log( "test", _block ); } initValidation.validate = validate; } initValidation(); initValidation.validate( "hello" ); //test hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With