A couple of problems here.
1. Javascript uses
=
to assign a value.
--- The equal value comparison is two equal signs
==
--- Three equal signs
===
compares value AND type for equality
2. The
else
only has null in it. Won't print it.
--- Replace with
console.log("null");
So I ended up with
const names = ["charlie","ben","randy"];
if (names.length == 2){
console.log(names[2]);
} else{
console.log("null");
}
Hmmmm. All it does is log
null. Why is this? So I updated the
else
block
else{
console.log("null");
console.log(names.length);
}
So it still logs the
null and now it also logs "3".
Oh yeah, while the array indexes are 0 based; length is another story.
A populated array has a length that is 1-based. The last element in the array generally has an index of (length-1).
An empty array has a length of 0, and element[0] is
undefined
So now you get to make a decision; do you want it this way, or do you want
names.length==3
, or how about a greater than comparison
names.length > 2
?
In all reality, it shouldn't be too hard to have notepad etc open with the code and a browser open to that saved html document. It's what I did!