最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Function returns undefined with ternary operator - Stack Overflow

programmeradmin2浏览0评论

I am trying to wrap my head around the isBreadwinner function. Why does not true pass into the (**) function. Why is Earning member:undefined

<script>
    "use strict"

    //creating a user object 
    let user = {
        name : "Stackoverflow Developer",
        age : 23
    };

    // appending properties to the user object
    user.location = "NYC";
    user["occupation"] = "JavaScript Developer";
    user["salary"] = 10;

    //(**)
    let isBreadwinner = () => {
        (user.salary) ? true : false;
    };

    console.log("asd" + isBreadwinner());
    user["Earning member"] = isBreadwinner();

    // printing the object
    console.dir("User dir object" + JSON.stringify(user));
    console.dir(user); //Earning member:undefined
</script>

I am trying to wrap my head around the isBreadwinner function. Why does not true pass into the (**) function. Why is Earning member:undefined

<script>
    "use strict"

    //creating a user object 
    let user = {
        name : "Stackoverflow Developer",
        age : 23
    };

    // appending properties to the user object
    user.location = "NYC";
    user["occupation"] = "JavaScript Developer";
    user["salary"] = 10;

    //(**)
    let isBreadwinner = () => {
        (user.salary) ? true : false;
    };

    console.log("asd" + isBreadwinner());
    user["Earning member"] = isBreadwinner();

    // printing the object
    console.dir("User dir object" + JSON.stringify(user));
    console.dir(user); //Earning member:undefined
</script>
Share Improve this question edited Aug 6, 2017 at 5:22 lft93ryt asked Aug 6, 2017 at 5:13 lft93rytlft93ryt 1,0161 gold badge17 silver badges34 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You're missing the return in your isBreadWinner function.

let isBreadwinner = function() {
    return (user.salary) ? true : false;
};

If you want to skip using a return then you might want to use an ES6 arrow function which has implicit returns if everything is declared on one line without a block, {}.

let isBreadwinner = () => (user.salary) ? true : false;

you may write the function like this

let isBreadwinner = () => (user.salary) ? true : false;

or just add return to your function

发布评论

评论列表(0)

  1. 暂无评论