Brackets in Functions Javascript

前端 未结 3 1904
花落未央
花落未央 2021-01-24 13:10

I am having trouble understanding the usage of brackets in \"for\" loops and \"if\" statements in Javascript. I have seen syntax in Javascript where there is brackets and where

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 13:44

    Bracket allow you to add more statement into one block. if I modify bit to show result

    function range(upto) {
      var result = [];
      for (var i = 0; i <= upto; i++) {
        result[i] = i;
        result[i] = result[i]*2
      }
        return result;
    
    }
    console.log(range(15));
    

    Result will be

    [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30]
    

    however, without bracket,

    function range(upto) {
          var result = [];
          for (var i = 0; i <= upto; i++) 
            result[i] = i;
            result[i] = result[i]*2
    
            return result;
    
        }
        console.log(range(15));
    

    result will be like this

    [1,2,3,4,5,6,7,8,9,10,11,12,13,14,30]
    

    *being rookie programmer, I think it probably will fail due to undeclared variable

提交回复
热议问题