What is a Variable?!A variable is a container with a label (name) where you store a certain value ( a piece of data ) to use it in your code.
Declaring variables and assigning values to them
To declare a variable is to give it a name, you have to use one of these keywords:
- var : most common key to declare variables.
- let : only visible within the block where it's declared.
- const : used for constant values and cannot be changed , it will cause an error if you tried to do so.
var myVariable ; let myName ; const pi ;
- you have to use camelCase (example: myName, schoolYear, etc.)
- You can add numbers but not at the beginning (whatever , who will name a variable 2myVarName, this won't satisfy the rule n.o. 2)
- you cannot use hyphens " - " or spaces but you can use underscores " _ " instead (note : underscores can be used as the first character in a variable name).
- You cannot use any of the reserved keywords (like : var, let, const, if, while, for and so on) . don't worry if you don't know a lot of keywords , if you tried to use one it will be highlighted as a keyword and results in an error.
Assigning values to variablesTo assign a value to a variable, use the assignment operator " = " (equal sign).
// Declaring variables var myVariable ; let myName ; const pi ; // assigning values to variables myVariable = 25; myName= "Rawan"; pi = 3.14;
Note : you can declare variables and assign values to them on the same line.
// Declaring a variable and assigning a value to it on one line var myAge = 15;
Main Datatypes :
- Numbers : they can be integer numbers or floats( numbers with decimal points).
- Strings : any series of characters included between quotes (double quotes " " or single quotes ' ' ).
- Boolean value : has one of the two values true or false .
- null : means nothing.
- undefined : something that hasn't been defined.
- Arrays : can store more than one piece of data.
- Objects : used to store key-value pairs( each property associated with its own value).
console.log("Hello World !"); // output : Hello World ! var myScore = 320 ; console.log(myScore); // output : 320
Notes , Again...1 . Everything greyed out (not highlighted) after " // " is called a comment , you write them to explain to yourself and others what your code does , you write them using :
- // : for inline comments
- /* */ : for multi-line comments
// I am an inline comment /* I am a multi-line comment */
3 . Variables that are declared but not assigned to store any values are called " Uninitialized variables " and have a default value of undefined .