When to create empty strings or arrays to solve problems?

Tell us what’s happening:
Hi!
I’ve noticed that to solve some javascript problems you need to declare empty variables (generally arrays or strings). For example:

Your code so far


function truncateString(str, num) {
while (str.length <= num){
  return str;
}
var newStr = ""; //this line
if (str.length > num){
  newStr = str.slice(0, num);
  
} 
return newStr + "...";
}
console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8))
truncateString("A-tisket a-tasket A green and yellow basket", 8);

I wonder if there is a certain “rule” that tells me that doing this is relevant to solve the problem, because sometimes I can’t tell when doing this is relevant or not.
Thanks!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0.

Challenge: Truncate a String

Link to the challenge:

Hello~!

This has to do with variable scope. Declaring the variable before the if statement allows your function to use it in the return statement. If you declare the variable inside the if statement, you may end up with an error when you try to return it.

first of all, this loop is not the best thing you could use there:

why don’t just use an if statement?


to answer your question

for example here you have a variable just inside an if statement, not changed above it. You don’t need to initialize it before the if statement. (EDIT: but @nhcarrigan is correct, you at least need to declare it in function scope to make sure the return statement access it)


An example of when it’s needed…

for (let i = 0; i < 10; i++) {
  let arr = [];
arr.push(i); 
}
console.log(arr);

what’s the value of arr after the loop?


EDIT for point above:

let arr;
for (let i = 0; i < 10; i++) {
arr = [];
arr.push(i); 
}
console.log(arr)

what’s the value of arr after the loop?


let arr = [];
for (let i = 0; i < 10; i++) {
arr.push(i); 
}
console.log(arr)

what’s the value of arr after the loop?

2 Likes