Tallaght Campus

Department of Computing

Javascript Variables
  1. Notes on notation

    Notes on notation

    Instructions starting with ACTION:, like the one below, are for the student to carry out while reading the tutorial.

    ACTION: Open your browser.

  2. What are variables?

    What are variables?

    • A variable is a name that is associated with a value e.g. the variable x could be associated with the value 5.
    • A variable can be used anywhere a value can be used e.g. if we say x + 3 this adds 3 to the value of x.
    • In Javascript, a variable has to be declared and initialised in order to be used.
  3. Declaring and intialising variables

    Declaring and initialising variables

    Strict vs. sloppy

    • In standard Javascript (ECMAScript) variables are declared with keywords let, const or var:
      
      let x = 4;
      const y = "xyz";
      var z = true;
      				
      ACTION: Declare the variables above in the console and write an expression that uses them all.
    • Javascript interpreters by default do not insist on the keywords being used (in the same way that they do not insist on the semicolon at the end of instructions). This is called non-strict mode (or informally sloppy mode) operation and would allow the variables to be declared as:
      
      a = 4
      b = "xyz"
      c = true
      				
      ACTION: Declare the variables above in the console and write an expression that uses them all.
    • In this module we will use the standard way of declaring variables i.e. with keywords.

    Variable names

    • A variable always has a name. It is a named value by definition.
    • Any variable name must be a valid Javascript identifier.
    • Identifier validity is explained here.

    The keywords

    • let declares a local variable, which
      • does not have to be initialised when it is declared
      • can be given new values at any stage
      • is visible (is scoped) in the block where it is defined and below
      • this is the type of variable you will use most of the time
    • const declares a named constant, which
      • must be initialised when it is declared
      • cannot be changed
      • is scoped (has visibility) like a variable declared with let
    • var declares a global variable, which
      • does not have to be initialised when it is declared
      • can be given new values at any stage
      • has global scope (is visible everywhere once loaded)