Obsidian templater creating a new note when renaming

I 2ant to automatically name any “Untitled” Obsidian files that I create based on a pre-defined template

I have tried multiple different configurations of this template:

<%*
// define list of characters and the length of the list
const charList = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
const listLen = charList.length;
// create the random string variable
let randStr = “”;

// Generate a 3-character string
for (let i = 0; i < 3; i++) {
// Get a random index from the characters string
const randInd = Math.floor(Math.random() * listLen);
// append random letter to string
randStr += charList[randInd];
}
%><%*
let title = tp.file.title;
if (title.startsWith(“Untitled”)) {
tp.file.rename(tp.date.now(“X”) + (“-”) + (randStr))
}
else {
}
-%>

id: <% tp.date.now(“X”) + (“-”) + (randStr) %>
tags:


The issue is that A duplicate note is created when the file is renamed. This does not happen if the file rename statement is outside of an if statement.

The Template:

<%*
// define list of characters and the length of the list
const charList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
const listLen = charList.length;
// create the random string variable
let randStr = "";

// Generate a 3-character string
for (let i = 0; i < 3; i++) {
// Get a random index from the characters string
    const randInd = Math.floor(Math.random() * listLen);
// append random letter to string
    randStr += charList[randInd];
	}
%><%*
let title = tp.file.title;
if (title.startsWith("Untitled")) {
	tp.file.rename(tp.date.now("X") + ("-") + (randStr)) 
}
else {
}
-%>
---
id: <% tp.date.now("X") + ("-") + (randStr) %>
tags:
- 
---