Reputation: 73
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
Upvotes: 5
Views: 34745
Reputation: 1137
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.
Upvotes: 8
Reputation: 1530
There are many ways of doing this and by far the best way is to declare your variables outside the function, then assign them inside the function.
var sample;
var myname;
function a() {
sample = "Hello World";
myname = "Solly M";
}
console.log(sample);
console.log(myname);
Upvotes: 4
Reputation: 6488
The best way to do this is to have the function returning a value
function a(){
var sample = "hello world";
return sample;
}
sample2 = a();
console.log(sample2);
Upvotes: 4