Search code examples
javascriptfunctionalertfirst-class

Unexpected behavior of alert function in javascript


I was experimenting on alert but alert dosen't worked as i expected have look below lines:

var tobealerted = function(){return 'worked!'};

now when i alert this:

alert(tobealerted());

this will work fine! now

alert(tobealerted);

in this i removed parentheses. now it alert function(){return "worked"} not worked! now i thought it may be a feature of javascript that it would alert any text without being in quotes then i wrote:

alert(worked!)

but the google console throw exception worked! is undefined , so my thinking was wrong. then again i wrote this

alert(function(){})

and you know what it alerted function(){}! and then i thought that alert would only allow such statement to be alerted without quotes. then again wrote:

alert(if(){}) //if is not defined
alert(for(){}) //for is not defined
alert(while(){}) //while is not define

but these did not worked for this i searched and found something, from my search i found this

functions are first class object

and according to wikipedia:

In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures

so my question is

why did alert function only allowed function (){} to be alerted but not others

and if you think it is because that function is a first-class object then i don't think so because i did not assign this function(last one) to any variable neither it returns anything in alert(function(){})

i am so much curious and also confused! thanks!


Solution

  • Function is just another type of object in Javascript, so:

    alert(tobealerted());
    

    alerts the function result but:

    alert(tobealerted);
    

    alerts the function object itself using .toString() method which returns function's body for objects of type function.

    Statements like if and so on are not objects but full definition of function declares an object. So you can alert function and not if statement for example.