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.
- What is undefined in JavaScript
- How to escape undefined in JavaScript
- undefined value in arrays
- Difference between NULL and undefined in JavaScript
- Conclusion
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
Host File
However, the case may be more advanced. Then try clearing the Host file on your device.
He is a potential target for virus programs. Unfortunately, antiviruses are not able to detect absolutely all viruses, because they are created every day.
So, it is viral activity that can block your access to different sections of the site, in this case, Vkontakte.
Bring the Host file into working order. To do this, go to the etc folder at the following address: C:\ Windows\ System32\ drivers\ etc. It will also contain that Host file.
You can edit it using notepad. But first right-click on it to run as administrator.
Otherwise, nothing will work; the OS will not allow you to make any changes.
More precisely, you won’t be able to save it. So don't do the same job twice.
Editing a file means adding additional information to it, such as an IP address and website address. Using VKontakte as an example, the file should contain the following:
Host File
The Host file may not be on your computer. And this is absolutely not fatal - on the contrary, if something is missing, then viruses cannot attack it.
If the Host file is hidden
True, don’t rejoice too early, check if the file is hidden. Also, the Host may simply be located in a different location. To find out where he is hiding, you will have to look into the registry.
Win+R
Hold down Win+R or type regedit in the search bar. Go to this directory: HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Services\ Tcpip\ Parameters\.
Next, find DataBasePath - the location is written opposite it. This corresponds to the location of the Host file.
However, this method is more serious. Be careful not to delete other important files in the registry.
This can affect your computer's performance much more than a Java error. True, you don’t need to be immediately afraid to even go into the registry itself.
The main thing is to find the file you need, that’s your whole task. There is no need to move, delete, etc.
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.
Course "IT Project Management"
Start February 24, 7 months, Online, From 8,000 to 88,000 RUR
tproger.ru
Events and courses 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.
It could be a cache issue
Press Control + F5
Your next step is to clear your Java cache and browser.
Perhaps they have errors that directly affect the operation of the VC.
Press Ctrl+F5 for a few seconds. The page you are on should reload.
If the problem was related to the cache, then everything should be normalized.
And the words “javascript error mutations are not initialized” will no longer scare you.
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.
Start with the basics
You can start with the most primitive thing - restart your computer.
Try restarting your computer
This is especially effective if you previously downloaded some kind of update, and for it to work correctly you need a reboot.
And this is still somehow affecting the way Java works. Of course, this doesn't help everyone.
Let's consider other methods.
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.
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.
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”
How to fix the error?
One of the options is an incorrect hosts file. This is a system file responsible for network routing. There is no need to go into details now. Let's just bring it back to its original form.
It is located in the following folder:
C:\Windows\System32\drivers\etc
We go into it and open our file using notepad.
The working version of the file should not contain extraneous lines. Lines starting with the “#” sign are system comments. There is no need to touch them. If there is anything unnecessary, we delete it.
Save and try to restart Contact. The error should disappear.
Sometimes updating java helps. Follow the link and download the latest version:
https://www.java.com/ru/download/
And the last piece of advice I wanted to give you. JavaScript-related errors can be caused by an outdated cache in your browser. Clean it up.
Let's do this in Google Chrome. Open the menu. Now the tab “Additional tools”, and there is the item “Deleting data about viewed pages”.
In the next step, indicate the time period, mark the necessary items and click the “Clear history” button.
After that we try to restart the page.
Questions?
Nowadays, almost every person has a mobile phone, and the younger generation strives to purchase new models, iPhones are especially famous among young people! Emphasize your individuality
Logo creation
A logo is much more than just text, an icon, and a color. A logo is the face of your company, reflecting its values and characteristics. Creating a logo is not easy. Need to take into account
SEO site analysis
Hi all! A new article from the series “Independent website promotion” - analysis of the website and the website of competitors. If you are looking for ways to optimize your own website, this article is for you.
Main principles of SEO
Most of the information offered for studying information on promoting resources certainly places the use of high-quality, unique content on Internet resources at the forefront. Also for promotion
Components and plugins for Joomla 1.5
In this short article we will talk about the most necessary components and plugins for joomla 1.5. Many of you know how difficult it can sometimes be to find the necessary extensions for your website built on joomla.
Drawing up a semantic core. Collection rules and errors
How to use the semantic core, rules and errors when compiling, step-by-step instructions for creating a list of search queries. We will analyze all this in detail in this article. Semantic core
Useful services for working with web analytics
It is impossible to work on optimization, increasing conversion and traffic without web analytics. Surely every web analyst has his own favorite tool or service that he uses most often.
About making money online
How to choose the right keywords? And what are they for? Selecting keywords is quite a serious step for a webmaster. The fate of the promoted resource on the Internet depends on it. Keywords
Creation of online stores
It seems that all this is too complicated and requires a lot of investment of time and money. Well, by the way, there is no “magic pill” that you click on and everything will appear right away. Above anyone
Hosting rating
Choosing a hosting is one of the primary tasks of a webmaster who wants to start making money on websites. Many people do not attach much importance to the choice of hosting, instead choosing the first one they come across or the most
Very often the social network VKontakte presents us with not very pleasant surprises. For example, complaints about the inability to listen to or view audio and video files have recently become more frequent. Let's look today at how to get rid of javascript errors on VKontakte
.
Java
It is likely that you will need to reinstall Java.
At some point you could have damaged some program files, which is why you are now suffering with the error “javascript error mutations are not initialized”.
Installing Java
It is best to download updates or the program itself through the official website (https://java.com/ru/download/) so as not to pick up viruses somewhere.
By the way, it is better to update Adobe Flash Player. It can also cause similar errors.