Javascript if variable is undefined then use another

This question already has an answer here:

  • Is there a “null coalescing” operator in JavaScript? 8 answers

  • I want to leave short comment but now I understand that will be better if I explain.

    var job = $scope.job || $scope.jobs;
    

    undefined == false; // prints true

    So that's how it works.

    If $scope.job == undefined == false || $scope.jobs == {...} == true.
    

    If job will be undefined - it will be false so or operand returns true value.


    So if i understand what you mean:

    if ($scope.job)
      var job = $scope.job;
    else
    {
      var job = $scope.jobs;
      $scope.job = $scope.jobs;
    }
    

    well, shorthand then:

    var job = $scope.job = $scope.job || $scope.jobs;
    

    Or you can use ternary operator

    var job = $scope.job ? $scope.job : $scope.jobs
    

    or

    var job = $scope.job == undefined ? $scope.job : $scope.jobs
    
    链接地址: http://www.djcxy.com/p/73362.html

    上一篇: 它在Javascript中的意义(分配变量)

    下一篇: 如果变量未定义,则使用另一个Javascript