How to access variables inside a function in javascript - javascript

I have the code:
var here;
function setNews(data2){
here = data2;
console.log(here);//1st console log
}
console.log(here);//2nd console log
in the 1st console log the the data inside here are printed but in the 2nd console log it prints undefined how can i access the data inside the setNews function so that I can use it outside setNews.
Thank you.

Probably you need to review your architecture.
var here;
function setNews(data2){
here = data2;
console.log(here);//1st console log
}
//executed immediatly, `here` is not yet initialized by setNews
console.log(here);//2nd console log
Variable 'here' is being output to the console immedialy when javascript is loaded, but since it's undefined, console shows 'undefined'.
When later you call setNews('sample'), it will set global variable here but there is no point in that, because it was already outputted.

var here;
function setNews(data2){
here = data2;
console.log("inside function " +here);//1st console log
}
setNews("something");
console.log("outside function" +here);//2nd console log
Fiddle: http://jsfiddle.net/bmArj/

// initialize this to desired value.
var here = "your value";

I think...use return...
var here = setNews(2);
function setNews(data2){
here = data2;
console.log(here);//1st console log
return here;
}
console.log(here);//2nd console log

Please read this article on JavaScript Variable and Function Hoisting.
What happened is when you first declare the variable here, it wasn't initialized.
When you give here a value inside function setNews(), its value is not available to the outer console.log.
So you need to call setNews() first before displaying the content of here in the second call to the console, like so:
var here;
function setNews(data2){
here = data2;
console.log(here);//1st console log
}
setNews("some data here");
console.log(here);//2nd console log, it will display "some data here"

If you want to define a variable, (let's call it "here") that is automatically set to the value of some function named "setNews," then this might work better:
var here,
data2 = "the news!";
// Set value of "here" to processed data2
here = (function (news) {
// Process news
news = "This is " + news;
return news;
})(data2);
console.log(here);
// Prints "This is the news!"

Related

Using a variable that has yet to be declared

I have a problem understanding Javascript's engine technique called hoisting.
I've tried to create a var in the top of my file to quickly access and edit, but i want to use a variable that has yet to be declared.
First attempt:
var easy_to_edit_value = "some text " + a_yet_to_be_defined_var;
//imagine loads of code so its hard to find the correct funtion to edit the log
function my_function (a_yet_to_be_defined_var){
console.log(easy_to_edit_value);
}
my_function("more text");
This generates an error at line 1 since a_yet_to_be_defined_var is not defined.
After looking at this post: post-by-apsillers i tried again but this time declaring the var without value (so its known but undefined untill declared somewhere futheron)
var a_yet_to_be_defined_var; // now its known so this error is gone
var easy_to_edit_value = "some text " + a_yet_to_be_defined_var;
function my_function (a_yet_to_be_defined_var){
console.log(easy_to_edit_value);
}
my_function("more text");
//still undefined
//new attempt with a fresh var being set in the function before being called
var new_var;
var easy_to_edit_value = "some text " + new_var;
function my_function2 (a_yet_to_be_defined_var2){
new_var = a_yet_to_be_defined_var2;
console.log(easy_to_edit_value);
}
my_function2("more text");
//still undefined
But this outputs: some text undefined where i was expecting the some text more text since i filled the var before asking for it.
Please note these functions aren't ran using my_function("something") but are triggered by this: client.on('message', my_function);, i've seen arrow function solutions for related questions but i'm not sure how i would get that to work here.
Is it possible to make this work?
Instead of defining a value called easy_to_edit_value, change it to a function called easy_to_call_function that will return "some text " concatenated with the current value of new_var.
Once a (var or let) variable is assigned, it must be reassigned or reevaluated each time.
let new_var;
const easy_to_call_function = () => "some text " + new_var;
function my_function2(a_yet_to_be_defined_var2) {
new_var = a_yet_to_be_defined_var2;
console.log(easy_to_call_function()); // Call the function
}
my_function2("more text");
You need to re-declare the variable inside of the function:
var new_var;
var easy_to_edit_value = "some text " + new_var;
function my_function2(a_yet_to_be_defined_var2) {
new_var = a_yet_to_be_defined_var2;
easy_to_edit_value = "some text " + new_var;
console.log(easy_to_edit_value);
}
my_function2("more text");
If one variable is changed, other variable will not update according to the new value. That kind of programming requires a really high level compiler, which not many people are willing to make. The programmer must update variables on their own.

Undefined results on calling module.exports in nodejs

my app.js contents:
var greet3=require('./greet3');
greet3.greet();
my greet3.js contents
function Greetr(){
this.greeting='greet3';
this.greet=function(){
console.log(this.greeting);
}
}
module.exports=new Greetr();
my console window output : greet3
but when i change the contents of app.js as :
var greet3=require('./greet3');
greet3();
i get the ouput as 'undefined'
I am a beginner in node.js and was trying different module patterns in it.I need help on why I am getting the result as undefined
Given your above module, the line
var greet3=require('./greet3');
essentially becomes:
var greet3 = {
greeting: "greet3",
greet: function(){
console.log(this.greeting);
}
}
So in app.js, greet3 is now an Object. greet3.greet(); works as expected and logs "greet3".
But greet3() produces greet3 is not a function, since greet3 isn't a function.
You are exporting a initialised object, when you set var greet3=require('./greet3') and call greet3() you are trying to use the object as a function, hence it says undefined.
Change your code in greet3.js:
module.exports = function(){
this.greeting='greet3';
this.greet=function(){
console.log(this.greeting);
}
}
As others said before, your code is working as expected.
Your module:
function Greetr(){
this.greeting='greet3';
this.greet=function(){
console.log(this.greeting);
}
}
module.exports=new Greetr();
Returns an object, but I think you wanted to return a function, so the last line should look like this:
module.exports=Greetr;
Instead of this:
module.exports=new Greetr();
Because now when you call:
var greet3=require('./greet3');
greet3();
It assigns object of function Greetr to a variable greet3 and you cannot call an object.

How to get console.log output from eval()?

I am using eval() to run a script from a string. Below is the code:
eval('console.log("hello")');
I will get hello from the console output. I wonder whether I can save the hello into an variable in the current context. So I am looking for something like this:
const output = eval('console.log("hello")'); // I expect the console output is returned from eval() function.
But I get an undefined response. Is there a way for me to do that?
It is impossible because console.log() only returns undefined, however you can make a function that will return something.
Example:
console.oldLog = console.log;
console.log = function(value)
{
console.oldLog(value);
return value;
};
const output = eval('console.log("hello")');
Hope this will help.
While the first answer works, it causes a "Maximum call stack size exceeded" error for my case.
Think this might be a better solution.
const originalLog = console.log;
console.log = function (...value) {
originalLog.apply(console, value);
return value;
};
const response = eval(code);
Have you try this?
out = ''
console.log = function(val){out = out + ' ' + val}
eval('console.log("test string")')

Passing value in function properly in AngularJS

I have the following function which takes variable description as parameter
$scope.relsingle = function(description) {
console.log(description);
var url = $scope.url+'/api/descrelation?limit=4&description='+description;
$http.get(url).success(function(data) {
console.log(data);
$scope.apgresponse = data;
})
};
I use the following approach to pass this value in the html page
ng-init="relsingle(prodres[0].description)"
This value of prodres[0].description comes from here.
And value of prodres comes from here
$scope.prodat = function(id) {
var uri = $scope.url+'/api/getproduct?productid='+id;
console.log(uri);
$http.get(uri).success(function(data) {
console.log(id);
console.log(data);
$scope.prodres = data;
})
};
when i log the value of description in console in the relsingle function.
console.log(description);
This gives me value undefined.
You can't do it like this with ngInit because it runs only once and when it happence variable prodres is not yet available because it comes from async call.
What you can however do is to make ngInit execute only after the value for prodres has been resolved:
<div ng-if="prodres" ng-init="relsingle(prodres[0].description)">...</div>
Because ngIf has higher priority ngInit will execute only after ngIf.
Well it is because it is because the array has not been evaluated in javascript.Use a call back function and store that array in a variable on the $scope scope.Then you can use it in the function

Problem with Javascript object and accessing property which exists

I have something like this:
var test = {};
function blah() {
test[2] = 'filled';
}
blah(); // ! Hopefully confusion is now averted..
console.log(test);
//result test -> 2:"filled"
console.log(test[2]);
//result undefined
I don't understand why I'm getting 'undefined' in the second instance when according to the first instance, the property of that object clearly exists!
Does anyone have any ideas?
Thanks
OK, it seems that folk are getting confused as to what context the code exists in, for clarity sake I have now added the call to the blah(). but please refer to the comment under Jeff B's response!
Here is an example of relevant code so to say:
mydb = ..... //gets created here with relevant credentials
var test = {};
mydb.transaction(
function(transaction) {
transaction.executeSql("select * from mytable;", [], function(transaction,result) {
var r = result.rows.item(0);
test[2] = r.title;
}, errorHandler);
});
console.log(test);
//result test -> 2:"the title"
console.log(test[2]);
//result undefined
#Dancrumb
Your mention of the single-threadedness of Javascript gave me an idea, and I tried this:
window.setTimeout(function(){ alert(test[2]); },2000);
and it worked! I got the expected value to alert. Can you suggest how I can get around this without using a 'hack' like that above?
Because you aren't calling blah()?
Also, you want:
var test = [];
or:
var test = new Array();
EDIT
I ran the following code:
mydb = openDatabase('note','','Example',1024);
var test = {};
mydb.transaction(
function(transaction) {
transaction.executeSql("select * from mytable;", [], function(transaction,result) {
var r = result.rows.item(0);
test[2] = r.title;
}, errorHandler);
});
console.log(test);
console.log(test[2]);
in Safari 4.0.5
I got the following:
Object
No Properties
undefined
This is what I would expect to see. The object test does not have any properties assigned to it until the callback from mydb.transaction occurs and, since Javascript is single threaded, this cannot happen before the calls to console.log.
Since you're getting a different outcome, can you outline what browser and what version you are using?
This is pretty clearly an asynchronous issue. The simplest way of getting code to run after you set test[2], is to either put the code right there, or use another callback, and call it after you set test[2].

Categories