0

why this code return undefined I can't spot the reason

function findShort(s){
  let splitted = s.split(' ');
  let result = splitted[0].length ;
  let looped
  for (var i=0 ; i++ ; i<splitted.length){ 
    looped = splitted[i].length;
    if (looped < result) {return looped}else {return result }}
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

I am supposed to get numbers of smallest word

1
  • The order of the statements in your for-loop is incorrect. Commented Apr 8, 2019 at 10:15

3 Answers 3

2

Your for loop condition and increment are inverted:

for (var i=0 ; i++ ; i<splitted.length){ ...

should instead be:

for (var i = 0; i < splitted.length; i++) { ...

You also have to fix your looping code as it returns in both branches of you inner if statement, which means only a single iteration will run.

If you want to return the length of the smallest word, do this:

function findShort(s) {
  let splitted = s.split(' ');
  let result = splitted[0].length;
  for (let i = 0; i < splitted.length; i++) { 
    const looped = splitted[i].length;
    if (looped < result) {
      result = looped;
    }
  }
  return result;
};
console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

Or shorter using Array.prototype.reduce():

function findShortest(s) {
  return s.split(/\s+/).reduce((out, x) => x.length < out ? x.length : out, s.length);
};
console.log(findShortest('bitcoin take over the world maybe who knows perhaps'));

Sign up to request clarification or add additional context in comments.

Comments

0

Your for-loop implementation is wrong, it is supposed to be:

for (var i=0; i<splitted.length; i++)

Comments

0

Order of condition and increment is wrong in you for loop as well as the code inside the loop,

it will check for the first element only as you have a return in all conditions.

Here's the correct one

function findShort(s) {
	let splitted = s.split(' ');
	let result = splitted[0].length;
	let looped
	for (var i = 0; i < splitted.length; i++) {
		looped = splitted[i].length;
		if (looped < result) { result = looped }
	}
	return result;
};

console.log(findShort("bitcoin take over the world maybe who knows perhaps"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.