Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get variable inside the function

Tags:

javascript

hello i'm new in javascript I just want to ask if it is possible to get the value inside a function?

sample code

function a(){
  var sample = "hello world"
};

then i will go to the global context and get the variable sample

sample2 = sample
console.log(sample2);

And when i console.log sample2 then the value of sample2 should be "hello world" please share your knowledge i want to learn more in javascript thanks in advance

like image 623
wiwit Avatar asked Dec 08 '22 20:12

wiwit


1 Answers

Like any other programming language all you need to do is to return the value that you need to access. So either you can make your function return the variable value and that way you can access it. Or make it return a object which further has sub functions with which you can return the value

So following the first approach,

function a() {
    var sample = "hello world";
    return sample;
}

var sample2 = a();
console.log(sample2); //This prints hello world

Or, you can use the second approach where you can alter the private variable by exposing secondary functions like

function a() {
    var sample = "hello world";
    return {
        get : function () {
            return sample;
        },
        set : function (val) {
            sample = val;
        }
    }
}

//Now you can call the get function and set function separately
var sample2 = new a();
console.log(sample2.get()); // This prints hello world

sample2.set('Force is within you'); //This alters the value of private variable sample

console.log(sample2.get()); // This prints Force is within you

Hope this solves your doubt.

like image 148
Akhil Arjun Avatar answered Dec 11 '22 11:12

Akhil Arjun