Asked  7 Months ago    Answers:  5   Viewed   35 times

I have a global variable in JavaScript (actually a window property, but I don't think it matters) which was already populated by a previous script but I don't want another script that will run later to see its value or that it was even defined.

I've put some_var = undefined and it works for the purpose of testing typeof some_var == "undefined" but I really do not think it's the right way to go about it.

What do you think?

 Answers

21

The delete operator removes a property from an object. It cannot remove a variable. So the answer to the question depends on how the global variable or property is defined.

(1) If it is created with var, it cannot be deleted.

For example:

var g_a = 1; //create with var, g_a is a variable 
delete g_a; //return false
console.log(g_a); //g_a is still 1

(2) If it is created without var, it can be deleted.

g_b = 1; //create without var, g_b is a property 
delete g_b; //return true
console.log(g_b); //error, g_b is not defined

Technical Explanation

1. Using var

In this case the reference g_a is created in what the ECMAScript spec calls "VariableEnvironment" that is attached to the current scope - this may be the a function execution context in the case of using var inside a function (though it may be get a little more complicated when you consider let) or in the case of "global" code the VariableEnvironment is attached to the global object (often window).

References in the VariableEnvironment are not normally deletable - the process detailed in ECMAScript 10.5 explains this in detail, but suffice it to say that unless your code is executed in an eval context (which most browser-based development consoles use), then variables declared with var cannot be deleted.

2. Without Using var

When trying to assign a value to a name without using the var keyword, Javascript tries to locate the named reference in what the ECMAScript spec calls "LexicalEnvironment", and the main difference is that LexicalEnvironments are nested - that is a LexicalEnvironment has a parent (what the ECMAScript spec calls "outer environment reference") and when Javascript fails to locate the reference in a LexicalEnvironment, it looks in the parent LexicalEnvironment (as detailed in 10.3.1 and 10.2.2.1). The top level LexicalEnvironment is the "global environment", and that is bound to the global object in that its references are the global object's properties. So if you try to access a name that was not declared using a var keyword in the current scope or any outer scopes, Javascript will eventually fetch a property of the window object to serve as that reference. As we've learned before, properties on objects can be deleted.

Notes

  1. It is important to remember that var declarations are "hoisted" - i.e. they are always considered to have happened in the beginning of the scope that they are in - though not the value initialization that may be done in a var statement - that is left where it is. So in the following code, a is a reference from the VariableEnvironment and not the window property and its value will be 10 at the end of the code:

    function test() { a = 5; var a = 10; }
    
  2. The above discussion is when "strict mode" is not enabled. Lookup rules are a bit different when using "strict mode" and lexical references that would have resolved to window properties without "strict mode" will raise "undeclared variable" errors under "strict mode". I didn't really understand where this is specified, but its how browsers behave.

Tuesday, June 1, 2021
 
Crashthatch
answered 7 Months ago
42

You will need to store the count variable on a server-side control in order to do this.

Example:

<script type="text/javascript">
    var count = 0;

    jQuery('td').click(function () {
        if ($(this).hasClass('process')) {
           count = count + 100;
           alert(count);
           // Store the value in the control
           $('#<%= example.ClientID %>').val(count);
        }
     });
</script>

<asp:HiddenField ID="example" runat="server" />

Then, in your code-behind simply use:

int value;
if (Int32.TryParse(example.Value, out value))
{
     // Do something with your value here
}
Saturday, June 26, 2021
 
muaaz
answered 6 Months ago
28

You should not pass a in parameter of timer function to access the global variable a. When a is passed to timer function the value of global variable is used but in timer the parameter variable is local to timer function and changing the value of it wont change the value of global variable. It means you have two variables in your code having name a one is global and other is local to timer function and you are changing value of local variable of timer.

a = 100;
var i = setInterval( timer, 1000 );

function timer() {
    console.log( a );
    if ( a < 1 ) {
        console.log( 'Reaching Stop' ); 
        clearInterval( i );
        return;         
    } 
    a -= 1;
}
Friday, July 30, 2021
 
Karsten
answered 4 Months ago
19

[...] is there any way to create a function to check if a variable exists and is defined [...]

No there is not. When you pass a variable to a function, it will always try to resolve that variable. If it is not declared it will throw a reference error.

Relevant section from the ECMAScript specification.

You have to check whether the variable is declared via typeof before you pass it to a function.

Sunday, August 29, 2021
 
makadev
answered 3 Months ago
22

Simply run replace on your string...:

var name = 'John';
$('.whatever').attr('addthis:title', function(i, attr){
    return attr.replace('[firstName]', name);
});

P.S. Are you sure you want an attribute addthis:title, not simply title? That's invalid HTML! If you want to create your own attributes, prefix them with data-:

<div class="whatever" data-addthis-title="Hi, your name is [firstName]"></div>
Thursday, November 25, 2021
 
Efog
answered 5 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share