Use of curly braces in functions and if statements

I need help understanding when to use curly braces in an if statement. I was attempting to solve the Basic Algorithm Scripting: Where do I Belong challenge. Compare the 2 functions below:

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  let sortedArr = arr.sort();
 for (var a = 0; a < arr.length; a++) {
    if (arr[a] >= num) return a;
  }

  return arr.length;
}

and

function checkIndex(u,n){
  let papa = u.sort();
  for (let i = 0; i < u.length; i++){
    if (sortedArr[i] >= num){
      return i;
  }else{
    return u.length
    }
}
}

console.log(checkIndex([], 1)); //prints undefined
console.log(getIndexToIns([], 1)); //prints out 0. The only difference is the curly braces.

syntax is like this:
const functionName(){
block code;
}
for conditionals:
if(boolean expression){
block code;
}

I think you meant:

function functionName() {
1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

Thanks for that. The solution provided however, does not include the curly braces after the if statement. Do you know how the curly braces affect the code?

It is not about the curly braces. It is the fact that the second function (checkIndex) will return either i or u.length within the first iteration of the for loop. The other function will return arr.length only if the return a; statement is never executed.

Ahhhhh thanks … check that ;o)

If a block consists of a single line, you can choose to omit the curly braces. However, you will very often find that people prefer that you use curly braces for all if and else blocks for consistency and readability.

2 Likes

I second that preference.

I personally do like the one-line if (foo) return bar; in my own personal code, but only for returns or throws. And in a team I stick to always using the curlies. It’s just too likely that someone will eventually evolve it into a multi-line statement and screw things up.

3 Likes

Ahh thanks. That makes sense.