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 trial

JavaScript

Searching multiple names on Student Record (solution without using loop)

I thought there must be a better way to solve this than using loop, and I found some great videos by funFunFunction on YouTube:

Higher order functions Arrow functions

With this, I came up with the solution to searching multiple names quite easily.

const students= [
  {name:"Sara", lang:"Ruby"},
  {name:"Bob", lang:"Python"},
  {name:"Lee", lang:"Javascript"},
  {name:"Sara", lang:"Haskell"},
  {name:"Isa", lang:"Java"},
]

var studentName= prompt("Pick a name:[Sara],[Bob],[Lee] or [Isa]")

//This does the same thing as the function below
var isStudent= (student => student.name=== studentName)

/* This is the anonymous function without use of arrow functions (as above)
var isStudent= function(student){
    return student.name=== studentName
    } */


var studentList= students.filter(isStudent)  
console.log(studentList)

I still don't quite know how or why the variable studentName can be called inside the anonymous function here, but it works JS Fiddle... Maybe someone can explain?

1 Answer

Steven Parker
Steven Parker
231,269 Points

:point_right: The variable studentName is defined at global scope.

Since it's not defined inside of a function, the variable is global and can be accessed from anywhere in the program.

Also, a more conventional syntax for the isStudent declaration would be:

var isStudent = student => student.name === studentName;