-3

I'm trying to convert a PHP snippet in javascript:

function year_shortcode() {
    $fromYear = 2010;
    $thisYear = (int)date('Y');
    return $fromYear . (($fromYear != $thisYear) ? '-' . $thisYear : '');
} add_shortcode('year', 'year_shortcode');

What I've done so far is:

var fromYear='2010';
var thisYear= new Date().getFullYear();

if (fromYear=thisYear) {
    document.write(fromYear);
}
else {
    document.write(fromYear + '-' + thisYear);
}

I'd like to avoid the if and else statements and shorten it as I would in PHP.

JackLinkers
  • 105
  • 1
  • 1
  • 11
  • 1
    Yes, kindof the same way. Yet the classic way often seems more maintainable and readable, especially when used on chained/multiple actions. – Lain Dec 11 '20 at 13:52
  • 1
    `document.write` is [not recommended](https://stackoverflow.com/q/802854/4642212) for DOM manipulations, as it is obsolete, slow and not suitable for any evolving application. `if (fromYear=thisYear)` is a typo. – Sebastian Simon Dec 11 '20 at 13:52
  • 1
    You can use the ternary operator in the same way as in php. Also you have to use `==` or better `===` to compare equality, not `=`. – Paflow Dec 11 '20 at 13:53
  • 2
    @Paflow yes JavaScript has the ternary `? :` operator, but **no** it is not the same as in PHP: the precedence rules are different (basically the opposite of PHP) – Pointy Dec 11 '20 at 13:54
  • @Pointy Oh thank you I never realized that! – Paflow Dec 11 '20 at 14:04

2 Answers2

0

You could do this

And one thing to notice, = is assignment operator, if you want to check equality between two value, use === instead

document.write(fromYear === thisYear ? fromYear : fromYear + '-' + thisYear)
hgb123
  • 9,840
  • 3
  • 11
  • 31
0

I was trying to use ternary operators as in PHP, thanks to @Pointy and @user4642212 and answer from @hgb123 I was able to solve my question with:

document.write((fromYear != thisYear) ? fromYear + " - " + thisYear : thisYear);
JackLinkers
  • 105
  • 1
  • 1
  • 11