struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills:

function tank(){
    this.width = 50;
    this.length = 70;
}

function Person(job) {
    this.job = job;
    this.married = true;
}
var tank1 = tank();
console.log(tank1.length);  //returns: Uncaught TypeError: Cannot read property 'length' of undefined

var gabby = new Person("student");
console.log(gabby.married);  //returns: true

The first console.log isn't functioning properly, however the second one is. As someone relatively new to javascript, I can't figure out why the length property is showing as undefined. Any insight would be greatly appreciated!

Answer №1

Make sure to include the new keyword:

var tank1 = new Tank();

Answer №2

When you run the tank() function, it operates within the context of the window object. This means that when you add the "width" and "length" fields to the window object, you can confirm this by checking window.length and window.width after calling tank(). These values should be 70 and 50 respectively. Since the tank() function does not return anything, assigning var tank1 = tank(); results in tank1 being set to undefined, leading to the error you are experiencing.

In the next scenario, when you invoke the Person constructor using the new keyword, the function Person(job) {...} is executed with 'this' referring to the newly created Person object. The new keyword performs the following actions:

  1. Instantiates a new Person object.
  2. Invokes the constructor function "function Person(...)", with 'this' pointing to the newly created object.
  3. Returns the fresh Person object back to the caller once the function completes its execution.

To delve deeper into the concept of execution contexts, visit this resource.

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

Webstorm showcases files with similar content in a distinct manner

In Webstorm, everything is color-coded based on whether it is a function, object, etc. I am working with JavaScript. I have noticed that in two different files, the same line of code looks differently: var Comment = React.createClass({ In file 1: "var" ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Redux - a method of updating state through actions

Hello, I am currently working on developing a lottery system and I have a question regarding the best approach to modify state using action payloads. Let's consider the initial state: type initialCartState = { productsFromPreviousSession: Product[ ...

The Datatable fails to render the JSON data

Currently, I am dynamically binding a DataTable from a JSON URL and also generating headers dynamically. However, I am facing some issues in passing the JSON data to aaData in the DataTable. Can you please take a look at my code snippet below and provide m ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...

What is the best way to access the id attribute of a <td> element within a <tr> using jQuery?

Can someone assist me with this issue? Is there a way to get the ID of the first or second td element instead of using a loop? Here is an example: "<tr class='test_point' id="+fileName+"><td><img src='"+ROOT_PATH+"/assets/d ...

Tips for invoking the href function in jwplayer with individual arguments

I need assistance with configuring jwplayer to load a list of href links one by one. Each href link includes a function that needs to be triggered automatically with specific parameters passed to JavaScript. Below is the code snippet I am currently worki ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

Having trouble with ui-router: "$injector:modulerr" - it seems an error has occurred

I recently started the tutorial AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails by Thinkster, but encountered a problem. After creating an inline template, I ended up with a blank page and an error message $injector:modulerr with ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Utilize JavaScript to append a CSS class to a dynamic unordered list item anchor element

I am working with a list of ul li in a div where I need to dynamically add CSS classes based on the click event of an anchor tag. Below is the HTML structure of the ul li elements: <div class="tabs1"> <ul> <li class="active"> ...

Guide on how to reference the Html directory using the path module in Node Js

Desperately trying to send an html file as a response using express, but I'm having trouble locating the position or path of the index.html file. This is how my files are structured - MyWebsite Html index.html Css index.css ...

What is the best way to extract a specific value from a line of data using JavaScript (JSON)?

My current task involves extracting the "correctAnswers" from a specific number. Let's take a look at this JSON example: { "questions": [ { "number": 3, "question": "☀️ ➕ ...

Retrieve live data from a Python script using jQuery and PHP for immediate usage

How can I show the current temperature on a webpage? My setup involves using a Raspberry Pi 3 with the Jessie OS and Chromium as the browser. To achieve this, I have placed a Python script inside a loop for a countdown timer. The script is triggered ever ...