Intro to JavaScript

The Language of the Web

Also used for plug-in scripting (Adobe/Mozilla/Chrome), game scripting, and more.

The History of JS

  • 1995: At Netscape, Brendan Eich created "JavaScript".
  • 1996: Microsoft releases "JScript", a port for IE3.
  • 1997: JavaScript was standardized in the "ECMAScript" spec.
  • 2005: "AJAX" was coined and the web 2.0 age begins.
  • 2006: jQuery 1.0 was released.
  • 2010: Node.JS was released.
  • 2015: ECMAScript 6 was released.

What can JS do?

  • Image switchers and lightboxes
  • Full featured web applications
  • Keep track of users with cookies
  • Interactive elements like tabs, sliders and accordions
  • Drawing and animation

Statements

Each instruction in JS is a "statement", like:

console.log('Hello World!');

Try it on repl.it:

Variables

Use const for most variables:

    const x = 5;
    console.log(x);

Use let if the variable needs to change

    let y = 2;
    y = 3;
    console.log(y);

Always use const unless you know you'll need to change the value later.

Primitive Data Types

Variables can store different "types" of data, like:

  • string: an immutable string of characters:
        const greeting = 'Hello Kitty';
        const restaurant = "Pamela's Place";
    
  • number: whole (6, -102) or floating point (5.8737):
        const myAge = 28;
        const pi = 3.14;
    
  • boolean: Represents logical values true or false:
        const catsAreBest = true;
        const dogsRule = false;
    
  • undefined: Represents a value that hasn't been defined.
        let notDefinedYet;
    
  • null: Represents an explicitly empty value.
        const goodPickupLines = null;
    

Strings

A string holds an ordered list of characters:

  const alphabet = "abcdefghijklmnopqrstuvwxyz";

The length property reports the size of the string:

  console.log(alphabet.length); // 26 

Each character has an index. The first character is always at index 0. The last character is always at index length-1:

  console.log(alphabet[0]); // 'a'
  console.log(alphabet[1]); // 'b'
  console.log(alphabet[2]); // 'c'
  console.log(alphabet[alphabet.length]); // undefined
  console.log(alphabet[alphabet.length-1]); // 'z'
  console.log(alphabet[alphabet.length-2]); // 'y'  

Variable Names

  • Begin with letters, $ or _
  • Only contain letters, numbers, $ and _
  • Case sensitive
  • Avoid reserved words
  • Choose clarity and meaning
  • Prefer camelCase for multipleWords (instead of under_score)
  • Pick a naming convention and stick with it
OK:
    numPeople, $mainHeader, _num, _Num
Not OK:
    2coolForSchool, soHappy!

Expressions

Variables can also store the result of any "expression":

    const x = 2 + 2;
    const y = x * 3;
    const name = 'Claire';
    const greeting = 'Hello ' + name;
    const title = 'Baroness';
    const formalGreeting = greeting + ', ' + title;

Loose Typing

JS figures out the type based on value, and the type can change:

    let x;
    x = 2;
    x = 'Hi';

A variable can only be of one type:

    const y = 2 + ' cats';
    console.log(typeof y);

Comments

Comments are human-readable text ignored by the computer:

    // You can write single-line comments
    const x = 4; // Or you can comment after a statement

    /* 
    Or you can write multi-line comments, if you have something very long
    to say like this gratuitously long description.
    */

Functions

Functions are re-usable collections of statements.

First declare the function:

    function sayMyName() {
        console.log('Hi Claire!');
    }

Then call it (as many times as you want):

    sayMyName();

Beware: Circular Dependencies

    function chicken() {
        egg();
    }

    function egg() {
        chicken();
    }

    egg();

Arguments

Functions can accept any number of named arguments:

    function sayMyName(name) {
        console.log('Hi, ' + name);
    }

    sayMyName('Claire');
    sayMyName('Testy McTesterFace');
    function addNumbers(num1, num2) {
        const result = num1 + num2;
        console.log(result);
    }

    addNumbers(7, 21);
    addNumbers(3, 10);

You can also pass variables:

    const number = 10;
    addNumbers(number, 2);
    addNumbers(number, 4);

Return Values

The return keyword returns a value to whoever calls the function (and exits the function):

    function addNumbers(num1, num2) {
        const result = num1 + num2;
        return result; // Anything after this line won't be executed
    }

    const sum = addNumbers(5, 2);

You can use function calls in expressions:

    const biggerSum = addNumbers(2, 5) + addNumbers(3, 2);

You can even call functions inside function calls:

    const hugeSum = addNumbers(addNumbers(5, 2), addNumbers(3, 7));

Variable Scope

Const and let have "block scope". They are visible only between the curly brackets where they are defined:

A variable with "local" scope:

    function addNumbers(num1, num2) {
      const localResult = num1 + num2;
      console.log("The local result is: " + localResult);
    }
    addNumbers(5, 7);
    console.log(localResult);

A variable with "global" scope:

    let globalResult;
    function addNumbers(num1, num2) {
      globalResult = num1 + num2;
      console.log("The global result is: " + globalResult);
    }
    addNumbers(5, 7);
    console.log(globalResult);

Coding Conventions: Spacing

Use newlines between statements and use spaces to show blocks.

Bad:

    function addNumbers(num1,num2) {return num1 + num2;}

    function addNumbers(num1, num2) {
    return num1 + num2;
    }

Good:

    function addNumbers(num1, num2) {
        return num1 + num2;
    }

Getting Help

Google for questions or check Mozilla Developer Network and W3Schools.

Post problematic code on JSFiddle and share the link on stackoverflow.