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\page qmllint-warnings-and-errors-block-scope-var-declaration.html
6\ingroup qmllint-warnings-and-errors
7
8\title Block scope var declaration
9\brief [var-used-in-block-scope] A variable has been declared with var inside a block scope
10
11\qmllintwarningcategory block-scope-var-declaration
12
13\section1 A variable has been declared with var inside a block scope
14
15\section2 What happened?
16A JavaScript variable has been declared with var inside of a block scope, for
17example in the body of a while loop.
18While it might look like the variable is only usable inside that scope, it
19can actually be accessed outside of it, as it is hoisted to the scope of the
20innermost function or QML binding.
21
22\section2 Why is this bad?
23It can be confusing to track the scope of such a variable, and they might
24accidentally shadow other variables.
25
26\section2 Example
27\qml
28import QtQuick
29
30Item {
31 id: root
32 property int count: 0
33 function countItems() {
34 let sum = 0
35 {
36 var count = root.children.length
37 sum += count
38 }
39 // ... more additions to sum
40 count = sum // modifies the function local variable, not root.count
41 }
42}
43\endqml
44To fix this warning, use let or const instead, or declare the variable directly in the function scope.
45\qml
46import QtQuick
47
48Item {
49 id: root
50 property int count: 0
51 function countItems() {
52 let sum = 0
53 {
54 let count = root.children.length
55 sum += count
56 }
57 // ... more additions to sum
58 count = sum // modifies the function local variable, not root.count
59 }
60}
61\endqml
62*/