Tenzolinho
Tenzolinho

Reputation: 982

set object properties in javascript

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!

Upvotes: 0

Views: 56

Answers (3)

khizerrehandev
khizerrehandev

Reputation: 1525

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
}

Upvotes: 1

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

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

Upvotes: 1

Pointy
Pointy

Reputation: 413692

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.

Upvotes: 1

Related Questions