- Just like we follow some rule while speaking english (the grammar) we have some rules to follow while writing a javascript program.
- The set of those rules is called syntax in javascript.
- A variable is a container that stores a value.
- This is very similar to the containers used to store rice, water and oats (treat this as an analogy).
- The value of a javascript variable can be changed during the execution.
- In javascript, we have two types of variables: var and let.
- var is a global variable and can be used anywhere in the program.
- It is declared using the keyword var followed by the variable name and the value.
- It can be updated and re-declared within its scope.
- It is initialized with undefined.
var a = 7;
- let is a block-scoped variable and can be used only within the block it is defined.
- It is declared using the keyword let followed by the variable name and the value.
- It can be updated but not re-declared within its scope.
- It is not initialized with undefined.
let a = 7;
- const is a block-scoped variable and can be used only within the block it is defined.
- It is declared using the keyword const followed by the variable name and the value.
- It can be updated but not re-declared within its scope.
- It is not initialized with undefined.
const a = 7;
- Letters, digits, underscore and $ sign is allowed.
- Must begin with a $, _ or a letter.
- Javascript reserved words cannot be used as a variable name.
- Saad and sAAd are different variables (case sensitive).
- In javascript, there are several data types such as string, number, boolean, object, array, function, etc.
- We can use the typeof operator to check the data type of a variable.
typeof "Hello World" // "string"
typeof 10 // "number"
typeof true // "boolean"
typeof {} // "object"
typeof [] // "object"
typeof function() {} // "function"
- var is glovaly scoped While let & const are block scoped.
- Var can be updated and re-declared within its scope.
- let can be updated but not re-declared.
- const can neither nor be re-declared.
- var variables are initialized with undefined whereas let and const variables are not initialized.
- const must be initialized during declaration unlike let and var.
- What is the difference between var, let, and const in JavaScript?
- What is the difference between undefined and null in JavaScript?