Additional Notes: Variables
How to declare a variable in JavaScript?
Declaring a variable with var:
● Use the reserved keyword var to declare a variable in JavaScript.
Syntax:
var variable_name;
var variable_name = value;
E.g.1 var name; //declaring a variable without assigning value.
Note: default value of the variable that does not have any value is undefined.
E.g. 2. var name = "John"; //declares and assign a string value
Since JavaScript is a loosely typed language that means it does not require a data
type to be declared. you can assign any value to a variable. (e.g string,
integer,float,boolean etc).
Re-Declaring JavaScript variables:
You can re-declare a javascript variable using var, which will not be losing its value.
E.g. The variable val will still have the value 10 after the execution of these
statements.
var val = 10;
var val;
console.log(val);//10
Note: You can't re-declare a variable declared with let or const.
let and const keywords
ES6 introduced two new keywords: let and const.
let:
● You can't re-declare the variable defined with the let keyword but can update
it.
E.g.
const
● Const is used to declare read-only variables, ie, they can’t be reassigned and
redeclared.
For e.g.
This will print the value of the constant variable as usual. But what if we tried
to reassign a value to it?
const a = 10;
console.log(a);
a = 20;
This will produce the following error:
a = 20;
//^ TypeError: Assignment to constant variable.
Note: You will be learning more about let and const in further lectures.
The general rules for constructing names for variables (unique
identifiers) are:
● Names can contain letters, digits, underscores, and dollar signs.
● Names must begin with a letter.
● Names can also begin with $ and _ (but we will not use it in this
tutorial).
● Names are case sensitive (y and Y are different variables).
● Variable names cannot contain spaces.
○ E.g var first Name = “John” (incorrect)
var firstName = “John” (correct)
● Reserved words (like JavaScript keywords) cannot be used as names.
Check out this complete list of reserved words.
Correct JavaScript Variables:
var x = 20;
var _name = "John";
var value1 = 25;
var firstName = "John";
Incorrect JavaScript Variables:
var 124 = 35;
var *value = 87;
var var = 25; //'var' is not allowed as a variable declaration name.