1

I want to use global variables in my project, but they don't work and I don't understand why they don't work. I'm trying to use them in the following way:

global.connection=null;
function create_connection(connection) {
    connection=12345;
}
create_connection(global.connection);

console.log(global.connection); // returns null, why doesn't it return 12345?
1
  • Not an answer to your quesion, but an advice: Don't use globals. Instead, you can write a file (module) that exports the connection itself and you can require it in other modules. Otherwise you will always have to make sure you called create_connection once, which can lead to nasty bugs. Commented Jan 25, 2016 at 10:59

1 Answer 1

3

Javascript always passes variables by value. So in your case you change the string value without keeping reference to global object.

You could have done this instead

function create_connection(global) {
    global.connection=12345;
}
create_connection(global);

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

2 Comments

Not all variables, but scalar types. Objects are passed by reference.
There is no pass by reference in javascript, when you pass an object you pass the reference, but strictly speaking you still pass the value, which is the copy of the object reference, which is different from passing by reference in C/C++

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.