Setting a conditional variable in Javascript
I've been hacking around with my website recently and I'm working on making my Eleventy shortcodes better. Specifically, I want to make writing and posting easier so I want the logic on how to handle image processing to happen during the build so I don't have to include such a convoluted path directly in the image shortcode. That lead me to writing some simple logic in my .eleventy.js
file.
I'm just learning Javascript and setting a conditional variable works differently with Javascript than in PowerShell (my mother tongue). In PowerShell I'd just write something like this:
$src = './src/posts/hello-world/images/image1.jpg'
if ($src -like './src/posts/*') {
$sourcePath = $src
}
else {
$sourcePath = $this.page.fileSlug + '/images/' + $src
}
I could then use $sourcePath anywhere in my script. Cool. This is what I tried at first with Javascript:
const src = './src/posts/hello-world/images/image1.jpg';
if (src.startsWith('./src/posts/')) {
let sourcePath = src;
} else {
let sourcePath = './src/posts/' + this.page.fileSlug + '/images/' + src;
};
When I tried this in my eleventy.js
file, I was getting an error message saying that sourcePath
was undefined. In my reading, I've read that developers should default to using let to define variables in Javascript so I was a little surprised that this wasn't working for me. I understood immediately that I was having some sort of scoping problem. The problem, as I understand it from my reading is when we use let
to define a variable, it's only available inside the scope of the if / else
block. Bummer. I need this variable available later in my script. I first just replaced let
with var
and that worked but I wanted to write this the correct way. After more reading, I think I've landed on the correct way to do this with Javascript and that's using the ternary operator. Here's the code I landed on:
const src = './src/posts/hello-world/images/image1.jpg';
let sourcePath = (src.startsWith('./src/posts/')) ? src : './src/posts/' + this.page.fileSlug + '/images/' + src;
Now I can use the sourcePath
variable later in my script. Yay!
That's all for now. Thanks for reading!