Intro to JavaScript

RDU

  • Learn how to problem-solve using JavaScript
  • Practice programming fundamentals
  • Identify next steps for learning

Today's goals

© 2016 Thinkful RDU All Rights Reserved.

  • Ben White

  • Left an anthropology PhD program after four years

  • Worked as a developer first in 2010 at a marketing software company doing sentiment analytics

  • Joined Thinkful in 2013 as an education engineer, and now run curriculum development

About me

© 2016 Thinkful RDU All Rights Reserved.

  • First steps towards becoming a software engineer

  • Communicate better with developers

  • Build out your business and app ideas

Why learn JavaScript?

© 2016 Thinkful RDU All Rights Reserved.

Why learn JavaScript?

Details at http://githut.info

© 2016 Thinkful RDU All Rights Reserved.

What is JavaScript?

© 2016 Thinkful RDU All Rights Reserved.

  • Written by Brendan Eich in 1995
  • Initial version written in 10 daysFront end:
  • Unrelated to Java, but named to draft off its popularity
  • Default programming language of browsers.

What is JavaScript?

© 2016 Thinkful RDU All Rights Reserved.

  • Programming language you can use to write instructions a computer can follow
  • Front end:
    • Retrieve data from APIs and display it
    • Handle user interactions
  • Server side:
    • Create APIs
    • Serve static resources
    • Manage data and persistence
  • Rich community and eco-system of open source libraries

What is programming?

© 2016 Thinkful RDU All Rights Reserved.

  1. Using everyday language to clearly state a problem.
  2. Using precise language to describe different solutions.
  3. Implementing a solution to the problem in a way your computer can understand.

What we'll cover today

© 2016 Thinkful RDU All Rights Reserved.

  • How to get JavaScript code to execute on a webpage.
  • How to use variables
  • How to use functions to create reusable sets of instructions
  • JavaScript's data types
  • Using Chrome Developer tools to write and execute JavaScript in the browser.

What we won't cover...

© 2016 Thinkful RDU All Rights Reserved.

  • HTML and CSS
  • Server-side programming
  • jQuery or any JavaScript framework
  • Object oriented programming
  • etc.

Our starting point

© 2016 Thinkful RDU All Rights Reserved.

  • Install Google Chrome if you don't have it already
  • Install Sublime Text 3 if you don't have a text editor you use
  • Download the starter files: https://github.com/Thinkful-Ed/intro-to-js-starter-files
  • Open starter files in Sublime Text
  • Open index.html in browser and Developer Tools

Our starting point

© 2016 Thinkful RDU All Rights Reserved.

  • Project open in Sublime text
  • Page open in Chrome
  • Developer tools open (Mac: option-cmd-J, windows: Ctrl + Shift + J

Working with variables

© 2016 Thinkful RDU All Rights Reserved.

A variable is a name that points to a value.

  • Shorthand way to refer to values we create elsewhere in a program.
  • Allow us to manage state in a program.

Working with variables

© 2016 Thinkful RDU All Rights Reserved.

Syntax for variables

© 2016 Thinkful RDU All Rights Reserved.

Declaring vs. assigning vs. declaring and assigning

// declaring
var firstVariable;

// assigning a value
firstVariable = 6;


// re-assigning value
firstVariable += 1;

// referring to variable
console.log(firstVariable);
alert(firstVariable);


// declaring and assigning
var secondVariable = 'foo';

Syntax for variables

© 2016 Thinkful RDU All Rights Reserved.

  • Use the var keyword
  • Assign a value with the assignment (=) operator
  • Semi-colons after each line of code

Naming variables

© 2016 Thinkful RDU All Rights Reserved.

  • Choose meaningful words for variable names. numberOfGorillas is better than x
  • Use camelCasing. First word starts with lowercase, subsequent words with uppercase. 
  • Must start with a letter.

What kinds of values can variables have?

© 2016 Thinkful RDU All Rights Reserved.

  • String
  • Number
  • Function
  • Object
  • Null
  • Undefined
  • Boolean

Strings

© 2016 Thinkful RDU All Rights Reserved.

  • Create with opening and closing quotes (single or double)
  • Can concatentate them
var foo = 'foo';
var bar = "bar";
var fooBar = foo + bar;

Numbers

© 2016 Thinkful RDU All Rights Reserved.

  • Can represent integers and floating point decimals
  • Can use arithmetic operators to manipulate (aka, +, -, *, /)
var width = 10;
var height = 5.5;
console.log("Area is " + (width * height)); // => Area is 55

Booleans, undefined, null

© 2016 Thinkful RDU All Rights Reserved.

  • Booleans signify truth or falsity
  • `null` is special value indicating variable has no value
  • `undefined` is special value browser assigns to declared but unassigned variables. Never directly set a variable's value to `undefined`.
// booleans and logical operators
var sunny = true;
var warm = false;
var shouldGoOut = sunny && warm;

// null
var accountNum = null;

// undefined
var myVar;
console.log(myVar);

Functions

© 2016 Thinkful RDU All Rights Reserved.

Used to represent re-usable sets of instructions

// defining 
function sayHi() {
  console.log('Hi');
}

// executing
sayHi(); // => Hi


// this function takes a `name` argument
function sayHiToName(name) {
  console.log('Hi ' + name);
}

sayHiToName('Sheila') // => Hi Sheila

// this function *returns* a value
function isEven(num) {
 return num % 2 === 0;
}

isEven(3); // => false

Objects

© 2016 Thinkful RDU All Rights Reserved.

Hold collections of values together

// defining object
var fido = {
  type: 'dog',
  legs: 4,
  name: 'Fido',
  speak: function() { console.log('arf arf') }
};

// dot notation
console.log(fido.name) // => Fido
fido.speak(); // => arf arf

// reassigning the value of .legs
fido.legs = 3;

// bracket notation
fido['type']; // => dog


// arrays
var myList = [1, 2, "three", true, fido];
myList[0]; // => 0

Challenge 1: Say your name

© 2016 Thinkful RDU All Rights Reserved.

  • Remove existing code from `app.js`
  • Add a new function called `sayMyName`
  • This function should log the text `My name is Ben`, displaying your name in place of Ben
  • Define the function, and then call it
  • Consider using Dev Tools to interactively code solution
  • Save changes to `app.js`
  • Should be able to see output in Dev Tools

Solution 1: Say your name

© 2016 Thinkful RDU All Rights Reserved.

// inside app.js

function sayMyName() {
  console.log('Ben');
}

sayMyName();

Challenge 2: Write an adder function

© 2016 Thinkful RDU All Rights Reserved.

  • Add new code below existing code in `app.js`
  • Create new function called `adder`.
  • `adder` should take two arguments: `num1` and `num2`
  • It should return the value of num1 + num2
  • Define the function, and then call it
  • Save changes to `app.js`
  • Should be able to see output in Dev Tools

Solution 2: Write an adder function

© 2016 Thinkful RDU All Rights Reserved.

// inside app.js

// ... existing code

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

console.log(adder(3, 5));

Deeper into strings

© 2016 Thinkful RDU All Rights Reserved.

Built in string methods

var foo = "foo bar foo bar foo bar";
foo.length; // =>
foo.charAt(0); // => "f"
foo.indexOf("bar"); // => 4
foo.slice(1); // => "oo bar foo bar foo bar"
foo.split(" ") // => ["foo", "bar", "foo", "bar", "foo", "bar"]
foo.toUppercase() // => "FOO BAR FOO BAR FOO BAR"
foo.replace('foo', 'bar') // => 'bar bar bar bar bar bar'

Deeper into strings

© 2016 Thinkful RDU All Rights Reserved.

Special characters and escaping

var foo = "He said, \"Foo!\"";
var bar = 'Dear Paul,\nHow are you?';

Challenge 3: wiseperson function

© 2016 Thinkful RDU All Rights Reserved.

  • Add new code below existing code in `app.js`
  • Create new function called `wisePerson`.
  • `wisePerson` should take two arguments: `who` and `what`
  • Given inputs of "Paul" for `who` and "Carpe diem!" for `what`, `wisePerson` should print the string value "A wise person named Paul said: 'Carpe diem!'"
  • Define the function, and then call it
  • Save changes to `app.js`
  • Should be able to see output in Dev Tools

Solution 3: wiseperson function

© 2016 Thinkful RDU All Rights Reserved.

function wisePerson(who, what) {
 console.log(
  "A wise person named " + who + " said, '" +
  what + "'");
}

wisePerson('Paul', "Carpe diem!");

Challenge 4: Shouter

© 2016 Thinkful RDU All Rights Reserved.

  • Add new code below existing code in `app.js`
  • Create new function called `shouter`.
  • `shouter` should take one `text`, which is a string.
  • It should return the text in all uppercase
console.log(shouter(
  "I am whispering can't you tell?")); // => I AM WHISPERING CAN'T YOU TELL?

Solution: Shouter

© 2016 Thinkful RDU All Rights Reserved.

function shouter(text) {
  return text.toUpperCase();
}

console.log(shouter('I am whispering'));

Challenge 5: Tweet analyzer

© 2016 Thinkful RDU All Rights Reserved.

  • Add new code below existing code in `app.js`
  • Create new function called `analyzeTweet`.
  • Paste the code from this gist: http://bit.ly/2gCzPNO
  • `analyzeTweet` should take one arguments: `tweet`, which is an object representing a tweet
  • Be aware that this challenge is  more difficult than the previous ones. Use it as an opportunity to work at the edge of your comfort zone.
{
 text: "All your base belong to us",
 author: "haxor3000",
 wordLength: 5,
 isRetweet: false,
 mentionsOthers: false
}

Challenge 5: Tweet analyzer

© 2016 Thinkful RDU All Rights Reserved.

Given:

{
 text: "All your base belong to us",
 author: "haxor3000",
 wordLength: 5,
 mentionsOthers: false
}
var tweet = {
  author: "@billy",
  text: "All your base belong to us"
  id: 333333
}

`analyzeTweet(tweet)` should return:

Challenge 5: Tweet analyzer

© 2016 Thinkful RDU All Rights Reserved.

Given:

{
 text: "RT @billy all your base belong to us",
 author: "@sally",
 wordLength: 8,
 mentionsOthers: true
}
var tweet = {
  author: "@sally",
  text: "RT @billy All your base belong to us"
  id: 444
}

`analyzeTweet(tweet)` should return:

Challenge 5: Tweet analyzer

© 2016 Thinkful RDU All Rights Reserved.

Hints

// convert string into array of words

var foo = ['lions and tigers and bears oh my!']
var splitUp = foo.split(" ");
console.log(splitUp); // => [
  'lions', 'and', 'tigers', 'and', 'bears', 'oh', 'my'];

// get length of array

var myArray = [1, 2, 3];
console.log(myArray.length); // => 3


// check if string contains substring
var string = "cats and dogs"
var containsCats = string.indexOf("cats") > -1;

Solution: Tweet analyzer

© 2016 Thinkful RDU All Rights Reserved.

function analyzeTweet(tweet) {
  return {
   text: tweet.text,
   numberWords: tweet.split(" ").length,
   mentionsOthers: tweet.indexOf('@') > -1
  };
} 

analyzeTweet({
    text: 'lions and tigers and bears',
    author: '@janeDoe',
    id: 2020202020
});

Next steps for learning

© 2016 Thinkful RDU All Rights Reserved.

  • Spend your first 10 hours on Codecademy
  • Google is your friend
  • Find an app idea you're excited about and practice at the edge of your abilities
  • Learn about jQuery and DOM manipulation
  • Structured learning:
    • Free / cheap online resources
    • Night classes at community college
    • Coding bootcamp (on or off line)
  • Ignore the "flavor of the month" (for now).

Thank you!

Email me with questions or suggestions:

ben@thinkful.com

RDU

deck

By Ben White

deck

  • 1,119