Skip to content

Instantly share code, notes, and snippets.

@mdang
Last active February 15, 2016 15:54
Show Gist options
  • Select an option

  • Save mdang/21be2a42dd98615b88d6 to your computer and use it in GitHub Desktop.

Select an option

Save mdang/21be2a42dd98615b88d6 to your computer and use it in GitHub Desktop.
Lesson: JavaScript Basics

JavaScript Basics

Learning Objectives

  • Explain what a programming language is
  • Explain what JavaScript is and how it fits into front end web development
  • List the primitive data types
  • Explain what variables are and why they are useful in a program
  • Create a variable and assign a value to it
  • Use common operators with variables and literals for arithmetic, string concatenation, and assigning values to variables
  • Explain the difference between expressions and statements
  • Explain what functions are and why they are useful in a program
  • Describe the role of the 'return' keyword and its importance to functions
  • Describe what arguments and parameters are, and their importance to functions
  • Declare a named function and return a value
  • Call a named function and store the value in a variable
  • Use console.log() to output debugging information

What is a programming language?

A programming language is a special language developers use to develop applications, scripts or other sets of instructions for computers to execute. With programming languages, we're able to use logic and execute commands based on any number of conditions. The moment we turn on our computer it begins to run programs and carry out instructions written by other developers in various programming languages.

How does a programming language like JavaScript differ from HTML/CSS? http://inventwithpython.com/blog/2013/12/15/why-is-html-not-a-programming-language/

With programming languages, we're able to process data and make decisions. We can store values like strings and integers, and later use them to perform calculations. They can also make decisions about what instructions to execute based on any condition.

How does JavaScript fit into front end development?

JavaScript, not to be confused with Java, was created in 10 days in May 1995 by Brendan Eich, then working at Netscape and now of Mozilla.

If HTML is like the bones that provide structure, CSS like the skin for appearance, then JavaScript can be thought of as the muscles that provide interactivity to a web page.

  • Supplies objects to control a browser
  • Manipulate the DOM
  • Respond to user events like form submissions, button clicks, page navigation, etc

What is a data type?

From the Wikipedia:

In computer science and computer programming, a data type or simply type is a classification identifying one of various types of data that determines: the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.

Data types are really similar across different languages:

Data Type Description Example
Strings Single words or sentences, surrounded by double or single quotes "lots of kittens", 'lots of kittens'
Integers Whole numbers, with no delimiter. Can optionally have underscores to make large numbers easier to read 42, 1024, 1\_000\_000
Floats Decimals, with no delimiter 3.14, 3.0
Booleans Represents either true or false true, false

Primitive Data Types

JavaScript has 5 primitive data types. Anything that doesn't belong to one of the 5 types below is an object.

  • Number - Integers, floating point numbers (e.g. 1, 100, 3.14)
  • Boolean - true or false
  • Strings - Any number of characters (e.g. "a", "one", "one 2 three")
  • Undefined - where no notion of the thing exists; it has no type, and it's never been referenced before in that scope
  • Null - where the thing is known to exist, but it's not known what the value is

null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).

REPL

A read–eval–print loop (REPL) is a simple, interactive computer programming environment that takes single user inputs (i.e. single expressions), evaluates them, and returns the result to the user; a program written in a REPL environment is executed piecewise.

In terminal:

node

Typeof operator

We can use the typeof operator to find out the type of a variable. The return value can be "number", "string", "boolean", "undefined", "object", or "function".

var n = 1;
typeof n;

Numbers

In more low-level languages, numbers are divided into two classes or objects:

  • Integers

     ..., -1,0, 2, 3, 4, 5, ...
  • Floats (or Decimal numbers)

     2.718, 3.14, .5, .25, etc

All numbers in JavaScript are "double-precision 64-bit format IEEE 754 values" - read this as "There's really no such thing as an integer in JavaScript." You have to be a little careful with your arithmetic if you're used to math in other programming languages. Let's take a look at what happens when we do this:

0.1 + 0.2
=> 0.30000000000000004

In JavaScript, these data points are the same type of object, which it calls Numbers, so if you know floats and integers do not go looking for them.

Strings

Strings are collections of letters and symbols known as characters, and we use them to deal with words and text in JavaScript. Strings are just another type of value in Javascript.

"John"
"Jane"
"123"

String helper methods

To find the length of a string, access its length property:

"hello".length;
=> 5

There's our first brush with JavaScript objects! Did I mention that you can use strings like objects, too?

Strings have other methods as well that allow you to manipulate the string and access information about the string:

"hello".charAt(0);
=> "h"

"hello, world".replace("hello", "goodbye");
=> "goodbye, world"

"hello".toUpperCase();
=> "HELLO"

Types of values like Number or String are not very useful without being able to form Expressions or Combinations.

Try your favorite number operators as expressions:

  1 + 1
  => 2
  2 - 1
  => 1

Converting Strings to Integers with parseInt() and parseFloat()

You can convert a string to an integer using the built-in parseInt() function. This takes the base for the conversion as an optional second argument, which you should always provide:

// Specify 10 for the decimal numeral system commonly used by humans
parseInt("123", 10);
=> 123

parseInt("010", 10);
=> 10

This will be important later when we're taking user input from the web and using it on our server or in our browser to do some type of numeric calculation.

Similarly, you can parse floating point numbers using the built-in parseFloat() function which uses base 10 always unlike its parseInt() cousin.

parseFloat("11.2");
=> 11.2

NaN

The parseInt() and parseFloat() functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is any invalid character in it.

A special value called NaN (short for "Not a Number") is returned if the string is non-numeric:

parseInt("hello", 10);
=> NaN

NaN is toxic: if you provide it as an input to any mathematical operation the result will also be NaN:

NaN + 5;
=> NaN

You can test for NaN using the built-in isNaN() function:

isNaN(NaN);
=> true

Variables

Variables are used to store data types into the memory of the computer so that they can be referenced later. When writing programs, it's more convenient and efficient to reference a variable than to retype the value over and over. The data stored with a variable can be changed after it's initially assigned, hence the name "variable".

  • Delcare variables using the var keyword
  • Variables are case sensitive
  • For code convention, use camelCase. What's important is that you're consistent

Always use var!

New variables in JavaScript are declared using the var keyword.

If you declare a variable without assigning any value to it, its type is undefined.

var a;
=> undefined

So lets try assigning a value to variable:

var name = "Alex";
=> undefined

name
=> "Alex"

Having made some expressions it becomes evident we want to store these values.

var myNumber = 1;
// or also

var myString = "Greetings y'all!"

The main note to make here is that these variables should always have the var keyword and use camelCase

Operators

Operators take one or more values (or variables), perform an operation and return a value

Arithmetic Operators

3 + 2; // Addition
3 * 2; // Multiplication
3 / 2; // Division
3 - 2; // Subtraction
3 % 2; // Modulus (Remainder)
3++; // Increment by 1
3--; // Decrement by 1

var a = 4; // assignment operation, = is the assignment operator 

String concatenation

var foo = 'hello';
var bar = 'world';

console.log(foo + ' ' + bar); // 'hello world' 

Type coercion - Taking a variable of one type and converting its value to another type when performing an operation or evaluation. You'll see type coercion when comparing variables of different types often times in dynamically typed languages.

Explain the difference between dynamically and static typed languages

3 + '2'; // Outputs 32

var one, two, result;
 
// one and two refer to string values of '1' and '2'
one = '1';
two = '2';
 
// result will contain the string '12';
result = one + two;
 
// redefine two to equal the number '2'
two = 2;
 
// concatenating a string and a number results in a string
// result will contain '12';
result = one + two;
 
// redefine one as a number
one = 1;
 
// then concatenate (or sum) the two values
// result will be 3
result = one + two;

Expressions vs Statements

A statement is a complete line of code that performs some action, while an expression is any section of the code that evaluates to a value. Expressions can be combined “horizontally” into larger expressions using operators, while statements can only be combined “vertically” by writing one after another, or with block constructs. Every expression can be used as a statement (whose effect is to evaluate the expression and ignore the resulting value), but most statements cannot be used as expressions.

A JavaScript program is a collection of statements. JavaScript statements combine expressions in such a way that they carry out one complete task.

Arrays

Unfortunately, strings and numbers are not enough for most programming purposes. What is needed are collections of data that we can use efficiently, Arrays.

Arrays are great for:

  • Storing data
  • Enumerating data, i.e. using an index to find them
  • Quickly reordering data

Arrays, ultimately, are a data structure that is similar in concept to a list. Each item in an array is called an element, and the collection can contain data of the same or different types. In JavaScript, they can dynamically grow and shrink in size.

var friends = ['Moe', 'Larry', 'Curly'];
=> ['Moe', 'Larry', 'Curly']

Items in an array are stored in sequential order, and indexed starting at 0 and ending at length - 1.

// First friend
var firstFriend = friends[0];
 => 'Moe'
// Get the last friend
var lastFriend = friends[2]
=> 'Curly'

We can even use strings like arrays:

var friend = "bobby bottleservice";
// pick out first character
friend[0]
//=> 'b'
friend.length

Working with Arrays

Using the JavaScript Keyword new, is one way of creating arrays:

var a = new Array();
=> undefined

a[0] = "dog";
=> "dog"

a[1] = "cat";
=> "cat"

a[2] = "hen";
=> "hen"

a
=> ["dog", "cat", "hen"]

a.length;
=> 3

A more convenient notation is to use an array literal:

var a = ["dog", "cat", "hen"];

a.length;
=> 3

Length method

The length method works in an interesting way in Javascript. It is always one more than the highest index in the array.

So array.length isn't necessarily the number of items in the array. Consider the following:

var a = ["dog", "cat", "hen"];
a[100] = "fox";
a.length; // 101

Remember: the length of the array is one more than the highest index.

Getting data from an array

If you query a non-existent array index, you get undefined:

var a = ["dog", "cat", "hen"];
=> undefined

typeof a[90];
=> undefined

Class Exercise

15 min

https://gist.github.com/mdang/c01d833997c14d437367

Functions

A function is a block of code designed to perform a particular task or calculate a value

  • Keeps code DRY. If you find repeating sections of code then that's a clue that you should be creating a function for it
  • Functions allow us to reuse code
  • Abstract complex functionality, isolate parts of the program from each other
  • Makes code easier to maintain/read

Functions can:

  • Have many parameters or none at all
  • Variables defined with the function are local to the function
  • Functions can access variables in the global scope, but other statements and expressions can't access any local variables defined in a function
// Function Expressions
// Assigning an anonymous function to a variable
var square = function(x) {
  return x * x;
};

// Assigning a named function to a variable 
var square = function squareValue(x) {
  return x * x;
};

// Function Declarations
// Named function 
function square(x) {
  return x * x;
}

Arguments vs parameters

An argument is the value/variable/reference being passed in, the parameter is the receiving value used within the function/block.

Anonymous vs Named functions

The difference is hoisting, as can be seen in the examples below

  // Error
  functionOne();

  var functionOne = function() {
  };

  // No error
  functionTwo();

  function functionTwo() {
  }

Return statement

  • JavaScript functions don't have to return anything, if you use the return statement with no value or don't use it at all, undefined is returned which is fine if you never expect to use a value
  • Functions can return any primitive data type, functions, and objects

Class Exercise

20 min

https://gist.github.com/mdang/931bf4eb58567facfd41

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment