Click here to Skip to main content
15,867,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just want the program to print the 3rd item in an array if there is one and if there isnt i want it to print "Null".

What I have tried:

const names = ["charlie","ben","randy"];

if (names.length = 2){
console.log(names[2]);
}
else{
 null;
}
Posted
Updated 27-Dec-18 14:03pm
Comments
Mohibur Rashid 27-Dec-18 19:19pm    
And what is the problem?

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
JavaScript
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
JavaScript
else{
     console.log("null");       // what you want
     console.log(names.length); // for troubleshooting
 }
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!
 
Share this answer
 
Quote:
I just want the program to print the 3rd item in an array if there is one and if there isnt i want it to print "Null".

To print the third element of array, its length must be at least 3.
You are using console.log to print third element of names, you must use it for null too.
JavaScript
const names = ["charlie","ben","randy"];

if (names.length == 3){
    console.log(names[2]);
}
else{
    console.log("null");
}
 
Share this answer
 
v2
Comments
Mohibur Rashid 27-Dec-18 19:47pm    
Incorrect source code
Patrice T 27-Dec-18 20:13pm    
I didn't trued to correct syntax errors
Mohibur Rashid 27-Dec-18 23:28pm    
noted!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900