0

I have a simple ES6 class that looks like:

class NewsItem {
    constructor(title, date, content, photoURL) {
        this.title = title | '';
        this.date = date | '01-01-00';
        this.content = content | '';
        this.photoURL = photoURL | '../images/image.png';
    }
}

I'm having trouble creating instances of the class. Trying something simple like:

new NewsItem("fgfdds", "gfdgfd", "fdsfds", "fdsfds");

results in a NewsItem object, however instead of the passed strings, all of the class' attributes are set to 0.

Issue

I'm pretty sure I'm just using JavaScript wrong, but can't figure it out. What's going on here?

2
  • 5
    You're looking for ||, not |. Commented Jun 16, 2017 at 21:42
  • @AndrewLi that's it. However, I'm not completely sure of the difference. Commented Jun 16, 2017 at 21:47

2 Answers 2

1

The problem is that you're using | instead of ||. The one you're using, bitwise OR, converts the left and right operands to numbers, then applies the operation to those values.

The distinguishing factor is this: bitwise operations perform operations on the bits, thus the operands are converted to numbers and the operations are performed on the bits. Logical operations perform operations logically, not on the bits themselves, but the data.

Thus:

'fgfdds' | ''

Is actually using ToInt32 internally to convert 'fgfdds' and '' to a number. Both come up to be NaN, and the method ToInt32 returns +0 if the result is NaN. Thus, you're doing this:

0 | 0

Which is 0 because both operands are 0. Using logical OR, or ||, does not convert the operands to numbers and logically evaluates the operands. If one operand or the other is defined or not falsey, then it evaluates to that operand. Thus, try this:

this.title = title || '';

This will evaluate to this.title if this.title is defined or truthy, and an empty string otherwise. See logical operators and bitwise operators at MDN.


Also, if you're using ECMAScript 2015, try using default parameters instead which is a much nicer way to do this:

constructor(title = '', date = '01-01-00', content = '', photoURL = '../images/image.png') {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

0
this.title = title || '';

Assign it like this. Go here to see the explanation on Logical OR and bitwise OR

Comments

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.