+ 1

JavaScript: deletion of a local variable

(function(x){ delete(x); console.log(x); })(1); This snippet was a SoloLearn match challenge and I would like to understand it. I have two questions: (1) In another languages, functions are only executed when they are called. Here I can’t see any caller. Why is this function executed? (2) It outputs 1. How does local and global scope work here if x is deleted?

15th Feb 2020, 6:56 PM
Prof. Dr. ZoltĂĄn Vass
3 Answers
+ 5
function is called... This is an IIFE..(Immediately invoked function expression) So 1 is basically in the scope and is passed as a parameter.. About the second question : Delete operator doesn't delete variables ... So it's value is not deleted.. Refer these for IIFE: https://medium.com/javascript-in-plain-english/https-medium-com-javascript-in-plain-english-stop-feeling-iffy-about-using-an-iife-7b0292aba174 https://www.tutorialspoint.com/Why-are-parenthesis-used-to-wrap-a-JavaScript-function-call
15th Feb 2020, 7:24 PM
$hardul B
$hardul B - avatar
+ 2
If anyone reads this thread later: Immediately Invoked Function Expression is a good way at protecting the scope of your functionand the variables within it. ...we simply want to call a function in order to get an output, but that’s it — we’ll never want to use it again and don’t want our program to ever be able to accidentally access it. 1. wrap our entire function in brackets 2. get rid of the name 3. simply add a pair of brackets at the end of the function (but just before the semi-colon) Source: https://medium.com/javascript-in-plain-english/https-medium-com-javascript-in-plain-english-stop-feeling-iffy-about-using-an-iife-7b0292aba174
15th Feb 2020, 9:00 PM
Prof. Dr. ZoltĂĄn Vass
+ 1
$hardul B Thank you for your answer and looking up the articles! I’ll read them.
15th Feb 2020, 7:29 PM
Prof. Dr. ZoltĂĄn Vass