Is there a distinction between including empty arrays within the method and passing them as object parameters in writing?

When it comes to writing empty arrays in JavaScript, is there a difference between declaring them inside the method like this:

var example = {
    calcMethod: function() {
        this.array1 = [];
        this.array2 = [];
    }
};

and declaring them as object parameters like this?

var example = {
    array1 : [],
    array2 : []
};

Both approaches will allow you to eventually fill these arrays with data.

Answer №1

Despite the irregular JavaScript syntax, I will provide an answer to your question.

The main distinction lies in the fact that calcMethod needs to be invoked before array1 and array2 are defined in the initial code snippet. Otherwise, they will remain as undefined:

let object1 = {

calcMethod: function() {
        this.array1 = [1];
        this.array2 = [2];
    }
}

let object2 = {
    array1: [3],
    array2: [4]
}


console.log(object1.array1);// undefined
console.log(object1.array2);// undefined

object1.calcMethod();

console.log(object1.array1);// [1]
console.log(object1.array2);// [2]

console.log(object2.array1);// [3]
console.log(object2.array2);// [4]

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

the proper injection of angular-resource is not being achieved in AMD

I am struggling to get angular.resource.js to work with angular.js. It seems like Angular is loaded but angular.resource is not being recognized. index.html <!doctype html> <html> <head> <script> var require ...

Tips on finding the ID of a textbox using the cursor's position

In the container, there are several textboxes. When a button is clicked, I want to insert some text at the cursor position in one of the textboxes. I have managed to insert text into a specific textbox using its ID, but I am facing difficulty in identifyin ...

Struggling to align my image in the center while applying a hover effect using CSS

Hey there, I'm having an issue centering my image when I add instructions for it to tilt on mouseover. If I take out the 'tilt pic' div, the image centers just fine. Can anyone help me identify what I might be doing wrong? Thanks in advance! ...

Ensure that input field is validated only upon clicking the save button in Angular framework

Can anyone suggest the most efficient method to validate required fields in an input form using AngularJS? I want to display an error message only after the user clicks the save button (submit). Thank you in advance. ...

The Parcel build was unsuccessful due to an error from @parcel/resolver-default: The file '../../../../../css/main.css' could not be loaded within the './src' directory

I utilize [email protected]. Whenever I attempt to load an external css or javascript file in my index.html, Parcel consistently fails to build with the following error: Build failed. @parcel/core: Failed to resolve './css/main.css' from & ...

Working with C functions and function prototypes that involve a two-dimensional array parameter

void create_game_map (int *game_map); <--- function prototype int rows, cols; <-- global variables some main { // Prompt user for number of rows and cols int game_map[rows][cols]; // Create game map here because another function will use it ...

Vue.js: Retrieving and Using Data from the API Repeatedly

<template> <h1 class="text-lg text-gray-400 font-medium">Tracker dashboard</h1> <div class="flex flex-col mt-2 w-3/4"> <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Using Ajax to implement a content slider with lightSlider

Seeking assistance in developing a dynamic content slider utilizing the LightSlider plugin. Currently, I have a script that fetches content from a database table (outputting JSON to HTML) and displays 6 div's of content per slide. However, I aim to di ...

Transitioning away from bower in the latest 2.15.1 ember-cli update

I have been making changes to my Ember project, specifically moving away from using bower dependencies. After updating ember-cli to version 2.15.1, I transitioned the bower dependencies to package.json. Here is a list of dependencies that were moved: "fon ...

Tips for managing the retrieval of non-existent images in JavaScript with LiipImagineBundle

I need to verify the existence of a file in NodeJS. While exploring a previous post, I came across this solution: const tryRequire = (path) => { try { return require(`${path}`); } catch (err) { return null; } }; However, is this the most ...

Tips for troubleshooting an Express application launched by nodemon through a Gulpfile in WebStorm 10

I have a unique Express application that is powered by a Gulpfile configuration. gulpfile.js 'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var prefix = require('gulp-autoprefixer'); va ...

Adding data from two different arrays to a MySQL table using PHP

I am attempting to populate a table with values from two arrays. The goal is to insert the corresponding values from array1 and array2 into the table as rows. For example, the table row should look like this: value1, array1[0], array2[0] ... value1, array ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue(); I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. ...

canvasJS: unable to load the chart

This is my first time using canvajs, but unfortunately, it's not working as expected. Can someone please review my code? data.php <?php header('Content-Type: application/json'); include './traitement.php'; $data =array(); ...

Issue with Typescript: When inside a non-arrow class method, the keyword "this" is undefined

Many questions have addressed the topic of "this" in both JS and TS, but I have not been able to find a solution to my specific problem. It seems like I might be missing something fundamental, and it's difficult to search for an answer amidst the sea ...

Ways to secure and conceal JavaScript functions or files from being accessed by users

Is there a way to protect my JavaScript methods from being easily copied by users? I am looking for a solution to hide my methods in firebug as well. Any suggestions on how to achieve this? Note: I am looking for methods to hide my code from users without ...

I am encountering issues with my JavaScript files that appear to be following the correct path, however they are not functioning properly. Error messages such as SyntaxError: expected expression

I am currently working on a Yii2 application. My goal is to utilize the JavaScript and CSS files from the common folder in my backend. The paths for these files are within the common/web/js and common/web/css directories respectively. To achieve this, I ...

Retrieving a targeted element from an array

I have a MySQL query that is returning an array when I use print_r(): $data = Array ( [2] => Array ( [0] => Array ( [sale_order_value_id] => 3 [sale_order_id] => 2 [name] => Comprobante Fiscal [value] => Consumidor Final [price] => 0. ...