Overriding JSON variables globally

In my project, I needed to utilize json2.js since the JSON object in the browser (IE8) was not capable of parsing strings into JSON.

After reviewing json2.js, I have a question regarding the variable declaration within it.

The json2.js file declares a global variable like this: check here for more information

var JSON;
if(!JSON){
    JSON={};
}

I am wondering about the impact of declaring var JSON; on the global JSON object. I expected that the declaration would override the global JSON object in any browser (IE8/IE7). However, I found that it does not override when a global object is already available. Does this mean that only a variable definition/initiation can override a global variable? Please provide clarification.

Answer №1

When it comes to each variable declaration (not initialization!), the following process occurs (section #10.5):

8. For every VariableDeclaration and VariableDeclarationNoIn in the code, follow these steps in sequential order according to the source text:

  1. Identify the Identifier in d as dn.
  2. Determine whether a binding for dn already exists by calling env’s HasBinding concrete method.
  3. If no binding exists for dn, then
    1. Create a mutable binding using env’s CreateMutableBinding concrete method with arguments dn and configurableBindings.
    2. Set the mutable binding by calling env’s SetMutableBinding concrete method with arguments dn, undefined, and strict.

Thus, whenever var x is encountered, it checks if a variable named x is already present in the environment. If so, it is disregarded; if not, the variable is declared and initialized with undefined.

Since the code runs in global scope, it verifies the existence of JSON in the global scope. Therefore, if JSON already exists, var JSON; is simply ignored.


Some reflections on testing/explaining this behavior:

I'm unsure exactly when the JavaScript execution creates the global object, but I presume it happens before evaluating other scripts. This implies that JSON exists with a value even before any variable declaration, a scenario only achievable by including two separate scripts (they can be inline).

Experiment with:

// script1.js
var foo = 'bar';

// script2.js
var foo;
if(!foo) {
    foo = 'baz';
}
alert(foo);

// include script2.js after script1.js

What result do you expect? (find out here).


In a single script file, all variable declarations are lifted to the top anyway. So, if you have:

var foo = 'bar';
var foo;
if(!foo) {
    foo = 'baz';
}

The script essentially runs like this:

var foo;
var foo;
foo = 'bar';
if(!foo) {
    foo = 'baz';
}

You cannot verify if the second var foo; overrides the first one because it lacks a value at that point. Hence, this example doesn't effectively showcase the mentioned behavior.

Answer №2

Using the var keyword guarantees the presence of a variable within the enclosing function or global scope, such as the window object, without initializing it.

The order of declaration does not have any significant impact.

Consider the following code snippet for instance :

a = 3;
var a;
alert(a);

It will display "3".

Therefore, the var declaration in your code sample ensures that there are no errors during testing and does not overwrite the existing value of the variable.

It is important to remember this, as a common mistake in JavaScript is to inadvertently declare a variable multiple times within a function, leading to unexpected results due to values being set before the var declaration. Try running this example, for instance :

if (true) {
    a = 3;
}
// lengthy code goes here, at a different level
if (true) {
    var a;
    if (433/43==3) a=true;
    if (a) alert('should not happen');
};
​

Indeed, the var keyword is associated with the function scope, rather than the block scope...

Answer №3

If you're unable to choose another option, there's also the possibility of switching IE8 to compatibility mode in order to restore the native JSON object:

// added to your preinit page event
Response.AddHeader("X-UA-Compatible", "IE=8");

Alternatively, you could consider creating the JSON variable only if it hasn't been created yet:

var JSON = JSON || {};

Answer №4

When running the code block in the global scope, the variable JSON will replace the global JSON object with undefined.

However, if you are in a different scope, such as within a function, this action will have no impact.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...

Retrieving data from Firebase in json format and populating a TableView using Swift 3

I've been working on converting the code below from Swift 2 to Swift 3, but I'm running into some errors. While I've managed to fix some of them, there are still a few that I can't seem to resolve. Any assistance would be greatly apprec ...

What is the best way to link options from a select directive with a different array?

Update: the working jsfiddle can be found here: http://jsfiddle.net/robertyoung/jwTU2/9/ I'm in the process of developing a webpage/app using AngularJS. The specific functionality I aim to achieve involves allowing users to add a row to the timecard ...

Tips for preventing the occurrence of undefined when retrieving data?

After fetching data from mongo, I encountered an issue where my useState([]) is initially defined as undefined. Can someone please offer a solution to this problem? const router = useRouter() const {id} = router.query console.log(id) // f ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...

Looking to prevent editing on a paragraph tag within CKEditor? Simply add contentEditable=false to the

Within my CKEditor, I am in need of some predefined text that cannot be edited, followed by the rest of my content. This involves combining the predefined verbiage (wrapped in a p tag) with a string variable displayed within a specific div in CKEditor. The ...

Guide to consistently fetching and parsing JSON data from a REST API using Spring Boot

Keeping track of a remote server that continuously provides data in JSON format can be achieved through a REST API called . If you wish to gather this data seamlessly in Spring Boot, refer to the example JSON response provided by the REST API: { "run-stat ...

What is the significance of receiving an error in Internet Explorer when running the code below?

function checkStepValidity(isValid, dataModel) { if (isValid) { updatedDataModel = mergeObjects(this.updatedDataModel, dataModel); } }, The code above encounters the following error in Internet Explorer / Edge browse ...

Matching Javascript Variables to CSS Styles

I am currently developing a small HTML page and I am utilizing JavaScript to retrieve the screen dimensions. However, I am facing an issue with passing this variable to a CSS style as shown below. How can I achieve this successfully? Additionally, I have ...

What is the best way to ensure that empty strings are not included in the length of my array?

I have encountered an issue with a JSON file that I fetch. The array syllables is capable of holding up to strings max. However, when I exclude 2 words, I end up with 2 words and 2 empty strings. Nevertheless, my front-end still expects 4 "strings". So, it ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

Is there a way to display a success message once the button has been activated?

<template> <div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Enter ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below https://i.sstatic.net/qUFP6.png This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, ...

Error encountered: The Bootstrap Carousel function is causing a TypeError as e[g] is not defined

I am attempting to build a dynamic bootstrap carousel using my json data, and I have implemented jQuery-Template for rendering. Essentially, I am generating the carousel slider on-the-fly from my json data with the help of jQuery-Template. Here is a snippe ...

Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists. A URI (/data/mydata.json) can be accessed to retrieve the following data: [["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]] Despite a ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...

Serializing a dictionary with frozen attributes classes as keys using Python's attrs/cattrs

My goal is to organize and disorganize an attrs object, which comprises dict fields utilizing simple frozen attrs for the dict keys. While this method works effectively for objects generated at runtime, the frozen attribute proves challenging when attempti ...