0

What I'm doing wrong here?

I have object like below inside function

function another(){
    
    var obj.level1 = {
            prop1 : 'some value 1',
            props2: 'somevalue 2'
            newProps : func() --> want new property with 1/ 2
        }
    }



function func() { // using this func for specific scenarios
        var setNewValue = '';
        if(myConditionPassed){
            setNewValue = 1; // i need this to be added in my above obj
        } else {
            setNewValue = 2;// or this to be added in my above obj
        }
    }

but when doing console.log(obj.level1); getting undefined

Expected:

obj{
   level1: {
            prop1 : 'some value 1',
            props2: 'somevalue 2'
            newProps : 1
        }
}

Thought of not posting this thread, though its very dead simple, even using JS daily, I don't understand where I'm missing and what I did wrong.

0

1 Answer 1

1

You can only create an object (not a property) with var, let and const

This statement is not executing successfully:

var obj.level1 = {
    prop1 : 'some value 1',
    props2: 'somevalue 2'
}

I suspect you are not noticing the error it produces. On my Chrome for Windows, I see this in the console: Uncaught SyntaxError: Unexpected token '.'.

As a result of that error, you are getting the error when you try to read obj.level1.

Two solutions

Option 1. Create obj first, and then set its level1 property.

var obj = {};
obj.level1 = {
  prop1 : 'some value 1',
  props2: 'somevalue 2'
}

Option 2. Create obj and level1 together.

var obj = {
  level1: {
    prop1 : 'some value 1',
    props2: 'somevalue 2'
  }
};

On an unrelated note, your newProps function is malformed

You have forgotten to return the allowHim. This is a common mistake, don't worry! You have calculated the value in func() but not returned it, so the new property is being correctly reported as undefined! Here is what you need.

function func() { // using this func for specific scenarios
    var allowHim = '';
    if(myConditionPassed){
        allowHim = true; // i need this to be added in my above obj
    } else {
        allowHim = false;// or this to be added in my above obj
    }
    return allowHim
}

On a supplementary note, I suggest you create the allowHim variable like this:

let allowHim = null;

This is preferable on two grounds. First, you are getting into the habit of using let wherever possible, which makes variables as local as possible, which in turn reduces bugs.

Second, you are setting the initial value to null, rather than ''. It won't affect how the code works but it is helpful because '' is a sensible default value for a string, and not for a boolean. When you are debugging a more complex program, and you see a variable containing '', you might wrongly suspect it is later supposed to contain a string value. If instead you see it containing null, you won't get that wrong hint.

Here is how to display the problem, and how to fix it

Your current version of the question has the following code exactly:

var obj.level1 = {
    prop1 : 'some value 1',
    props2: 'somevalue 2'
    newProps : func() --> want new property with true/ false
}

function func() { // using this func for specific scenarios
    var allowHim = '';
    if(myConditionPassed){
        allowHim = true; // i need this to be added in my above obj
    } else {
        allowHim = false;// or this to be added in my above obj
    }
}

There are 4 faults in the code.

Fault 1. It uses var in var obj.level1.

Get rid of the var. Presumably you created obj earlier in your program? So I am just pre-setting obj to {}. You won't need to do that if your program already sets it to something before.

Fault 2. The following line is missing a terminal comma.

props2: 'somevalue 2'

Fault 3. The following line has a comment which you have not marked as a comment.

newProps : func() --> want new property with true/ false

Fault 4. The definition of func does not include a return statement.

The return statement you mention in the comments below, is not correctly formed.

Here is a revised version that works.

var obj = {} 

obj.level1 = {  // DO NOT put a "var" on this line.
    prop1 : 'some value 1',
    props2: 'somevalue 2', // I have inserted the missing comma
    newProps : func() // If you want to comment, you need the "//" symbols
}

function func() { 
    var allowHim = null;
    if(1 + 1 === 2){
        allowHim = true; 
    } else {
        allowHim = false;
    }
    return allowHim; // Your original version was missing this.
}

console.log(obj.level1)

Faults 1, 2 and 3 would have been picked up by you instantly if you had used the snippet tool ("< >" icon) to insert your code

When you manually enter code there are multiple problems. First, you leave in syntax errors which answerers have to guess the resolution to. Second, you rely on your own correct conveying of the error message.

In your case you conveyed the error message incorrectly. Your question said the following:

but when doing console.log(obj.level1); getting undefined

And accordingly I explained what would cause that to happen.

However, after spending some time trying to help, I now realise that your error message was not that, but that the property newProp was undefined, i.e.

console.log(obj.level1) is getting undefined.

This confusion would have been prevented if you had given us a snippet, because we can immediately see what the error is, rather than relying on a questioner's potentially inaccurate description of the error.

Sign up to request clarification or add additional context in comments.

9 Comments

still i dont see syntax error but obj.level1{ prop1 : 'some value 1', props2: 'somevalue 2', newProps: undefined } only
Hmmm... Your comment makes me think that what you are running is not the code you showed you showed in the question. In the question, you have commented out the newProps. Yet your message shows a newProps. Can you try EXACTLY the code you used in the question? And report the EXACT output of console.log(obj.level1).
Hey sorry, actually i tried to highlight what i need .. i've edited my question now. pls check..
OK, read my updated answer from 2 min ago. (Incidentally, again your updated question is not exactly what you used. You have forgotten to put the comment symbols ("//") into the call to func(). These mistakes are easy to make if you are simply typing code without an ability to test. In future, you might like to use the "<>" icon which lets you both edit and test code, and helps answers reproduce your EXACT problem. If the solution works, please mark as correct. 8-)
and side note is. unfortunately am not using es6 so not giving try to use let or const. otherwise i would have used ... spread operator to get things done :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.