How to access global variable in function hook in javascript? - javascript-objects

I want to use global variable 'x' in the below hook funcion.
var x = 10; //global variable
var oldA = a;
a = function a(param){
alert(x); //showing error: x is undefined
return oldA(param);
}
How to resolve the error?

Your code works fine for me, but you might want to resolve x to the global variable explicitly by using window.x.
When not in a browser environment, or an environment where the global object isn't called window, try:
(window || root || global || GLOBAL || this || self || {x: undefined}).x
The {x:undefined} object literal is just to make sure the expression doesn't throw up errors.I've listed pretty much all names I know of that are given to the (strictly speaking nameless) global object, just use the ones that might apply to your case.
On the other hand, if the global variable x might be reassigned by the time the function (a) gets called, a closure would be preferable:
a = (function (globalX)
{
return function a(param)
{
console.log(globalX);
return oldA(param);
};
}(x || window.x));//pass reference to x, or window.x if x is undefined to the scope
Of course, if you're in strict mode, you need to be careful with implied globals, too.
That's all I can think of that is going wrong with your code, some more details might provide us with a clue of what's actually happening...

To access global Js variable inside function, don't use Var in function scope and mention var in global scope.
Eg.
<script>
var foo = "hello";
function fxn() {
alert(foo);
foo = "bai";
}
fxn();
alert(foo+"out side");
</script>

Related

ESLint throws no-undef even if variable is in IF statement

I am using React and I am not able to build my application as long as I have undefined variable. I am using that variable only in IF statement (if it's defined, use it).
if (something)
const newItem = 'wow!';
if (typeof newItem === "undefined")
console.log('newItem undefined')
else
console.log(newItem); //ESLint: Line YY:XX: 'newItem' is not defined no-undef
How can I avoid this behavior?
An if statement creates a lexical scope. In fact, any time you see {} in javascript, that creates a scope. What that means is that variables declared with let or const in that scope cannot be accessed outside of that scope.
if (something) {
const newItem = 'wow!';
// newItem exists here
}
// newItem does not exist here
What you want to do is declare the variable in the scope where you want to access it, and then just assign to that variable in your if statement:
let newItem;
if (something) {
newItem = 'wow!';
}
// newItem exists here, and has a value of either 'wow!' or undefined.
Note that I had to change the variable declaration from const to let because we need to assign a value to the value after its creation, so it can no longer be a constant.

How does "arguments" keyword work in Javascript?

I came across this little exercise and I am not really sure how the "arguments" keyword works here and also why (...arr) is placed where it is as it is outside of the a's declaration parentheses...
var arr = ["tic", "tac", "toe"];
var a = (
function() {
return arguments[2];
}
)(...arr);
console.log(a);
Could you please explain or point me to a relevant source as I am not sure what I am actually looking for? Thank you.
arguments is the array of arguments passed to the current function. In the above code example, the function within the parentheses is being called with ...args as the arguments.
In JS, you need not name a function to call it. The above code is equivalent to the following:
var arr = ["tic", "tac", "toe"];
var callme = function() {
return arguments[2];
}
var a = callme(...arr);
console.log(a);
The arguments in the function call are being passed with "spread syntax."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
So the function is being called with the values of arr as it's arguments, and is returning the third argument arguments[2].

Kotlin - Val cannot be reassigned , but can be reassigned by accessing from index?

I have these two functions where i am trying to modify the elements. One of them compiles and other says 'val cannot be reassigned'. What is the difference between the following functions? Why does one compile and the other does not?
The one that compiles
fun <T> Array<T>.mapInPlace2(transform: (T) -> T) {
for (i in this.indices) {
this[i] = transform(this[i])
}
}
The one that says
Val cannot be reassigned
fun <T> Array<T>.mapInPlace1(transform: (T) -> T) {
for (i in this) {
i = transform(i);
}
}
Similiarly to how function parameters are final in Kotlin, so are the variables used in for loops. Essentially, writing down...
for (i in array) {
...
}
... is the equivalent of doing this in Java:
for (final int i : array) {
...
}
This helps catch some common errors, in this case - if the compiler allowed you - you'd be reassigning this local variable that just contains a reference to the real element, without changing the array. In Java terms, you'd be doing this:
for (int i : array) {
i = transform(i);
}
This new value of i is unused, it doesn't change the array itself, and it will be immediately overwritten by the value of the next element when the loop comes around.
Try this:
for(i:Int in 0 until this.size) {
this[i] = "your value"
}
You're confusing the mutability of references to objects and objects themselves.
In the first example, the structure is mutable, but the reference to it is immutable. You can change the structure of the object itself, but you can't change what structure the references points to.
In the second example, you're trying to change an immutable reference to an object, not the object itself.
If you write
val i = obj
obj can still be mutated if it's a mutable object. i can't be reassigned though, sine the reference can't be changed.

Variable becoming undefined in Promise function

I have an array (targets) in global scope, the values of which I am passing to an external function [third party library, externalConverter] that does some text conversion. The values of this array are being passed in to the convert function and the conversion is happening fine.
const targets = [‘box’, ’box1’, ’box2’, ’box3’]
for (var i = 0; i < targets.length; ++i) {
console.log(targets[i]); // this is coming out fine
externalConverter
.convert(data.text, targets[I])
.then(results => {
data.convertedText.push({
[targets[i]]: results[0]
});
//above convertedText array comes out as
//{“undefined: ”, “nice converted text”}, ...
})
}
Inside the result of the Promise, I am trying to access the targets values but getting undefined values inside the function above. I am not sure why targets is suddenly becoming undefined
Any ideas?
The value of i will have progressed to its final value (i.e. targets.length) before any of the then callbacks have executed, and so any use of i as index will be out of range.
Use let i instead of var i to make separate instances of i that will not have this problem.

Returning variables

Here I have a basic doubt. Here it says that I need not to return global variables.
Now, I am wondering, if I return a global variable (let it be char or int or some other data type), what horrid does it cause?
I know that, when I return a variable from a function, the variable is destroyed immediately.
Does it mean, the memory allocated to that variable is de-allocated/freed?
Can someone please shed some light?
Consider the following code:
#include<stdio.h>
int var; //a global int
int MyFuction(void)
{
int temp_var = 0;
temp_var++;
return temp_var; //it will get destroyed after returning
}
int main(void)
{
MyFunction();
var++;
return var; //Will it get destroyed here, (var being a global variable)?
}
var is gloabl variable it doesn't destroyed after return statement, its life is till program executes and scope is every where in code.
Only variable local to functions goes out-of-scope and destroyed after return statement.
Note: There is two things life and scope.
Life of local variable is till function returns. And scope is within function its memory comes from stack.
Life of global varialbs is till program terminates and scope is every where in C.
int main(void)
{
MyFunction();
var++;
return var; //Will it get destroyed here, (var being a global variable)?
}
No, it won't. Objects with static storage duration (like var here) are destroyed at program termination.
the global variable will not get destroyed as they have a lifetime(the time till they are accessible) is that of the whole program.

Resources