iife - functions in javascript wrapped in parenthesis -


this question has answer here:

i new javascript , might have dove deep end first. have came across following definition while reading design patterns in js. don't understand syntax used here, why "log" function definition in "()",

var log = (function() {     var log = "";     return {         add: function(msg) { log += msg + "\n"; },         show: function() { alert(log); log = ""; }     } })(); 

please point me in right direction.

without parenthesis, right hand side of assignment function expression, , log assigned reference (anonymous) function expression, allowing call log() later.

if include parenthesis, wrapped function turns self-invoking function expression (and executed), log assigned whatever function call returns.

as else stated, code shows example of so-called module pattern. read more here.


Comments