Javascript Variables
Storing & Manipulating Data With Variables
Variables are containers for storing data. A variable name is a label that points to this data that will allow you to access and manipulate this stored data. Creating a variable is called declaring it. You declare a variable in JavaScript by using the var keyword. Generally it’s best practice to declare all variables at the beginning of a script. All variables must be identified with a unique name. To assign a value to the variable, use the = sign. A variable declared without a value will have the value undefined. It’s best practice to end all lines of code in JavaScript with a ; semicolon. It’s not required but it’s considered best practice.
There are 3 ways to declare a variable in JavaScript.
- Var: Global Scope – Can be accessed from anywhere.
- Let: Local Scope – Only lets you use the variable within the block you declared it in. (Best practice to avoid naming collisions)
- Const: A variable that can not be changed.
The general rules for creating names for variables are:
- Variable names can contain letters, digits, underscores, or a dollar sign.
- Names must begin with a letter and not a number.
- Names can also begin with $ (but that’s usually reserved for JQuery)
- Names are case sensitive so (Price and price are different variables)
- Reserved keywords cannot be used as variable names.
- It’s best practice to use Camel Case for variable names. First letter of the first word is small. First letter of all following words should be capitalized.
JavaScript Provides 7 Different Data Types:
You can get the type of a variable using the typeof keyword: typeof variable;
- undefined: variable that hasn’t been defined.
- null: Means nothing. Set a variable to be nothing.
- boolean: Set a variable to true or false.
- number: Variable that contains any number.
- string: Variable that contains any text.
- symbol: A symbol may be used as an identifier for object properties and dynamically produces an anonymous, unique value.
- object: An object can store key value pairs.
Escape characters inside a sting.
Some chatacters don't work inside a sting and need to be escaped to work.
Quote | \’ |
Double Quote | \” |
Back Slash | \\ |
New Line | \n |
Carriage Return (Simular to new line) |
\r |
Tab | \t |
Backspace | \b |
Form Feed A form feed is a page-breaking. Forces the printer to start a new page. |
\f |
Bracket Notion
Get a character within a specific index of the string. Remember that javaScript uses ZERO BASED INDEXING which starts at 0 not 1.
Numbers & Variables In Javascript
In JavaScript, just like in algebra, we can use variables in an expression.