2

I am currently learning node.js and already meet several times the same problem that seems very simple but I can't still understand how to solve it.

Code:

var SRC_PORT = 6025;
var dgram = require('dgram');
var clientUDP = dgram.createSocket("udp4");
var test

clientUDP.bind(SRC_PORT, function () {
    multicastNew()
});

function multicastNew() {
    var test = 777
    console.log(test);
}

Problem Cant use variable test content outside the function multicastNew()

In the function multicastNew() I have a variable var test. In that function multicastNew() I gave to test = 777. When I want to console.log(test) in the same function multicastNew() everything works,it outputs 777. The problem is that when I want to console.log(test) outside function multicastNew() it outputs undefined.

Can you please explain me how to solve this issue and why it is. Thank you!

Chris
  • 884
  • 2
  • 11
  • 22

2 Answers2

7

You should change var test = 777; to test = 777; in mulitcastNew(). Your code should be as such:

var SRC_PORT = 6025;
var dgram = require('dgram');
var clientUDP = dgram.createSocket("udp4");
var test;

clientUDP.bind(SRC_PORT, function () {
    multicastNew();
});

function multicastNew() {
    test = 777;
    console.log(test);
}

A note on scope. In Javascript, functions create scope. Any variable defined with var inside of a function is a local variable, invisible outside the function. It's only local to the wrapping function, and if there is no wrapping function, it becomes a global variable.

Consider the following:

//this is global scope
var a = "Chris";
var b = "Inspired";

function nameChange(){
    var a = "inspired"; // local to the function nameChange()
    b = "Chris"; //without var we are changing the global variable
    console.log(a); //will output inspired
}
nameChange(); // inspired
console.log(a); // Chris
console.log(b); // Chris
Abdullah Rasheed
  • 3,562
  • 4
  • 33
  • 51
  • The problem is that in the function multicast I am adding a value to the varialbe test and afterwards I want to use the same variable with its value in another function. – Chris Nov 11 '15 at 20:44
1

It's all about function scope. When u declare var test = 777, then u are creating new variable in scope of your function multicastNew(). This variable covers your 'main' variable from the global scope... So your function works from now on your local variable, not on the one from the global scope.
JavaScript always look for variables inside scope it is called. In your example, when u try to call test outside the multicastNew(), then current scope is GLOBAL, so it finds your var test from the begining of your code. It's always work from inside to outside (closures).

You can read:
Scopes

Community
  • 1
  • 1