Passing an Object to a Function in JavaScript:

So while learning about how objects behave in javaScript, I came across an issue that had me stumped for a bit. I understood object creation, the syntax was pretty straight forward, and stepping away from procedural programming into thinking in terms of complex objects with multiple properties that act as one unit was a really cool change of mindset.

So in this example let’s say we are looking for a vintage automobile with the criteria that it must be pre-1960, with 10,000 miles or less: we will create a variable named taxi that is an object with these properties:

var taxi = {
make: “Webville Motors”,
model: “Taxi”,
year: 1955,
color: “yellow”,
passengers: 4,
convertaible: false,
mileage: 281341,
started: false

We’ll want to run it through a conditional test to determine if it fits our criteria. Let’s make a function called prequal that takes the object as a parameter and runs some if else conditionals returning a boolean value like so:

function prequal(car) {
if (car.mileage > 10000) {
return false;
} else if (car.year > 1960) {
return false;
return true;

The important part (and the part that stumped me) was that the object passed to the function in this case was called car instead of taxi! The reason we’d want to call it car is because we may want to pass several similar car objects up to the function, with all of them having different properties.

So let’s save the value the function returns to a variable called worthALook. (note that the taxi object reference is in the prequal parameter, not literally the object taxi) Then, using another if/else statement, we’ll log to the console a string, concatenating the object properties in there as well.

var worthALook = prequal(taxi);
if (worthALook) {
console.log(“You gotta check out this ” + taxi.make + ” ” + taxi.model);
} else {
console.log(“You should really pass on the ” + taxi.make + ” ” + taxi.model);

The main take-away is this:
When passing an object up to a function as a parameter you can use an object name that can refer to all your objects. This was the first thing in the “Head First JavaScript” series that had me stumped and I had to go back and pull out of the chapter why the object taxi/car can be called using the name car instead of taxi.

Author: John McKirdy

Husband, Father, Computer nerd, Fat fitness junkie, MMA fan, Wildebeest

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s