Using variables and constants wherever possible and appropriate is good coding practice. It is also good coding practice to declare your variables and constants.
In this tutorial:
Required knowledge:
1. Some code
This tutorial starts with the code we wrote in the “Hello World!” in JavaScript tutorial:
<html> <head> <title>Hello World! JavaScript</title> </head> <body> <h1>Hello World! JavaScript</h1> <script> alert("Hello World!"); </script> </body> </html>
There is nothing wrong with this code; it works.
2. undeclared
The next step would be to assign a value to a variable and then use the variable, like so:
<html> <head> <title>Hello World! JavaScript</title> </head> <body> <h1>Hello World! JavaScript</h1> <script> myGreeting = 'Hello World!'; alert(myGreeting); </script> </body> </html>
3. var
You will see var used in a lot of code. It should only be used in code for much older browsers.
It is good practice to declare your variable type. Here we declare the variable and assign a string to it in one go:
<html> <head> <title>Hello World! JavaScript</title> </head> <body> <h1>Hello World! JavaScript</h1> <script> var myGreeting = 'Hello World!'; alert(myGreeting); </script> </body> </html>
4. let
It is preferable to use let in place of var:
<html> <head> <title>Hello World! JavaScript</title> </head> <body> <h1>Hello World! JavaScript</h1> <script> let myGreeting = 'Hello World!'; alert(myGreeting); </script> </body> </html>
5. constant
In this example, the greeting is always the same. It does not change — and we don’t want it to change — during the running of the program. Here we use a constant:
<html> <head> <title>Hello World! JavaScript</title> </head> <body> <h1>Hello World! JavaScript</h1> <script> const myGreeting = 'Hello World!'; alert(myGreeting); </script> </body> </html>
6. When to use which?
I cannot state this better than the gurus at W3Schools.com :
When to use var
, let
, or const
?
- Always declare variables
- Always use
const
if the value should not be changed - Always use
const
if the type should not be changed (Arrays and Objects) - Only use let if you can’t use
const
- Only use
var
if you MUST support old browsers. [1]
The var
and let
keywords are not exactly the same. They specifically differ in terms of scope. [2]
References:
- W3Schools Online Web Tutorials, W3Schools.com (no date) JavaScript Variables. Available at: https://www.w3schools.com/js/js_variables.asp (Accessed: 17 October 2024).
- , W3Schools Online Web Tutorials, W3Schools.com (no date) JavaScript Let. Available at: https://www.w3schools.com/js/js_let.asp (Accessed: 17 October 2024).