Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

410
Views
Write a function firstWord, taking a string and returning the first word in that string. The first word are all characters up to the first space
function firstWord (go and run) {
 let text = "go and run";
 let firstBlank = text.substr(0, 2);
 return firstBlank;
 }

Why is this giving me wrong answer? Can any one explain the solution please? hint:-

function firstWord(s) {
  let firstBlank = s.indexOf(' ');
  return s.substr(0, firstBlank);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are several problems with your code:

  • go and run is not a valid parameter declaration in the function header. There is confusion here with the parameter and the string value that you expect the function to be called with. In the function header you should list the parameter(s) with variable names. Since the function should be called by passing a string, you could name that variable phrase, or text or something else that is descriptive.

  • let text = "go and run"; should not appear in the function. The function should work for any string, so it should not be hard-coded to "go and run". The parameter variable will have the actual string that the function is called with.

  • let firstBlank = text.substr(0, 2); is again focusing on one particular string. It actually doesn't search for a space at all. You -- as programmer -- tell it that the first word is 2 characters long. Your function then might as well just do return "go". But you should really support any string, and then let the code find out how long the first word is by scanning the string for the first space or end of the string.

  • substr (also in the second code block) is a deprecated function. Use slice instead.

The second code snippet does the job better, but it still goes wrong when the given string only contains one word. In that case, it will return the wrong answer.

Here is a correction to that second function, but using a more descriptive parameter variable:

function firstWord(text) {
  let firstBlank = text.indexOf(' ');
  if (firstBlank == -1) { // There is no space at all -- return the whole string
    return text;
  } 
  return text.slice(0, firstBlank);
}

NB: Using split a shorter solution code is possible.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!