Is there a way to scope a variable that is assigned within an if statement's condition?
The following will of course assign el to my element and will be globally scoped (as will date).
if (el = document.querySelector('.footer__year'), el) {
var date = new Date();
el.textContent = date.getFullYear();
}
But say I wrap that in an iife.
(function() {
if (el = document.querySelector('.footer__year'), el) {
var date = new Date();
el.textContent = date.getFullYear();
}
})();
el is still accessible via window.el but date is not.
Using if (var el = document.querySelector('.footer__year')) ends up with an unexpected token error.
Is there a way to scope this?
Also, I am aware that the following would fix my issue.
(function() {
var el = document.querySelector('.footer__year');
if (el) {
var date = new Date();
el.textContent = date.getFullYear();
}
})();
But would like to know if this is even possible!
UPDATE
Overall variable scoping is not the problem here (the last example works just fine and el is not globally scoped), it is the ability to declare vs. assign a variable within the condition of an if statement.