Variables and data types

Objectives

Variables

See W3schools.com JavaScript variables article

  1. Variables are named memory locations that can contain values.
  2. The var keyword can (and should) be used to declare variables in JavaScript.
  3. The var keyword helps control the scope of a variable
  4. Strict mode requires variables to be declared using the "var" keyword
  5. 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.
  6. You can set the value of a variable using an assignment operator (=).
  7. Naming variables:
  8. 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.
  9. Example of creating (declaring) a variable: var num;
  10. Example of declaring multiple variables with one statement: var num, x;
  11. Example of setting a variable's data type when declaring it: var num = new Number;
  12. Example of setting a variable to a value: num = 7;
  13. Example of creating and initializing a variable in one statement: var num = 7;
  14. Example of creating and initializing multiple variables in one statement: var num = 7, greeting = "Hi";
  15. 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

  1. String: a series of characters; string literals are contained within quotes; the quotes can be either single or double quotes
  2. Number: numbers can be written with or without a decimal point; exponential representation can also be used (5e3 is 5000, 5e-3 is .005)
  3. Boolean: true or false
  4. Array: a set of variables that have the same name, but can be distinguished using a subscript
  5. Object: a collection of properties and their values; the properties can include functions; technically, all JavaScript variables are objects
  6. null: you can set a variable to null to get rid of its value
  7. undefined: the value of a variable which contains no value