Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
When do I need to create a new variable within a function?

I'm a new learner of JavaScript, and when I get to learn the way of using a function. It sometime confuses me on why we should declare a new variable and add the variable to the action we want to execute. Let's look into the code.

function reverse(word){
  Array.from(word);
  let reverseWord='';
  for(i = word.length-1; i >= 0; i--) {
    reverseWord += word[i];
  }
  return reverseWord;
}

I'm sure you know this one of the way of reversing string in javascript, my question is:

  1. Why do we need to declare a new variable within the function, when should we declare it?

  2. Why can't I just type console.log(word[i]);?

  3. What does it mean by wordLength+=word[i];?

  4. Why should we return the new variable(wordLength), instead of the function(reverse) after the loop?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Why do we need to declare a new variable within the function...

Because you need a place to store the reversed word as you build it. (Note: wordLength isn't a good name for that variable. It doesn't contain the word's length. It contains the characters of the reversed word.)

...when should we declare it?

Any time before you first need it.

Why can't I just type console.log(word[i]);?

Because the goal of the exercise is to build a string containing the reversed word, not just to output it. (And because console.log writes a new line each time you call it.)

What does it mean by wordLength+=word[i];?

That adds the character in word[i] to the end of wordLength. For instance, if the word is "start", wordLength starts out with "", then gets "t" added to it to make it "t", then gets "r" added to it to make "tr", and so on.

(+= is a shorthand way to write wordLength = wordLength + word[i];. There are several of these compound assignment operators, most of them for math: -=, *=, etc.)

Side note: The Array.from call in your code isn't doing anything useful. It's creating an array, but then throwing that array away because nothing uses the return value. The rest of the code is using the string you receive in word.

about 4 years ago · Juan Pablo Isaza Relatório

0

Why do we need to declare a new variable within the function, when should we declare it?

Vars is a place to store data. If your algorithm requires keeping some data to use it later you need vars. Also well named variables is a good way to create easy-to-understand code

Why can't I just type console.log(word[i]);?

You can, but it will do nothing useful. Your goal is to build a string and return it. Usage of your function will be something like

const word = getSomeText()
const reversedText = reverse(word)
doSomeStuff(reversedText) // whatever, send it online, or render it on screen some fancy way, not in the console.

So you need to return actual string, not to solve a puzzle and show the answer whatever way you like

Why should we return the new variable(wordLength), instead of the function(reverse) after the loop?

Because it contains reversed word and you function supposed to return it. there is rare complicated occasions when a function returning itself is useful, but it has nothing in common with your task

about 4 years ago · Juan Pablo Isaza Relatório

0

Why do we need to declare a new variable within the function, when should we declare it?

Variable is required to store the data value that can be changed later on. In your case wordLength variable is required to store the reverse string.

It's best to declare variables when you first use them to ensure that they are always initialized to some valid value.

Why can't I just type console.log(word[i])

console.log() is used just to print the output but will not use if you want to return something and as per your statement it will just print the word[i] not a whole reverse string.

What does it mean by wordLength+=word[i]

It means you are concatenating the each iteration word[i] into a wordLength variable.

wordLength+=word[i] is a shorthand for wordLength = wordLength + word[i]. If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.

Why should we return the new variable(wordLength), instead of the function(reverse) after the loop ?

Because this is what you expected from the function. It returns the reversed string and function should return it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda