Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialgaritychapman
7,421 PointsHow to check if value is an array Stage 5: Javascript Functions
On line 16 I need to build a function that takes an array as an argument. I then need to return 0 if the value passed in is a string number or undefined. I'm not sure how to do this. This is what I cam up with:
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Foundations: Functions</title>
<style>
html {
background: #FAFAFA;
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>JavaScript Foundations</h1>
<h2>Functions: Return Values</h2>
<script>
function arrayCounter (array) {
var array = [];
if (typeof array != 'object') {
return 0;
}
return array.length;
}
</script>
</body>
</html>
2 Answers
Clayton Perszyk
Treehouse Moderator 48,850 Pointshey garitychapman
Remove var array = []; from inside your function; it's overwriting the value that is being passed into your function. In other words the value that is passed in is being set to an empty array (hence return array.length will always equal zero).
clayton
Devin Scheu
66,191 PointsThis should work for you, you dont need the var array=[]:
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Foundations: Functions</title>
<style>
html {
background: #FAFAFA;
font-family: sans-serif;
}
</style>
</head>
<body>
<h1>JavaScript Foundations</h1>
<h2>Functions: Return Values</h2>
<script>
function arrayCounter (array) {
if (typeof array != 'object') {
return 0;
}
return array.length;
}
</script>
</body>
</html>
Clayton Perszyk
Treehouse Moderator 48,850 PointsClayton Perszyk
Treehouse Moderator 48,850 PointsHere's how I solved it:
I used instanceof instead of typeof.