0

I have this snippet below (with this valid case, where x.size exists):

let x = {
  "size": 123
}

let y = {
  'size': null
}

try {
  y.size = parseFloat(x.size) ? `${parseFloat(x.size)}` : `${x.size}`;
} catch (e) {
  console.log("yes")
  y.size = null;
}

console.log(y)

But I was expecting in case the property x.size is missing to enter on catch, and set y.size to null, but I get:

{ size: undefined }

let x = {
}

let y = {
  'size': null
}

try {
  y.size = parseFloat(x.size) ? `${parseFloat(x.size)}` : `${x.size}`;
} catch (e) {
  console.log("yes")
  y.size = null;
}

console.log(y)

What am I doing wrong? Thank you for your time!

1
  • 3
    x exists and is an object, so there's no problem accessing its properties. x.size is indeed undefined and there's nothing wrong with accessing or writing to it. If you want to test for its presence, use 'size' in x Commented Jun 9, 2020 at 15:13

3 Answers 3

1

the catch block will only execute if an error is thrown in the try block.

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

2 Comments

So in which case my code will throw an error inside try? I tried by removing the size property or by setting it to Nan, undefined, null.. and nothing is working
in your current implementation, it will not throw an error. you could explicitly throw one yourself, but this is probably not best practice. you could just have the "else" part of your ternary operator set y.size to null instead of x.size, which is undefined. then you could remove the try/catch and just have the ternary operator on its own take care of setting y.size
1

Well parseFloat(undefined) gives NaN, so you'll go to the "else" part of the ? :. That will interpolate that undefined value into a string, so you get the string undefined.

Accessing an undefined property of an object does not throw an exception.

Comments

1

According to your code. Output is correct. Explanation:

try {
    y.size = parseFloat(x.size) ? `${parseFloat(x.size)}` : `${x.size}`;
} catch (e) {
    console.log("yes")
    y.size = null;
}

// when x.size => undefined => which is converted to string using `tempate literal` to  "undefined" 

// Output
{
  "size": "undefined"
}

Right Solution: If you want null value of undefined value:

let y = {
    'size': null
}

try {
    y.size = parseFloat(x.size) ? `${parseFloat(x.size)}` : x.size ? x.size : null;
} catch (e) {
 // This will be required if any error occurs so catch block will add property to y object
    console.log("yes")
    y.size = null;
}

console.log(y)

Output:
// Output
{
  "size":  null
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.