What is best practice for typing variables in QML?

• Aug 28, 2023 - 14:45

This code:
"for (var j in chords){
var z = j+1"
gives z = 01
so that console.log ("chords[z].ticks = ", chords[z].ticks) gives a type error!!!
Very confusing!!
var z = ++j
var z = 0;
z = j+1

Any suggestions?
EDIT: ++j is no good: will advance j twice in the loop
EDIT2: now
var z = 0;
z = j+1
also gives z = 01
z = ++j
followed by j-- is OK


maybe coz the javascript inside qml is said to be loosely typed

I keep it that way most of the time so that I can code quick and dirty, I saw coders use prefix
var boolTest = true
var uText = 'foobar'

var z = j+1
gives 01, it means j is string, not number
just do this instead:
var z = (+j)+1
and that will work as you want

In reply to by Jojo-Schmitz

@Jojo this is not for you as I know you know, but I disagree with "converts" is the same as "makes clear it is"
"Makes clear it is" a number implies it was already one and the interpreter wasn't able to detect it.
This is not true, j is not a number but a string and and a real action (convert) is necessary to get a number.
It doesn't convert j itself by the way, j stays a string, only the expression value +j is a number.
Converting j itself would require to replace its value e.g. by
j = +j;

In reply to by frfancha

FYI: in the above example

"for (var j in chords){
var z = j+1”

replacing z = j+1 with z = j gives no type error. So j is not a string per se.

The default value of a variable in JavaScript is null or undefined.

To make z a string after j+1 is an outright error in my eyes.
EDIT: and it probably occurs because you are allowed to concatenate strings with +
EDIT2: And Stack Overflow agrees with me:
“Why is + so bad for concatenation?”

“Javascript is a dynamically typed language, meaning that variable types are not declared, but rather are inferred by the interpreter at runtime.”

In reply to by elsewhere

If you need information about JavaScript online, avoid stackoverflow (at least as starting point), use mozilla developer network instead, their content is of super high quality.
If you google something you can just add MDN to your search to guide google (or site:... But usually just MDN is enough).
If books are your thing, read 2 of them : the first 10 chapters of "JavaScript the definitive guide" and "JavaScript the good parts".

In reply to by frfancha

It'd be beneficial for readers to also know that @elsewhere pointed out a "known" confusing / bug-ish behavior of the musescore 3 plugin coding system. The "for ... in" sometimes returns index number as string unexpectedly, like your mother-in-law paying you surprise visits, forcing you search best practice online. Could be a "Quit My Life" situation, aka QML: might be originated from qml javascript engine's implementation of list / dictionary.

Do you still have an unanswered question? Please log in first to post your question.