Array.length variable

Hello,

Could someone tell me why the following code returns that undefined? :

let arr = [1,2,3];
let a = arr.length

console.log(a)
//returns undefined
//returns 3

Thanks

Hey there @karolm5444849688!! Welcome to the forums :grinning:

I moved this topic over to “Get Help JavaScript” to be more specific.

Is this all of your code? Running this does not result in undefined, and I can not think of a way to make the .length attribute return undefined( Though if someone with more knowledge of JS than me does, please correct me).

Since you use the term return it would make since that it is part of a function, and your end result of logging that function would match that too. Say for example you had this code:

function randomFunction() {
  let arr = [1,2,3];
  let a = arr.length;

  console.log(a);
}

console.log(randomFunction());

// logs:
// 3
// undefined

Not exactly like you said, but nearly. If your code is somewhere along these lines
than it is probably due to the fact you have no return statement. In order to use the value of a function you must return the value you need from it. For example, this function will tell me the value of the two numbers I provide it with:

function add(n1, n2) {
  newValue = n1 + n2;
  console.log(newValue);
}

add(3, 5) // logs 8
console.log(add(3, 5)) // The function logs 8, 
                       // but this logs undefined right afterwords

But without a return this newValue is deleted as soon as the function terminates. In order to save it I would use a return.

function add(n1, n2) {
  newValue = n1 + n2;
  return newValue;
}

let num = add(3, 5) // a equals 8
console.log(add(3, 5) //logs 8
Refactored function

I wrote the function the way I did to help illustrate, it can be refactored a bit. If you are curious, I would actually write it like this:

const add = (n1, n2) => {
  return n1 + n2;
}

Now we can both log and save the value from add()


In the event you are not working with a function, and my only clue to that is because you said undefined was returned before 3, than I would guess you have another variable or function hidden up in your program that is undefined. And another console.log() that is logging it. For example:

let badValue = undefined;
console.log(badValue);

let arr = [1,2,3];
let a = arr.length;

console.log(a);

If this is not your full code, please post it properly formatted. Simply press this button:

And copy/paste your code between the two rows of backticks:

Edit:

There is one way I know of to make .length return undefined, though I don’t think it is the case here, since you variable arr is obviously an array. If you use .length on something that is not an array but is instead a single object, it will return undefined:

let a = true;
let b = false;
let c = 3;
let d = 3.5;

a.length // undefined
b.length // undefined
c.length // undefined
d.length // undefined

let e = "hello";
let f = [1, 2, 3, 4, 5];

e.length // 5
f.length // 5
2 Likes