Variables and data types
Objectives
- explain what variables are
- use variables
- explain the basic data types available in JavaScript
Variables
See W3schools.com JavaScript variables article
- Variables are named memory locations that can contain values.
- The var keyword can (and should) be used to declare variables in JavaScript.
- The var keyword helps control the scope of a variable
- Strict mode requires variables to be declared using the "var" keyword
- Variables do NOT have to be declared before they are used in JavaScript. The
first use of a variable will automatically declare it if it isn't already declared -
but don't do that. It can cause problems.
- You can set the value of a variable using an assignment operator (=).
- Naming variables:
- The first character of the name must be a letter, '$', or underscore
- Subsequent characters must be letters, digits, underscore, or '$'
- Names are case sensitive
- You can't use words reserved by the JavaScript language
- Variables in JavaScript don't have a set data type (such as String or Number).
They can change data types as needed. This is not uncommon in scripting languages.
- Example of creating (declaring) a variable: var num;
- Example of declaring multiple variables with one statement: var num, x;
- Example of setting a variable's data type when declaring it: var num = new Number;
- Example of setting a variable to a value: num = 7;
- Example of creating and initializing a variable in one statement: var num = 7;
- Example of creating and initializing multiple variables in one statement: var num = 7, greeting = "Hi";
- Example of using a variable: var numSquared = num * num; // numSquared will be 49 (assuming num is 7)
JavaScript data types
See W3schools.com JavaScript data types article
- String: a series of characters; string literals are contained within quotes; the quotes can be either single or double quotes
- Number: numbers can be written with or without a decimal point; exponential representation can also be used (5e3 is 5000, 5e-3 is .005)
- Boolean: true or false
- Array: a set of variables that have the same name, but can be distinguished using a subscript
- Object: a collection of properties and their values; the properties can include functions; technically, all
JavaScript variables are objects
- null: you can set a variable to null to get rid of its value
- undefined: the value of a variable which contains no value