- 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.
- Advanced Splunk
- Windows系統(tǒng)管理與服務配置
- Clojure for Domain:specific Languages
- Web Development with Django Cookbook
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- R大數據分析實用指南
- Haxe Game Development Essentials
- Creating Stunning Dashboards with QlikView
- C專家編程
- 小程序,巧應用:微信小程序開發(fā)實戰(zhàn)(第2版)
- Python趣味編程與精彩實例
- Go語言從入門到精通
- Python Programming for Arduino
- Microsoft HoloLens By Example
- Flink原理深入與編程實戰(zhàn):Scala+Java(微課視頻版)