Salma Ahmed
Salma Ahmed

Reputation: 15

why I am getting undefined result with for loop function?

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

Upvotes: 0

Views: 41

Answers (3)

jo_va
jo_va

Reputation: 13993

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'));

Upvotes: 2

arizafar
arizafar

Reputation: 3132

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"));

Upvotes: 0

Xin Jun Ho
Xin Jun Ho

Reputation: 1

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

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

Upvotes: 0

Related Questions