JavaScript Syntax
JavaScript code consists of a set of statements that need to follow certain rules as mentioned below.
- JavaScript is Case-sensitive
- Hyphen is reserved for mathematical subtractions, so it cannot be used for other purposes, like naming variables.
- Javascript identifiers must follow the below rules.
- Must either begin with a letter (A-Z or a-z), a dollar sign ($), or an underscore sign (_).
- Then subsequent characters may be letters, digits, dollar signs, or underscores.
- JavaScript keywords are reserved and must be used only for the purpose they are defined for.
- Use the keywords "var", "let", and "const" to declare a variable.
JavaScript Literals & Variables
In JavaScript, there can be two types of values, fixed and variable.
- Fixed values are called Literals, which are constant in nature.
- Variable values are called Variables, their values vary during the execution.
The below example contains both the literal and variables.
var name = "Cheese"; //Here "name" is a variable and "Cheese" is a literal
var price = 120.25; //Here "price" is a variable and "120.25" is a literal
JavaScript & Lower Camel Case
Hyphen is reserved for mathematical subtractions, so it cannot be used for other purposes.
So, to variable names with multiple words, use either an underscore, uppercase Camel case, or lowercase Camel case.
Using underscore for the variable names.
- first_name, last_name, master_card, user_name
Using Upper Camelcase format for the variable names.
- FirstName, LastName, MasterCard, UserName
Using Lower Camelcase format for the variable names.
- firstName, lastName, masterCard, userName
JavaScript is Case-sensitive
All the variables, language keywords, function names, and other identifiers must be typed correctly, with consistent capitalization.
- The variable "myVar" must always be referred to as "
myVar
", and not as "myvar
" or "MyVar
". - The function "myFunction()" must always be referred to as "
myFunction()
", and not as "myfunction()
" or "MyFunction()
".
var myVar = "Hello World!";
console.log(myVar); // Prints: HelloWorld!
console.log(MyVar); // Error: Uncaught ReferenceError: MyVar is not defined
console.log(myvar); // Error: Uncaught ReferenceError: myvar is not defined
Overall
JavaScript syntax is nothing but a set of rules recommended for clean and maintainable code.