Conditional logic in the constructor using Javascript may or may not include if

Check out this starting code snippet.

function person(name, age, child){
    this.name = name;
    this.age = age;
    if(this.child == undefined){
        this.child = 'default';
    }else{
        this.child = child;
    }
}
var sarah = new person('sarah',34,true);

document.write(sarah.child+' ');

I'm attempting to include an optional property in a constructor function. However, regardless of what I provide as the value for the child parameter, it always displays 'default' when outputted. I am relatively new to JS, coming from a background in PHP. I can't figure out why this isn't working. I've researched other similar issues and tried various solutions, but nothing seems to fix the problem.

Answer №1

Have you considered using child = child || 'default' in place of a traditional if-else statement?

It accomplishes the same result with less code.

Answer №2

Here is the corrected code snippet:

function person(name, age, child){
    this.name = name;
    this.age = age;
    if(child == undefined){
        this.child = 'default';
    }else{
        this.child = child;
    }
}
var sarah = new person('sarah',34,true);

document.write(sarah.child+' '); // true

The issue here is that the comparison should be made with the argument child instead of this.child.

A more concise solution would be to use a ternary operator:

this.child = child || 'default';  

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

What is the best way to retrieve nested ng-include scope/fields within a form?

I've searched high and low but haven't found a solution to my unique issue. Just like many others, I'm facing the challenge of ng-include creating a new child scope that doesn't propagate to the parent. I have a versatile template tha ...

Is it possible to render an SVG using PDFTron?

Before, I attempted to utilize an Annotation.StampAnnotation to make a personalized annotation while using an SVG as the foundation image. Unfortunately, I discovered that the StampAnnotation does not allow the user to alter or set the color. Thus, I have ...

Personalize the iOS smartbanner

We have a plan to incorporate smart banners into our app. Is there a way to personalize the smart banner so that the close button is hidden and cannot be closed by the user? I attempted to use a jQuery plugin (https://github.com/jasny/jquery.smartbanner) ...

Clickable div containing a hyperlink

I need assistance with a clickable div that contains a link. Here is the setup: HTML: <div onClick="goToCat(2);" class="author-topics-block "> <a href="http://mywebsite/page/?cat=2">The woman in steel</a> </div> CSS: .author ...

Can you guide me on how to export a named function using module.exports?

I have a script file for my discord bot that includes a specific command and a function with parsing logic that I want to reuse in my main index.js // File: ./commands/scrumPrompt.js // The function const extractDeets = function (f, scrum) { let items ...

Any suggestions on how to customize the tawk.to positioning within a Next Js script?

I've been attempting to adjust the positioning of the Tawk.to Sticky button on my Next js website using CSS, but it doesn't seem to be working. Below is the script within the Next Js script tag: <Script dangerouslySetInnerHTML={{ __html: ` ...

The functionality of jQuery UI autocomplete is limited to only one use

My current setup involves using jQuery UI for an autocomplete field. However, after making changes to my PHP file to incorporate JSON encoding, I encountered an issue where the autocomplete functionality only works during the initial page load. Subsequentl ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Plane is constantly cloaked in darkness

I'm having trouble adding a texture to my plane that repeats both horizontally and vertically. Every time I try to apply the texture, it shows up as black. I've attempted to add some lights to the scene, but the issue persists without any errors. ...

Looking to transfer a cell value to different cells within an HTML table

Currently, I am utilizing a basic HTML code to duplicate the value from the first cell to all other cells. You can take a look at how the HTML table appears here. In addition, I am attempting to automatically fill in the remaining dates once input is provi ...

The information was not displayed in the message exchange

I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code: Here's ...

Updating @Html.DisplayFor item following a successful ajax request

Attempting to update a value on my view, I seem to have the correct path, but the update only occurs when I reload the entire view. Here is the HTML: <table class="table"> <tr> <th> @Html.DisplayNameFor(model =&g ...

Creating a table in Javascript using an array of objects

I need a larger version of this data structure. [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zo ...

Configuring three instances of Express: admin, website, and application

Greetings, while I consider myself an intermediate level Javascript programmer, the questions I have may come across as amateur - please forgive me. Recently, I was reverse engineering the Ghost.org blog platform (CMS) to understand its workings. I discov ...

Angular and Node.js Integration: Compiling Files into a Single File

I have a question, is it possible to include multiple require js files in one file? If so, how can I create objects from them? Calling 'new AllPages.OnePage()' doesn't seem to work. To provide some context, I'm looking for something sim ...

Creating dynamic child components in Vue.js version 2

I am currently developing a facet search system using VueJS. The concept is fairly straightforward: Within a FilterGroup component lies the overarching filter logic. This component allows for several child components, such as AttributeXYZFilter, to provid ...

What are the applications of client-side libraries within node.js?

Recently, I started exploring node.js and came across npm, which has proven to be quite useful. One thing that caught my attention is the fact that many libraries I have previously used in client-side JavaScript development, such as jquery and d3, can be ...

What sets React.Component apart from Component?

There are two different methods for accessing Component: import React from 'react'; class Foo extends React.Component { ... } versus import React, { Component } from 'react'; class Foo extends Component { ... } Is there an ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

Ordering Arrays based on a particular attribute

My array includes user points as follows: let groupRank = []; userA = ["Sara", "24"]; userB = ["John", "12"]; userC = ["Eddi", "20"]; userD = ["Marry", "13"]; I am looking to rank them according to their points and achieve the following result: Console ...