Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
var-used-in-block-scope.qdoc
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5\ingroup qmllint-warnings-and-errors
6
7\title Block scope var declaration
8\brief [var-used-in-block-scope] A variable has been declared with var inside a block scope.
9
10\qmllintwarningcategory block-scope-var-declaration
11
12\section1 A variable has been declared with var inside a block scope
13
14\section2 What happened?
15A JavaScript variable has been declared with var inside of a block scope, for
16example in the body of a while loop.
17While it might look like the variable is only usable inside that scope, it
18can actually be accessed outside of it, as it is hoisted to the scope of the
19innermost function or QML binding.
20
21\section2 Why is this bad?
22It can be confusing to track the scope of such a variable, and they might
23accidentally shadow other variables.
24
25\section2 Example
26\qml
27import QtQuick
28
29Item {
30 id: root
31 property int count: 0
32 function countItems() {
33 let sum = 0
34 {
35 var count = root.children.length
36 sum += count
37 }
38 // ... more additions to sum
39 count = sum // modifies the function local variable, not root.count
40 }
41}
42\endqml
43To fix this warning, use let or const instead, or declare the variable directly in the function scope.
44\qml
45import QtQuick
46
47Item {
48 id: root
49 property int count: 0
50 function countItems() {
51 let sum = 0
52 {
53 let count = root.children.length
54 sum += count
55 }
56 // ... more additions to sum
57 count = sum // modifies the function local variable, not root.count
58 }
59}
60\endqml
61*/