Essentials
Variables
Learn about variables in JavaScript.
Declare & assign
You can declare and assign value to a variable.
let username;
username = 'DabAZ';
const
Use by default for values that never change.
const taxRate = 0.1;
let
Use only when the value needs to be updated.
let age = 20;
age = 20 + 1;
console.log(age);
21
var
Don't use var. It allows variables to be redeclared, which lead to bugs.
var name = "John";
Naming conventions
Only use the following naming conventions:
- Camel case:
myFirstVariable - Pascal case:
MyFirstVariable - Snake case:
my_first_variable - Constant case:
MY_FIRST_VARIABLE - Totally lower case:
myfirstvariable
The camel case myFirstVariable is the most common and recommended naming convention.
Here are some names that you should avoid when naming your variables:
const myFirst Variable = 'Hello, world!';
const 'myFirstVariable' = 'Hello, world!';
const 1FirstVariable = 'Hello, world!';
Make sure you're clearly specifying what does the variable represent.
Types
typeof
Use the typeof operator to get the type of a variable.
const age = 20;
console.log(typeof age);
number
TypeScript
TypeScript is a superset of JavaScript that adds static typing.
const age: number = 20;
Implicit conversion
In this case, the age variable is converted to a string and concatenated with the name variable.
const age = 20;
const name = 'John';
console.log(age + name);
20John
Explicit conversion
In this case, we specify the type that the number1 variable should be converted to.
const number1 = '20';
const number2 = 30;
console.log(Number(number1) + number2);
50