0 and 1 are two relatively new concepts for variable declarations in JavaScript. , 0 is similar to 3 in some respects, but allows users to avoid some of the common “gotchas” that users run into in JavaScript. 1 is an augmentation of 0 in that it prevents re-assignment to a variable. With TypeScript being an extension of JavaScript, the language naturally supports 0 and 1. Here we’ll elaborate more on these new declarations and why they’re preferable to 3. If you’ve used JavaScript offhandedly, the next section might be a good way to refresh your memory. If you’re intimately familiar with all the quirks of 3 declarations in JavaScript, you might find it easier to skip ahead. tsfunction sumMatrix(matrix: number[][]) { var sum = 0; for (var i = 0; i < matrix.length; i++) { var currentRow = matrix[i]; for (var i = 0; i < currentRow.length; i++) { sum += currentRow[i]; } } return sum;}3 declarationsDeclaring a variable in JavaScript has always traditionally been done with the 3 keyword.
As you might’ve figured out, we just declared a variable named 2 with the value 3. We can also declare a variable inside of a function:
and we can also access those same variables within other functions:
In this above example, 4 captured the variable 2 declared in 6. At any point that 4 gets called, the value of 2 will be tied to the value of 2 in 6. Even if 4 is called once 6 is done running, it will be able to access and modify 2.
Scoping rules3 declarations have some odd scoping rules for those used to other languages. Take the following example:
Some readers might do a double-take at this example. The variable 5 was declared within the 6 block, and yet we were able to access it from outside that block. That’s because 3 declarations are accessible anywhere within their containing function, module, namespace, or global scope - all which we’ll go over later on - regardless of the containing block. Some people call this 3-scoping or function-scoping. Parameters are also function scoped. These scoping rules can cause several types of mistakes. One problem they exacerbate is the fact that it is not an error to declare the same variable multiple times:
Maybe it was easy to spot out for some experienced JavaScript developers, but the inner 9-loop will accidentally overwrite the variable 0 because 0 refers to the same function-scoped variable. As experienced developers know by now, similar sorts of bugs slip through code reviews and can be an endless source of frustration. Variable capturing quirksTake a quick second to guess what the output of the following snippet is:
For those unfamiliar, 2 will try to execute a function after a certain number of milliseconds (though waiting for anything else to stop running). Ready? Take a look:
Many JavaScript developers are intimately familiar with this behavior, but if you’re surprised, you’re certainly not alone. Most people expect the output to be
Remember what we mentioned earlier about variable capturing? Every function expression we pass to 2 actually refers to the same 0 from the same scope. Let’s take a minute to consider what that means. 2 will run a function after some number of milliseconds, but only after the 9 loop has stopped executing; By the time the 9 loop has stopped executing, the value of 0 is 3. So each time the given function gets called, it will print out 3! A common work around is to use an IIFE - an Immediately Invoked Function Expression - to capture 0 at each iteration:
This odd-looking pattern is actually pretty common. The 0 in the parameter list actually shadows the 0 declared in the 9 loop, but since we named them the same, we didn’t have to modify the loop body too much. tsfunction sumMatrix(matrix: number[][]) { var sum = 0; for (var i = 0; i < matrix.length; i++) { var currentRow = matrix[i]; for (var i = 0; i < currentRow.length; i++) { sum += currentRow[i]; } } return sum;}0 declarationsBy now you’ve figured out that 3 has some problems, which is precisely why 0 statements were introduced. Apart from the keyword used, 0 statements are written the same way 3 statements are. 0 The key difference is not in the syntax, but in the semantics, which we’ll now dive into. Block-scopingWhen a variable is declared using 0, it uses what some call lexical-scoping or block-scoping. Unlike variables declared with 3 whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or 9-loop. 1 Here, we have two local variables 2 and 04. 2’s scope is limited to the body of 6 while 04’s scope is limited to the containing 6 statement’s block. Variables declared in a 09 clause also have similar scoping rules. 2 Another property of block-scoped variables is that they can’t be read or written to before they’re actually declared. While these variables are “present” throughout their scope, all points up until their declaration are part of their temporal dead zone. This is just a sophisticated way of saying you can’t access them before the 0 statement, and luckily TypeScript will let you know that. 3 Something to note is that you can still capture a block-scoped variable before it’s declared. The only catch is that it’s illegal to call that function before the declaration. If targeting ES2015, a modern runtime will throw an error; however, right now TypeScript is permissive and won’t report this as an error. 4 For more information on temporal dead zones, see relevant content on the . Re-declarations and ShadowingWith 3 declarations, we mentioned that it didn’t matter how many times you declared your variables; you just got one. 5 In the above example, all declarations of 5 actually refer to the same 5, and this is perfectly valid. This often ends up being a source of bugs. Thankfully, 0 declarations are not as forgiving. 6 The variables don’t necessarily need to both be block-scoped for TypeScript to tell us that there’s a problem. 7 That’s not to say that a block-scoped variable can never be declared with a function-scoped variable. The block-scoped variable just needs to be declared within a distinctly different block. 8 The act of introducing a new name in a more nested scope is called shadowing. It is a bit of a double-edged sword in that it can introduce certain bugs on its own in the event of accidental shadowing, while also preventing certain bugs. For instance, imagine we had written our earlier 15 function using 0 variables. 9 This version of the loop will actually perform the summation correctly because the inner loop’s 0 shadows 0 from the outer loop. Shadowing should usually be avoided in the interest of writing clearer code. While there are some scenarios where it may be fitting to take advantage of it, you should use your best judgement. Block-scoped variable capturingWhen we first touched on the idea of variable capturing with 3 declaration, we briefly went into how variables act once captured. To give a better intuition of this, each time a scope is run, it creates an “environment” of variables. That environment and its captured variables can exist even after everything within its scope has finished executing. 0 Because we’ve captured 20 from within its environment, we’re still able to access it despite the fact that the 6 block finished executing. Recall that with our earlier 2 example, we ended up needing to use an IIFE to capture the state of a variable for every iteration of the 9 loop. In effect, what we were doing was creating a new variable environment for our captured variables. That was a bit of a pain, but luckily, you’ll never have to do that again in TypeScript. 0 declarations have drastically different behavior when declared as part of a loop. Rather than just introducing a new environment to the loop itself, these declarations sort of create a new scope per iteration. Since this is what we were doing anyway with our IIFE, we can change our old 2 example to just use a 0 declaration. 1 and as expected, this will print out
tsfunction sumMatrix(matrix: number[][]) { var sum = 0; for (var i = 0; i < matrix.length; i++) { var currentRow = matrix[i]; for (var i = 0; i < currentRow.length; i++) { sum += currentRow[i]; } } return sum;}1 declarations1 declarations are another way of declaring variables. 3 They are like 0 declarations but, as their name implies, their value cannot be changed once they are bound. In other words, they have the same scoping rules as 0, but you can’t re-assign to them. This should not be confused with the idea that the values they refer to are immutable. 4 Unless you take specific measures to avoid it, the internal state of a 1 variable is still modifiable. Fortunately, TypeScript allows you to specify that members of an object are 32. The chapter on Interfaces has the details. tsfunction sumMatrix(matrix: number[][]) { var sum = 0; for (var i = 0; i < matrix.length; i++) { var currentRow = matrix[i]; for (var i = 0; i < currentRow.length; i++) { sum += currentRow[i]; } } (adsbygoogle = window.adsbygoogle || []).push({}); return sum;}0 vs. tsfunction sumMatrix(matrix: number[][]) { var sum = 0; for (var i = 0; i < matrix.length; i++) { var currentRow = matrix[i]; for (var i = 0; i < currentRow.length; i++) { sum += currentRow[i]; } } return sum;}1Given that we have two types of declarations with similar scoping semantics, it’s natural to find ourselves asking which one to use. Like most broad questions, the answer is: it depends. Applying the principle of least privilege, all declarations other than those you plan to modify should use 1. The rationale is that if a variable didn’t need to get written to, others working on the same codebase shouldn’t automatically be able to write to the object, and will need to consider whether they really need to reassign to the variable. Using 1 also makes code more predictable when reasoning about flow of data. Use your best judgement, and if applicable, consult the matter with the rest of your team. The majority of this handbook uses 0 declarations. DestructuringAnother ECMAScript 2015 feature that TypeScript has is destructuring. For a complete reference, see the article on the Mozilla Developer Network. In this section, we’ll give a short overview. Array destructuringThe simplest form of destructuring is array destructuring assignment: 5 This creates two new variables named 38 and 39. This is equivalent to using indexing, but is much more convenient: 6 Destructuring works with already-declared variables as well: 7 And with parameters to a function: 8 You can create a variable for the remaining items in a list using the syntax 40: 9 Of course, since this is JavaScript, you can just ignore trailing elements you don’t care about: 0 Or other elements: 1 Tuple destructuringTuples may be destructured like arrays; the destructuring variables get the types of the corresponding tuple elements: 2 It’s an error to destructure a tuple beyond the range of its elements: 3 As with arrays, you can destructure the rest of the tuple with 40, to get a shorter tuple: 4 Or ignore trailing elements, or other elements: 5 Object destructuringYou can also destructure objects: 6 This creates new variables 2 and 04 from 44 and 45. Notice that you can skip 46 if you don’t need it. Like array destructuring, you can have assignment without declaration: 7 Notice that we had to surround this statement with parentheses. JavaScript normally parses a 47 as the start of block. You can create a variable for the remaining items in an object using the syntax 40: 8 Property renamingYou can also give different names to properties: 9 Here the syntax starts to get confusing. You can read 49 as ” 2 as 51”. The direction is left-to-right, as if you had written: 0 Confusingly, the colon here does not indicate the type. The type, if you specify it, still needs to be written after the entire destructuring: 1 Default valuesDefault values let you specify a default value in case a property is undefined: 2 In this example the 52 indicates that 04 is optional, so it may be 54. 55 now has a variable for 56 as well as the properties 2 and 04, even if 04 is undefined. Function declarationsDestructuring also works in function declarations. For simple cases this is straightforward: 3 But specifying defaults is more common for parameters, and getting defaults right with destructuring can be tricky. First of all, you need to remember to put the pattern before the default value. 4
Then, you need to remember to give a default for optional properties on the destructured property instead of the main initializer. Remember that 60 was defined with 04 optional: 5 Use destructuring with care. As the previous example demonstrates, anything but the simplest destructuring expression is confusing. This is especially true with deeply nested destructuring, which gets really hard to understand even without piling on renaming, default values, and type annotations. Try to keep destructuring expressions small and simple. You can always write the assignments that destructuring would generate yourself. SpreadThe spread operator is the opposite of destructuring. It allows you to spread an array into another array, or an object into another object. For example: 6 This gives bothPlus the value 62. Spreading creates a shallow copy of 38 and 39. They are not changed by the spread. You can also spread objects: 7 Now 65 is 66. Object spreading is more complex than array spreading. Like array spreading, it proceeds from left-to-right, but the result is still an object. This means that properties that come later in the spread object overwrite properties that come earlier. So if we modify the previous example to spread at the end: 8 Then the 67 property in 68 overwrites 69, which is not what we want in this case. Object spread also has a couple of other surprising limits. First, it only includes an objects’ own, enumerable properties. Basically, that means you lose methods when you spread instances of an object: 9 Second, the TypeScript compiler doesn’t allow spreads of type parameters from generic functions. That feature is expected in future versions of the language. Can you put a variable inside a function?Variables defined inside functions are called local variables. Their value can only be used within the function where they are declared. You can change the scope of a local variable using the global keyword – which we'll discuss in the next section.
Can you create a variable inside the function in JavaScript?JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function.
How do you add a variable to a function?we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.
|