1

So I'm learning Javascript and I see this code:

var apple = {//... an object with some properties};
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple});

Where someMethod and a_property_of_apple are valid methods and properties.

My question pertains to the argument, b, of the anonymous function which is not declared or defined anywhere else:

function (b) {return ...

What is going on here? What is b and why is it being used?

Apologies in advance for the basic nature of the question. If someone just wants to drop some focused terms on me to read up on that would be great short of an explanation.

3
  • Try looking for "first class function" in the search, or "callback function". Commented Jul 21, 2017 at 22:03
  • 1
    That's a parameter, just like any other parameter of any other function. It gets passed from the caller, like any other function call. Commented Jul 21, 2017 at 22:04
  • someMethod has logic in it that is expecting a call back method with one parameter. So, when it hits that line in someMethod where it calls the callback (the function with 'b' as a parameter) it hands in whatever it wants as a parameter. Basically, someMethod decides what 'b' is. Commented Jul 21, 2017 at 22:06

4 Answers 4

2

The anonymous function is a callback function being passed to the apple.method() invocation.

apple.method() will invoke that anonymous function at some point during it's execution, ( or pass it to another function ). Whenever it's invoked it will be invoked with an argument that will be available inside the callback. You could call it b, or response, or whatever you want (logical names are best) and be able to use it within the anonymous function.

You should read about Callback functions over at MDN.

EDIT: I will explain the parts to you

var apple = {} This is the definition of an object

var fruit = apple.someMethod(function (b) {return b.a_property_of_apple}); is defining that fruit is equal to the return value of the invocation of apple.someMethod(...)

apple.someMethod(function (b) {return b.a_property_of_apple}); is the invocation of apple.someMethod with function (b) {return b.a_property_of_apple} as the only argument.

The b argument in the anonymous function function (b) {return b.a_property_of_apple} will be passed to it's invocation within the apple.someMethod.

Here is an example snippet.

// define apple
var apple = {
    // define method
	someMethod: function( callback ) {
		var obj = {
			a_property_of_apple: "Eat me!" // this will be returned
		}

        // return the invocation of callback with obj as argument
		return callback(obj);
	}
}

var fruit = apple.someMethod(function (b) {return b.a_property_of_apple});

console.log(fruit);

EDIT: Ok, going to use something slightly less abstract as an example.

// notice employees being passed to this function
// that is called an argument and is usable inside the function
var orginization = function( employees ) {
   // this will take the empoyees argument and assign it to this.employees
	// or set this.employees to an empty array if there is no employees argument
	this.employees = employees || [ ];

	// this is a method ( a method is a function on an object )
	// this function takes 3 arguments
	this.addEmployee = function( employee ) {
		// we use the 3 arguments to push a new object with title, name, and salary
		// properties provided by the function arguments
		this.employees.push( employee );
	}

	// this method returns the value stored in this.employees
	this.getEmployees = function() {
		return this.employees;
	}
}

// this is a variable an array of employees only containing 1 employee
// i will use it in the creation of my new orginization
var employess = [
	{
		title: "CEO",
		name: "Enola",
		salary: "$$$$$$$"
	}
];


// i use the new to create learningInc from originization( employees )
// originization is a constructor function which creates an object
// with methods and properties found on the constructor
var learningInc = new orginization( employess );


// console.log learningInc.getEmployees() an you will see still only the CEO
// works here

console.log( "before newHire: ", learningInc.getEmployees() );

// lets make a newHire
var newHire = {
	title: "Peon",
	name: "Sadly McFrownFace",
	salary: "$"
};

// add the newHire to the employess of learningInc wth out getEmployees() method
learningInc.addEmployee( newHire );


// log the new value of learningInc.getEmployees and you see we now have 2 employees
console.log(  "after newHire: ", learningInc.getEmployees() );

Ok now notice this line var learningInc = new orginization( employess );

The employees variable I'm passing to this function as an argument is used in this function var orginization = function( employees ) { ... }.

Hope this help.

Sign up to request clarification or add additional context in comments.

14 Comments

You're welcome. If this solved you problem, please accept it as the answer :)
Ok. So I read the article suggested on MDN. Thank you. It helped the situation when a callback function is defined. Then in our example where the a presumed callback function, 'd', is not define explicitly, such as... function d () {// do something}; Is 'd' taking some return value from apple.someMethod(); as it's assignment value?
I'm not sure what you mean by "presumed callback function, 'd"
From the paradigm on the MDN page, I'm assuming that what is being passed as the parameter and assigned 'd' is a function.
if you are talking about function (b) { ... } the b is a argument passed to the callback function from within the invoking method. What you are talking about function d () { ... } though I don't know where you got that block of code from, yes d would be the name of the function in that situation.
|
0

My question pertains to the parameter, b, of the anonymous function which is not declared or defined anywhere else: What is going on here? What is b and why is it being used?

Why you say it is not declared? It is declared right there. Consider this simple JavaScript function:

function doSomething(a, b){
  //do something here;
}

In this code, we are creating a function, naming it "doSomething", and declaring two parameters for it a and b. This is how we declare function parameters in JavaScript. Now your example:

function (b) {return ...

is exactly the same, except we didn't give this function a name, which means it is an anonymous function. That's the only difference, but its parameter b is declared right there like any standard function. So there is nothing special going here, it's a standard function parameter and used as such.

2 Comments

Originally, one of my sources of confusion was less what 'd' is, it's a parameter, but more what it contained or was assigned. Now I believe it to be the object 'apple' in this case. And that the accessor function; function (b) { return b.property; } is returning a value back to the method that called it. I think this is what's going on.
Like any parameter, it gets assigned whatever you pass to the function when you call it. In your example, you call it like this callback(obj), so it is assigned the object obj. And it is returning b.a_property_of_apple.
0

There are a couple concepts at work here

  1. Function declarations vs function expressions; you can use function as an operator to define a function, and assign the function to an identifier and pass it around like any normal object
  2. Callbacks; you can pass a function CB into another function A to be called by A (as defined by A)
  3. Passing something without an identifier

Function Declaration

// declare function
function foo(argFoo) {
    console.log('foo', argFoo);
}

// invoke function
foo('was declared'); // "foo" "was declared"

Function Expression

// express function
var bar = function (argBar) {
    console.log('bar', argBar);
};

// invoke function
bar('was expressed'); // "bar" "was expressed"

Callbacks

function fizz(callback) {
    console.log('first I fizz');
    callback();
}

function buzz() {
    console.log('then I buzz');
}

fizz(buzz);
// "first I fizz"
// "then I buzz"

Passing without an Identifier,
Basically, defining things in-place

// say we have some fn fizzbuzz
function fizzbuzz(foo) {
    console.log(foo);
}

// we could pre-define what we want to pass to it
var i = 1;
fizzbuzz(i); // 1

// or we could pass directly
fizzbuzz(1); // 1

// with anything we like
fizzbuzz({some: 'object'}); // {some: "object"}

// even a function
fizzbuzz(function () {}); // function () {}

2 Comments

bar('is expressed') is actually a function invocation. The expression if the code block between the { ... do stuff ... } that resolves to a value.
@KyleRichardson I've added a few comments to make that section clearer
0

Maybe if I break down what is happening into more readable code, you can see what is happening.

someMethod is a method that take a function as an argument. This is more easily seen when broken down like below.

It's up to someMethod to determine what they do with that function. In this example, I am executing the function being passed into someMethod and passing it my this context.

var apple = {
  name: 'Apple',
  someMethod: function(func) {
    return func(this);
  }
};

function getName (b) {
  return b.name;
};

const name = apple.someMethod(getName); // Apple

To your question: b is defined as the first argument to your anonymous function. This is more clearly expressed when the code is broken out above. But you could also express it like this:

const name = apple.someMethod(function(x) { return x.name; }); // Apple

or like this using ES6:

const name = apple.someMethod(x => x.name); // Apple

1 Comment

Bingo! Your example cleared all ambiguity for me. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.