- Web Development with MongoDB and Node(Third Edition)
- Bruno Joseph D'mello Mithun Satheesh Jason Krol
- 468字
- 2021-07-08 10:32:43
Syntax basics
The most basic thing you can do in pretty much any programming language is declare a variable. Unlike most other languages, JavaScript is a dynamically-typed language, which means when you declare a variable, its value can be of any type and can change during the course of its lifetime. However, in contrast, a strongly-typed language dictates that a variable defined as a string type must always be a string and must always have a value of a string. The strong typed feature is included in es6 which we are going to learn next. For now, to declare a variable in JavaScript, simply use the var keyword before your variable name:
var myVariable; // declaring a variable with no value var myFirstName = "Jason"; var myLastName = "Krol"; var myFullName = myFirstName + ' ' + myLastName; // => Jason Krol
The preceding code snippet shows how we declare variables and define them with initial values alongside their declarations. The + operator is used for string concatenation.
Also, we use camel case for the variable names. It is not mandatory that you use camel case for variable naming, but it is more common in object-oriented languages to follow camel case as opposed to the underscore-based approach.
Since, es6 has introduced two more keywords for variable declarations, namely let and const, has made JavaScript a lot more elegant. First, lets learn const by considering the following example:
const loopOver = [1,2,3];
The usage of const is same as var. Declaring a variable with const makes itself immutable and it cannot be used for reassigning new content in itself.
Let's test it by adding the following line:
loopOver = [4,5,6];
It throws the following error:
Uncaught TypeError: Assignment to constant variable
Well, Why is it needed? The recommended practice for coder is to keep things simple which means using a single variable to represent a single value for a time. However, we discussed about the dynamicity of the variable earlier which has its own advantages, sometimes there is need to represent a data which is immutable itself. Like store some credentials of server configuration or the Node packages itself. The usage can vary but will be applied with a single rule of one time assignment.
To study the let keyword, we need to know about the scope of variables first which is covered in the following section.
- 手機安全和可信應用開發指南:TrustZone與OP-TEE技術詳解
- 大學計算機應用基礎實踐教程
- Visual C++串口通信開發入門與編程實踐
- 精通搜索分析
- Interactive Applications Using Matplotlib
- PHP+MySQL網站開發項目式教程
- D3.js 4.x Data Visualization(Third Edition)
- Python編程實戰
- Linux C編程:一站式學習
- iPhone應用開發從入門到精通
- Python Data Science Cookbook
- Odoo 10 Implementation Cookbook
- Mastering Elixir
- 實戰Python網絡爬蟲
- Three.js權威指南:在網頁上創建3D圖形和動畫的方法與實踐(原書第4版)