In the previous article "How to return array elements greater than the specified number through js", I introduced how to return array elements greater than the specified number through js. Interested friends can learn about it. ~
Then the theme of this article is to teach you how to declare variables in different ways in JavaScript!
First of all, everyone should also know that in JavaScript, variables can be declared in different ways by using different keywords. After all, each keyword has some specific functions in JavaScript; basically we can use Variables are declared in three different ways using the var, let and const keywords, and each keyword is used under certain conditions.
Note: Before 2015, we used the var keyword to declare JavaScript variables; ES2015 (ES6) added two important JavaScript keywords let and const.
The first wayvar
:
var:This keyword is used to declare variables globally. If you use this keyword to declare a variable, the variable can also be accessed and changed globally.
Note: It is suitable for shorter codes.
The syntax is:
var variableName = "Variable-Value;"
An example of declaring variables through var:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> </head> <body> <script> var geeks = "I love PHP中文网"; console.log(geeks); </script> </body> </html>
will output "I love PHP Chinese website", as shown below:
The second waylet
:
let: This keyword is used As for declaring variables locally, if you declare a variable using this keyword, the variable is accessible locally and is also mutable.
Note: Variables declared by let are only valid within the code block where the let command is located.
Syntax:
let variableName = "Variable-Value;"
An example of declaring variables through let:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> </head> <body> <script> if (true) { let geeks = "I love PHP中文网"; console.log(geeks); } /* 显示未定义错误 */ console.log(geeks); </script> </body> </html>
Output:
The third wayconst
:
const: This keyword is used to declare variables globally. If you declare a variable using this keyword, the variable is globally accessible and cannot be changed.
Note: const declares a read-only constant. Once declared, the value of the constant cannot be changed.
Grammar:
const variableName = "Variable-Value;"
An example of declaring variables through const:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> </head> <body> <script> const geeks = "I love PHP中文网"; console.log(geeks); </script> </body> </html>
Output:
Finally for everyone Recommended "JavaScript Basics Tutorial"~Welcome everyone to learn~
The above is the detailed content of Teach you how to declare variables in JavaScript in different ways. For more information, please follow other related articles on the PHP Chinese website!