Behrouz Riahi
Behrouz Riahi

Reputation: 1791

NodeJS - My method doesn't execute

inside my file ./functions/login_registration_functions.js

I have the following code

var methods = {
    check_if_not_null: function (item_to_be_checked, item_to_store_the_checked_item) {
        if(item_to_be_checked != null){
            item_to_store_the_checked_item = item_to_be_checked;
        }
}
};

module.exports = methods;

and I am calling it inside my routes.js file

var log_reg_funcs = require('./functions/login_registration_functions.js');

and I am calling the method inside my put call

log_reg_funcs.check_if_not_null(req.body.title, request.title);

but it doesn't work. when I replace the above code with below:

if(req.body.title != null){
            request.title = req.body.title;
        }

it works fine

why am I missing here?

Upvotes: 0

Views: 37

Answers (1)

rsp
rsp

Reputation: 111258

When you are doing this:

item_to_store_the_checked_item = item_to_be_checked;

when item_to_store_the_checked_item is the argument to your function, then you are not changing the original variable that was used when calling your function but only your local copy of the passed value that is in your function.

If you passed and object and changed one of its properties then it would work as you expect.

For example if you had:

var methods = {
    check_if_not_null: function (item_to_be_checked, object_to_store, object_key) {
        if(item_to_be_checked != null){
            object_to_store[object_key] = item_to_be_checked;
        }
    }
};

then you'd be able to do:

log_reg_funcs.check_if_not_null(req.body.title, request, 'title');

(it's strange for JavaScript to use underscores instead of camelcase but I'm keeping your style here)

Upvotes: 2

Related Questions