JavaScript 101

Part 1
Statements, Variables, Functions, and Primitive Data Types

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important
  • Help each other
  • Have fun

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of this class?
  • What is your favorite city?

What we'll cover today

  • Intro to Programming
  • Brief history of JavaScript
  • What does JavaScript do?
  • Statements
  • Variables
  • Primitive data types
  • Functions
  • Scope
  • Coding conventions

Intro to Programming

What is programming?

A way of telling the computer what to do. Commands!

Types of Programming

  • High-level: abstracts things away from the computer, makes it easier for us
  • Assembly: specific to the computer
  • Machine code: actual code executed by the computer

Compiled v. Interpreted Languages

Compiled Languages

Source code is translated to machine code before it can run. Usually these are lower-level languages closer to machine code.

Interpreted Languages

Code is executed automatically. Each statement is translated into subroutines that are already compiled into machine code. These are higher-level languages abstracted from machine code.

Compiled v. Interpreted Languages

The Language of the Web

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

Brief History of JavaScript

  • 1995: At Netscape, Brendan Eich created "LiveScript", which gets renamed to "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.
  • 2012: ECMAScript Harmony spec nearly finalized.

What can JavaScript do?

Statements

Each separate instruction in Javascript is called a 'statement'. A 'simple' statement represents a single instruction and ends with a semi-colon.

Statements

Type this in the JavaScript console in your web browser:


console.log('Hello World!');
            

What happens?

Variables

Variables store values so we can re-use them later.

Variables are one of the basic building blocks of Javascript.

Variables

Variables have to be declared before you can use them. There are two ways to do this.

Option 1:


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

Option 2:


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

In both cases, x is our variable. 5 is the value of that variable.

Variables

You can also re-assign variables:


var z = 5;
z = 1;
console.log(z);
            

What does this print out?

Data Types

Primitives

Variables can store different "types" of data.

Primitive Data Types: Strings

An immutable string of characters.


var greeting = 'Hello Kitty';
var restaurant = "Taco's Place";
            

Primitive Data Types: Numbers

Whole numbers (6, -102) or floating point (5.8737).


var myAge = 28;
var pi = 3.14;
            

Primitive Data Types: Booleans

Represents logical values true or false.


var catsAreBest = false;
var dogsRule = true;
            

It looks like a string, but it's not.

Primitive Data Types: undefined

Represents a value that hasn't been defined.


var notDefinedYet;
            

Primitive Data Types: null

Represents an explicitly empty value.


var goodPickupLines = null;
            

How does JavaScript know what data type something is?

Loose Typing

You don't tell JS what type of data type it is, it guesses. You can use typeof to see what it thinks:


var hello = "Hello, world";
typeof hello;
            

What does that return?

Variables

Naming

Variable Naming

Rules:

  • 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

Variable Naming

Okay:


var numPeople;
var $mainHeader;
var _num;
var _Num;
            

Not okay :(


var 2coolForSchool;
var soHappy!;
var 10019;
            

Dubious:


var HELLOFRIENDS;
var TACOparty;
            

Variables

Expressions

Variables and Expressions

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


var x = 2 + 2;
var y = x * 3;
            

This includes strings, too:


var name = 'Shawn';
var greeting = 'Hello ' + name;
            

Exercise!

Variables

If you get stuck, raise your hand.

Comments

Private notes in your code.

Comments

Comments are human-readable text ignored by the computer:


// You can write single-line comments
var 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.
*/
            

Comments

There is a time and a place for comments.

Comments are good when:

  • You're learning something new
  • There's something that needs fixing
  • Something is not finished, or needs to be done

Comments

Comments should not:

  • Explain what your code is doing
  • Provide instructions to the user

Comments

Too many comments is a code smell.

It means your code isn't easy to understand.

But! Don't worry about this too much when you're learning!

Functions

Functions

Functions are re-usable collections of statements.

First, you declare the function:


function sayMyName() {
  console.log("Destiny's Child");
}
            

Then call it as many times as you want:


sayMyName();
            

Functions are not run straight away, they are stored in memory until they are called.

Beware!

Circular dependencies

Don't do this (no, seriously, don't):


function chicken() {
    egg();
}

function egg() {
    chicken();
}

egg();
            

This is a loop that will never end. We want to avoid stuff like this.

Functions

Arguments

Function Arguments

Functions can accept any number of named arguments:


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

sayMyName('Testy McTesterFace');
            

function addNumbers(num1, num2) {
  var result = num1 + num2;
  console.log(result);
}

addNumbers(3, 10);
            

Function Arguments

You can also pass variables:


var number = 10;
addNumbers(number, 2);
            

Functions

Return values

Return Values

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


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

var sum = addNumbers(5, 2);
            

You can use function calls in expressions:


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

Scope

Variables and Functions

Variable Scope

Variables have "function scope". They are visible in the function where they're defined.

There are two scopes we have to be worried about:

  • Local scope
  • Global scope

Local scope

Restricted to the function it is defined in.


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

What happens when we run this code?

Global scope

Available to your entire program.


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

Coding Conventions

Spacing

Spacing

Use newlines between statements and use spaces (2 or 4, pick one and stick to it) 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;
}
            

Exercises!

Functions

Raise your hand if you get stuck.

Getting help

Google for questions or check Stack Overflow. Also look on the Mozilla Developer Network.

Before you share your problematic code, post it to jsbin.com

Homework

Yes, just like high school.

Homework

Save your code to jsbin.com for easy lookup and console access.



See you next week!