Fixing Javascript error: mutations are not initialized on VKontakte

Translation of the article “7 tips to handle undefined in JavaScript”

undefined in JavaScript is a real nightmare for a beginner front-end developer. What is the difference between undefined and NULL, if even the comparison NULL == undefined outputs true, and how to handle the undefined error? Let's figure it out.

Note You are reading an improved version of an article we previously published.

  1. What is undefined in JavaScript
  2. How to escape undefined in JavaScript
  3. undefined value in arrays
  4. Difference between NULL and undefined in JavaScript
  5. Conclusion

Manifestations of a "javascript" error

Due to the error, the user will have problems opening videos and playing music tracks. In addition, some members of the social network note that their messages do not open and there are delays in loading pages.

Reference. Before you take specific steps to resolve the problem, you should restart your computer. In some cases, this helps get rid of the error.

In addition to the impossibility of launching multimedia files, the VK system itself will notify a person about problems that have arisen: in the upper left corner of the pages a message will appear on a red background “javascript error adslight is not defined.” The warning may also contain the words “a function”, “CustomMedia” and others. They all indicate the same type of error. Let's look at possible methods to eliminate it.

undefined value in arrays

You get undefined when trying to access an array element with an index outside the array.

const colors = ['blue', 'white', 'red']; colors[5]; // => undefined colors[-1]; // => undefined

The colors array has 3 elements, so the correct indices are 0, 1, and 2. Because there are no elements at array indices 5 and -1, colors[5] and colors[-1] are undefined.

In JavaScript, you may encounter so-called sparse arrays. These arrays have spaces, that is, at some indexes no elements are defined. When we try to access an empty value in a sparse array, the output is undefined:

const sparse1 = new Array(3); sparse1; // => [, , ] sparse1[0]; // => undefined sparse1[1]; // => undefined const sparse2 = ['white', ,'blue'] sparse2; // => ['white', , 'blue'] sparse2[1]; // => undefined

sparse1 is created by calling the Array constructor with a numeric first argument. It has 3 empty elements. sparse2 is created with an array literal whose second element is missing. In any of these arrays, access to an empty element evaluates to undefined.

Cleaning the hosts file

In the Windows system folder there is a hosts file, which is responsible for routing addresses entered in the browser. It can be used by scammers to replace the original VK site, but third-party entries located there also affect the operation of Java elements. The solution in this case is to clean the document and restore it to its original form.

Step-by-step instruction:

  • Open your computer's Explorer and go to the folder located in this path: C:\Windows\System32\drivers\etc. The drive letter may differ if the system is installed on a different partition, but in any case you need to find the Windows folder and then work from there.
  • Open the hosts file using notepad.
  • Remove unnecessary entries after the line “# ::1 localhost”.
  • Save the document and restart your computer.

We recommend: How to add an audio recording to VK

The problem should disappear; if this does not happen, you need to try other options to resolve it.

How to escape undefined in JavaScript

Uninitialized variable

A declared variable that does not yet have a value (not initialized) is undefined by default. Example:

let myVariable; myVariable; // => undefined

The variable myVariable has already been declared, but has not yet been assigned a value. An attempt to access it will result in the output undefined. To fix this, just assign a value to the variable. The less time a variable exists in an uninitialized state, the better.

Below are ways to solve the problem.

const and let instead of var

Objects and variables declared in this way have a scope limited by the current block of code, and are in a temporary dead zone until a value is assigned to them.

When using immutable data (constants), it is recommended to initialize them as const:

const myVariable = 'initial'

The constant is not subject to the uninitialized state, and it is impossible to obtain the undefined value in this case.

Product Owner

Exness, Limassol, Cyprus, Based on the interview results

tproger.ru

Jobs on tproger.ru

If you need to change the value of a variable, then denote it as let and also assign it an initial value:

let index = 0

The problem with var is variable hoisting: wherever the declaration is, it is the same as declaring the variable at the beginning of the code.

function bigFunction() { // code... myVariable; // => undefined // code... var myVariable = 'Initial value'; // code... myVariable; // => 'Initial value' } bigFunction();

In this case, the variable myVariable contains undefined until it receives its value:

myVariable = 'Initial value'

If a variable is declared as let, it will remain inaccessible until a value is assigned to it. So using const or let will reduce the risk of getting an undefined value in JavaScript.

Increased connectivity

Cohesion characterizes the degree of interconnection between module elements (namespace, class, method, code block). Strong cohesion is preferable because it implies that module elements should focus exclusively on one task. This will help the module to be:

  • focused and clear;
  • easy to maintain and refactorable;
  • reusable;
  • easy to test.

A block of code itself can be considered a small module. To benefit from the benefits of strong coupling, you need to keep variables as close as possible to the block of code that uses them.

Here's a classic example of what not to do:

function someFunc(array) { var index, item, length = array.length; // some code... // some code... for (index = 0; index < length; index++) { item = array[index]; // some code... } return 'some result'; }

index, item and length are declared at the beginning of the function, but they are only used towards the end. All the time between declaring the variable at the beginning and before using it in the loop, index and item are not initialized and output undefined. It makes more sense to move the variables closer to where they are used:

function someFunc(array) { // some code... // some code... const length = array.length; for (let index = 0; index < length; index++) { const item = array[index]; // some code } return 'some result'; }

Accessing a non-existent property

An attempt to access a non-existent property of a JavaScript object ends up undefined. Example:

let favoriteMovie = { title: 'Blade Runner' }; favoriteMovie.actors; // => undefined

favoriteMovie is an object with one title value. Accessing a non-existent actors property will result in the output undefined.

Accessing to itself will not cause an error, but if you try to get a value from a non-existent property, an error will be displayed:

TypeError: Cannot read property of undefined

The problem is a feature of JavaScript: the property may or may not be set. A good solution is to set rules that require you to set values ​​for properties.

But it is not always possible to control the objects with which you have to work. Such objects may have a different set of properties in different scenarios, and each of them must be processed manually.

Let's implement the append(array, toAppend) function, which adds new elements to the beginning and/or end of the array:

function append(array, toAppend) { const arrayCopy = array.slice(); if (toAppend.first) { arrayCopy.unshift(toAppend.first); } if (toAppend.last) { arrayCopy.push(toAppend.last); } return arrayCopy; } append([2, 3, 4], { first: 1, last: 5 }); // => [1, 2, 3, 4, 5] append(['Hello'], { last: 'World' }); // => ['Hello', 'World'] append([8, 16], { first: 4 }); // => [4, 8, 16]

Because the toAppend object can remove the first or last properties, you need to check their existence using the if(toAppend.first){} and if(toAppend.last){} conditions.

Except that undefined, like false, NULL, 0, NaN, and ' ', are false values, and the current implementation of the append() function does not allow false elements to be inserted:

append([10], { first: 0, last: false }); // => [10]

0 and false are false values ​​because if (toAppend.first){} and if (toAppend.last){} are actually compared to false values ​​and those elements are not inserted into the array. The function returns the original array [10] unchanged.

Availability of property

Luckily, JavaScript offers many ways to determine whether an object has a certain property:

  • obj.prop !== undefined in JavaScript allows you to check for undefined by comparing an object to it;
  • typeof obj.prop !== 'undefined' checks the type of the property value;
  • obj.hasOwnProperty('prop') checks an object to see if it has its own property;
  • 'prop' in obj checks an object to see if it has its own or an inherited property.

The best practice in this case is to use the in operator to check whether an object has a certain property without accessing the actual value of that property:

function append(array, toAppend) { const arrayCopy = array.slice(); if ('first' in toAppend) { arrayCopy.unshift(toAppend.first); } if ('last' in toAppend) { arrayCopy.push(toAppend.last); } return arrayCopy; } append([2, 3, 4], { first: 1, last: 5 }); // => [1, 2, 3, 4, 5] append([10], { first: 0, last: false }); // => [0, 10, false]

'first' in toAppend (like 'last' in toAppend) prints true, regardless of the existing property. In other cases, it displays false.

Using the in operator eliminates the problem of inserting false elements 0 and false. Now adding elements at the beginning and end of the array [10] produces the expected result: [0, 10, false].

Destructuring access to object properties

Object destructuring allows you to set a default value if the property does not exist: useful for avoiding direct contact with undefined:

const object = { }; const { prop = 'default' } = object; prop; // => 'default'

Taking advantage of object destructuring, we implement quote():

function quote(str, config) { const { char = '"', skipIfQuoted = true } = config; const length = str.length; if (skipIfQuoted && str[0] === char && str === char) { return str; } return char + str + char; } quote('Hello World', { char: '*' }); // => '*Hello World*' quote('"Welcome"', { skipIfQuoted: true }); // => '"Welcome"'

const { char = '"', skipIfQuoted = true } = config in one line retrieves the char and skipIfQuoted properties from the config object.

If some properties are not available in the config object, destructuring sets default values: '"' for char and false for skipIfQuoted. Fortunately, the feature can be improved.

Let's move the destructuring to the options section and set the default value (an empty object { }) for the config parameter to skip the second argument when the default values ​​suffice:

function quote(str, { char = '"', skipIfQuoted = true } = {}) { const length = str.length; if (skipIfQuoted && str[0] === char && str === char) { return str; } return char + str + char; } quote('Hello World', { char: '*' }); // => '*Hello World*' quote('Sunny day'); // => '"Sunny day"'

Destructuring assignment ensures that an empty object is used if the second argument is not specified at all. As a result, you avoid the occurrence of an undefined value in JavaScript.

Default property

There's a simple way to set default values ​​for object properties, and it's called Spread syntax:

const unsafeOptions = { fontSize: 18 }; const defaults = { fontSize: 16, color: 'black' }; const options = { ...defaults, ...unsafeOptions }; options.fontSize; // => 18 options.color; // => 'black'

The object initializer propagates properties from the original defaults and unsafeOptions objects. The order in which the source objects are listed is important: the properties of a later source object overwrite earlier ones. Regardless of the situation, an object always contains the full set of properties, and undefined is not possible.

Function parameters

A function that has certain parameters must be called with the same number of arguments. In this case, the parameters receive the expected values:

function multiply(a, b) { a; // => 5 b; // => 3 return a * b; } multiply(5, 3); // => 15

When multiply(5, 3) is called, the parameters a and b are given the corresponding values ​​of 5 and 3. The multiplication is calculated as expected: 5 * 3 = 15.

But what happens when an argument is skipped when called? The parameter inside the function gets the value undefined. How to avoid this?

A better approach is to use the default options from ES2015:

function multiply(a, b = 2) { a; // => 5 b; // => 2 return a * b; } multiply(5); // => 10 multiply(5, undefined); // => 10

Setting b = 2 in the function signature ensures that if b is undefined, the parameter will default to 2.

Function return value

In JavaScript, a function that does not have a return statement returns undefined:

function square(x) { const res = x * x; } square(2); // => undefined

The same thing happens if return is present, but without any expression nearby:

function square(x) { const res = x * x; return; } square(2); // => undefined

By specifying a value for return, you can get the desired result:

function square(x) { const res = x * x; return res; } square(2); // => 4

Now calling the function will output the desired value.

void operator

The void operator evaluates the expression and returns undefined regardless of the result:

void 1; // => undefined void (false); // => undefined void {name: 'John Smith'}; // => undefined void Math.min(1, 3); // => undefined

One use of the void operator is to override the result of an expression and return undefined if unexpected results from the function occur.

Reinstalling Java Components

Virus activity or software obsolescence could affect the normal operation of Java. You should download and reinstall the program. To do this, you need to visit the site https://www.java.com/ru/download/. On the page that opens, click “Download for free”, then select a folder to save. After downloading the file, you must run it and follow further instructions from the installer.

To completely eliminate the negative impact of outdated software, it is also recommended to reinstall Flash Player. Link to download the installer: https://get.adobe.com/ru/flashplayer/. It is important to uncheck the boxes on the first page to prevent the installation of additional programs.

Difference between NULL and undefined in JavaScript

The main difference is that undefined represents the value of a variable that has not yet been initialized, while NULL represents the intentional absence of an object.

Let's say the variable number is defined, but it has not been assigned an initial value:

let number; number; // => undefined

The same thing will happen when trying to access a non-existent property of an object:

const obj = { firstName: 'Dmitri' }; obj.lastName; // => undefined

Or the variable should expect a function object to be returned, but for some reason the object cannot be created. In this case, NULL is a significant indicator of the missing object. For example, clone() is a function that clones a simple JavaScript object. The function is expected to return an object:

function clone(obj) { if (typeof obj === 'object' && obj !== NULL) { return Object.assign({}, obj); } return NULL; } clone({name: 'John'}); // => {name: 'John'} clone(15); // => NULL clone(NULL); // => NULL

But clone() can be called with an empty argument: 15 or NULL. In this case, the function cannot create a clone, so it returns NULL, an indicator of a missing object.

JavaScript has tests for NULL and undefined. The typeof operator demonstrates the difference between two values:

typeof undefined; // => 'undefined' typeof NULL; // => 'object'

The strict equality operator === also distinguishes undefined from NULL:

let nothing = undefined; let missingObject = NULL; nothing === missingObject; // => false

You might also be interested in our article on error handling in JavaScript.

Clearing cache

During browser operation, temporary files are created that reduce traffic consumption when loading Internet pages. A large accumulation of such documents can negatively affect the operation of the browser and Java elements. Let's look at the process of clearing the cache using the Chrome browser as an example:

  • Press the key combination Ctrl+Shift+Del.
  • In the pop-up window, check the boxes for “Cookies” and “Other files stored in the cache.”
  • Select a time range at the top. It is better to specify the value “All time”.
  • At the bottom, click on the “Delete data” button.
  • Restart the browser and check the operation of VKontakte multimedia elements.

By following the recommendations in the article, you will be able to get rid of the “javascript error” error. First of all, you should simply restart your PC, and only then proceed with more serious actions.

What is undefined in JavaScript

undefined is a special value. According to the ECMAScript specification, undefined in JavaScript can be obtained by accessing uninitialized variables, non-existent object properties, non-existent array elements, etc. Example:

let number; number; // => undefined let movie = { name: 'Interstellar' }; movie.year; // => undefined let movies = ['Interstellar', 'Alexander']; movies[3]; // => undefined

As we can see, undefined is printed when trying to access:

  • uninitialized variable number;
  • non-existent property of the movie.year object;
  • to a non-existent array element movies[3].

The typeof operator returns the string undefined for an undefined value:

typeof undefined === 'undefined'; // => true

The typeof operator is great for checking for undefined value in JavaScript:

let nothing; typeof nothing === 'undefined'; // => true

What is this VKontakte error?

This bug can be caused by many reasons. The most common of them are outdated or broken extensions, unstable Internet connection. Less commonly, such failures are caused by viruses, Trojans and browser hijackers. It is also worth mentioning the scheduled work on the VK website, which has been carried out very often lately. Many people believe that the error is directly related to the Java package installed on Windows, but these are completely different things and updating Java will not help you.

VKontakte error “JavaScript error: str is undefined”

conclusions

Got rid of javascript error mutations are not initialized?

The problem with the error “javascript error mutations are not initialized” occurs to everyone. But it is solved in completely different ways.

It may go away on its own if it was related to technical work on the site. The notorious reboot with a full scan of the computer for viruses will also come to the rescue.

Before digging into the registry, try opening your page through another browser, incognito mode, or adding the letter m to get m.vk.com.

The mobile version of the application is somewhat simplified, so sometimes errors do not occur in it.

If all this does not work very well, install all the necessary updates, in particular, Java and Adobe Flash Player.

Also try updating your browser if a new version is available. Before this, you can still clear the cache of both the page itself and the browser as a whole.

As a last resort, go to the registry to edit the Hosts file.

If none of this helps, but the error appears only on the VKontakte website, it makes sense to contact technical support.

Rating
( 1 rating, average 4 out of 5 )
Did you like the article? Share with friends:
Для любых предложений по сайту: [email protected]