Is it safe to rely on the order of execution when declaring variables in JavaScript?

Could you clarify if either of these examples depend on undefined behavior, and if there is a way to modify them to avoid it:

Sample 1:

var str = {
  ver: '1.01',
  verdesc: 'WIP',
  composite: {
    version_block: str.ver + str.verdesc
  }
}

Sample 2:

var str = {
  ver: '1.01',
  verdesc: 'WIP',
},
composite: {
  version_block: str.ver + str.verdesc
};

Answer №1

When referencing a property defined within an object literal from within the same object literal, it is not possible. The properties are only assigned to the variable after the entire object literal has been evaluated. Therefore, you cannot reference properties of the variable within the object literal itself.

If you assign an object literal to a variable like this:

var data = { ... };

you will not be able to use the reference data inside the object literal. This is because at the time of evaluation, data is still undefined. It is only after the object literal has been fully parsed and evaluated that the Object value is created and assigned to data.

var data = {
    x: 456,
    y: data.x // this will throw an error as "data" is undefined
};
data.y = data.x; // this will work fine

Answer №2

http://jsfiddle.net/kendfrey/XwVFt/

The message of error provides all the details.

It is not permissible to do that. The properties of the variable cannot be accessed until after the variable has been assigned, which occurs once the entire object has been created.

To resolve this issue, you need to assign the object first and then proceed to set its properties.


var str = { };
str.ver = '1.01';
str.verdesc = 'WIP';
str.composite = {
  version_block: str.ver + str.verdesc
}

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

Automatically navigate to a specific element as the user scrolls down the page

I am attempting to achieve a similar effect as seen on the App Builder Website. When the user reaches the header with the background image/video and scrolls down, the website smoothly transitions to the next div/section. If the user scrolls back up and ret ...

Utilize JavaScript/jQuery to check for upcoming deadlines in a SharePoint 2013 list

I need to check if an item is due based on its date. When a user creates an item with a date in the format MM/DD (e.g., 06/15), I want to determine if that date falls within the next 30 days, turning it red, within the next 60 days, turning it orange, or g ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

Error in Chrome console after running Elixir webpack: Variable is undefined

I am facing an issue with a javascript file called scripts.js containing vue js code: var app2 = new Vue({ el: '#app-2', data:{ message: 'Some msg' } }) After building the js file using gulp elixir webpack, I incl ...

What are some ways to personalize column design when a Kendo grid column is automatically created?

I am populating the Kendo grid with data using JavaScript: var dataSource = new kendo.data.DataSource({ transport: { read: { url: "@Url.Action("GetProductList", "Home")", type: "POST&qu ...

Is the function failing to generate an input field?

Trying to implement a function that triggers an input field to appear upon clicking an element using the onclick event. Let's take a look at the code below. <!DOCTYPE html> <html> <body> <button onclick="createMessage()">New ...

Customize esLint by incorporating exceptions

My webpack configuration has two required variables that are causing linting errors. Is there a way to create exceptions for specific variables? I need to ignore the variables path and persistentPlugins. My current .eslintrc file is structured as shown ...

Implementing an Onclick function in HTML

I have an HTML code and I am looking to add an onclick event for a button named GET DATA. When the button is clicked, I want to send data for userId and categoryId to a PHP file. Can someone help me implement this functionality in my existing code? Here ...

What is the best way to select a random item from a DropDownList using JavaScript?

I am looking to automate the process of selecting random items from a dropdown list. Currently, it is selecting items in order from first to last, but I would like it to select items randomly. /* function to automatically select items from DropDownList1 * ...

What is the best way to structure files within the css and js folders after running the build command in Vue-cli?

Vue-cli typically generates files in the following structure: - dist -- demo.html -- style.css -- file.commom.js -- file.commom.js.map -- file.umd.js -- file.umd.js.map -- file.umd.min.js -- file.umd.min.js.map However, I prefer to organize them this way: ...

Refreshing the PHP Combo Box using AJAX Technology

Currently, I have a PHP page that displays team positions for 4 years in columns. The client now wants the ability to select players for each position as their first, second, and third choices. The current design features multiple combos with all available ...

Having trouble transforming the API response data into a usable form

I am facing an issue with rendering the API response to a form. I am using the same form for both adding and editing purposes. My goal is to display an empty form when the 'Add' button is clicked, but show specific user data when the 'Edit&a ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

Can custom directives in Vue be used to define data variables?

I am using two components: SceneList and SceneCard. In the SceneList component, I am randomly setting the background color of each SceneCard and trying to pass the color code to the SceneCard component. However, I am encountering an error message: "Error i ...

Using the map function to loop through an array of objects and accessing nested values within the objects

Within my array, there are multiple objects structured like this: { "id": 2, "nom_operation": "opSavCreationTest2", "num_serie": "1203250cd81b2101", "address_mac": "04:15:d9:00:00:49", "description": "opSavCreation ...

Having difficulties integrating a login solution due to an error saying "eslint Promise executor functions should not be async no-async-promise-executor"

I'm currently working on integrating a login solution into my Vue app using the JWT Authentication plugin. While I have a test solution that is functional, I'm facing an issue in my main branch where the eslint version seems to be causing an err ...

Invoking a Server-Side Event with Client Script/HTML Added on the Fly

I'm facing an issue with triggering server-side events from dynamically generated HTML and JavaScript on the client side. Our website is built using .NET, which has a complex page lifecycle with numerous events that can be triggered. We are looking t ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Issue with Bootstrap's form-inline element causing incorrect spacing in btn-group

I'm having an issue with Bootstrap components. When I try to input numbers, everything works fine as long as I don't use form-inline or a navbar. Check out my fiddle here: http://fiddle.jshell.net/6Lrhcezb/ https://i.sstatic.net/hzmlM.png The ...

What is the most effective way to obtain the maximum innerHeight in a browser that is not set to 100% size

Imagine the scenario where window.innerHeight = 978px with the browser not in full screen mode. However, as the browser is resized, the value of window.innerHeight will decrease accordingly. So, how can one achieve the same height = 978px when the browse ...