Search code examples
javascriptconditional-operatorarrow-functions

Why the following arrow function won't execute but a simple if statement will?


Is there a problem with code? or do i lack the understanding of how to fire functions without specifically calling them?

code:

let age = prompt('How old are you?');

//Arrow function that won't execute:

()=> { return (age < 18 ? alert('You are too young!') : alert('welcome!')); };

//This executes just fine:

if (age <= 18) {
    alert('You are to young!');
} else { 
    alert('welcome!');
};

Solution

  • In JavaScript functions can be variables themselves. What your code has so far done is created a function but not actually assigned it to a variable. So you're saying "Here is a function to run" but never actually saving that function anywhere. There's a few methods you can do here.

    1. Just keep the code as an if statement

    2. Assign the function to a variable and call it like this:

    var checkAge = ()=> { return (age < 18 ? alert('You are too young!') : alert('welcome!')); };
    

    And then call it with checkAge().

    What you really should do instead though is pass age as a parameter into the checkAge function like this:

    var checkAge = (a)=> { return (a < 18 ? alert('You are too young!') : alert('welcome!')); };
    checkAge(a);
    

    Because this means you could then use that function again somewhere else in your code whenever you like.