DEV Community


Posted on

(function(){....})() Did you Know what is this

this function is called Immediately Invoked Function Expression(IIFE)
what's the use of this function

  • well this function get invoked itself at the time of load and we can do any ui process at that time let's say if i want to get data from localstorge at the time of load to find the theme used by the user let's take this eg.
(function () {
    const value = localStorage.getItem('theme')
    if (value === 'Dark Mode') {
//darkMode is outside IIFE
    else if (value === 'Light Mode') {
        return null
    else {
        localStorage.setItem('theme', 'Light Mode')
Enter fullscreen mode Exit fullscreen mode

this code initially check theme and if it is dark calls another function in the script if it is light it returns null and if value is not present then create a theme useful in next load

Top comments (0)