Skip to content

JavaScript Basics

HendrikSchmidt edited this page Sep 30, 2016 · 8 revisions

References

This is an overview of references you should check out whenever you need help.

  • It would be shameless not to name Google. Most questions you have, somebody else had before.
    Queries like js split sentence in words do the job (note the js).
  • Chances are high Google will point you to StackOverflow, a big, popular, live-saving Q&A website for coders. Don't user their search, Google does that better.
  • If Google doesn't point you to StackOverflow, it might point you to the official JavaScript documentation.
  • Also check out this short but sufficient Cheat Sheet.

Hello, Console!

Normally, you write JavaScript in a text file and then load that file in your browser or use another environment like Node.js. We will, too. But for a quick start, you can run JavaScript directly in your browser. Open any website. If you are using windows, press F12 in a browser of your choice. If you are using a mac, go to View → JavaScript Console in Chrome. In Safari, go to Preferences → Advanced and make sure "Show develop menu in menu bar" is activated. Then go to Develop → Show Error Console. You'll see something like this:

JS Console

Variables and values

Variables store all kinds of values.

var participants = 5; // Declares a variable named 'participants' and assigns the number '5' to it
var name = "Hackschool"; // Here we assign a string of characters 'H-a-c-...' to the variable

var isFun; // This only declares a variable
isFun = true; // And this assigns a truth value to the variable (initialization)

We declare a variable with var, we give it a name, and then assign (using =) any of the JavaScript data types (numbers, strings, truth values, arrays, and objects).

By the way, the stuff after // are comments. They don't affect the code, but they help explain it. It's good style to use them, because other people (or even your future self) might be confused by what you wrote. Multiline comments start with /* and end with */.

Arrays

Arrays are sequences of values.

var someNumbers = [0, 1, 2, 3, 4, 5];

We use square brackets ([ ]) to indicate an array. Inside those brackets goes any value or variable and each one is delimited by a comma.

// We can put in any value, variable, or even another array
var reallyAnything = [0, 1, true, false, "Hackschool", [3, 4], isFun]

(Throwing different types in an Array is not recommended!) To access a value in an array we use brackets and the position of that value in it (Important: We count from 0).

reallyAnything[0] // returns 0
reallyAnything[4] // returns "Hackschool"
reallyAnything[5] // returns [3 , 4]
reallyAnything[6] // returns true (what?)

Strings, as they are characters stringed together, a little like arrays. We can here too access single characters with square brackets:

var someString = "Hello, World!";
someString[1] // return "e"

Objects

If we have complex data, we use objects.

var hackschool = {
  participants: 8, // Objects can contain numbers,
  topic: "JS & Chatbots", // strings,
  instructors: ["Hendrik", "Willi"] // arrays and more (further down)
};

Objects are denoted with curly brackets ({ }). They contain pairs of properties and values (e.g. topic is a property, "JS & ..." is a value). A value can be any JS data type (including arrays). Property/value pairs are delimited by commas.

We access properties by writing our object's name, ., and then our property's name. We can also assign new properties after creating the object.

hackschool.topic  // Returns 'JS & Chatbots'
hackschool.makesSense = false; // Assings false to the new (!) property 'makesSense'

The expressive power of objects is clear once we nest objects and arrays inside each other.

var myFriends = [  // An array of objects
  {
    name: "Martha",
    year: 1989,
    // Objects can contain arrays
    likes: ["Skittles", "M&M (the blue ones)"],
    // And objects can also contain other objects
    favoriteBook: {
      title: "The Catcher in the Rye",
      year: 1951
    }
  }, {
    name: "McLovin",
    year: 1995,
    likes: ["Cats", "Dogs"],
    favoriteBook: {
      title: "You Don't Know JS: Up & Going",
      year: 2015
    }
  }
];

To access values in nested objects we use familiar notation:

myFriends[0].likes[0] // Returns 'Skittles'
myFriends[0].favoriteBook.title // Return 'The Catcher...'

Manipulating values

Most of programming is manipulating variables (variable). JS allows us to use the operator signs +, -, *, and / that behave different for different data types.

1 + 1  // Returns 2
5 * 5  // 25

// With variables
var twenty = 20;
var five = 5;
twenty / 2 // 10
twenty / five // 4

// Strings
"Hello, " + "World" // 'Hello, World'
"Number " + 5 // 'Number 5', but don't mix types, it only adds confusion

// Truth values (AND and OR)
true && true  // true
true && false  // false
true || false  // true
false || false  // false

Two values combined via an operator form an expression (as in "do this"). Expressions return values. We can assign those values to variables or use them in other expressions.

var five = 2 + 2 + 1;  // Assigns 5 to variable five
var price = 79.99;
var fivePercentDiscount = (five / 100) * price;  // First calculates (five / 100), then multiplies that by price
var meLike = "Bla" + "Bla" + "Bla";  // We can also combine strings

In addition, we have the following comparison operators:

==  // equal to
!=  // not equal to
<   // less than
>   // greater than
<=  // less than or equal to
>=  // greater than or equal to

They compare values and return either true or false.

true == false  // false
2 < 2 + 1  // true
3 >= 4 - 1 // true
var imSaying = "hey";
var youreSaying = "hey";
youreSaying = imSaying  // true

Comparison operators unleash their power once we use them to direct the flow of our program.

Directing flow

Whenever your code has to make a decision or repeat things, you have to rely on control structures (structures to control program flow).

If statement

To decide, use the if statement:

if (test) {
  // Do extraordinary things between the curly brackets
}

The if () { } statement looks at the expression in the (normal) brackets, in this case test, and checks its truth value. If test is true, the code in the {curly} brackets is run. If test is false, nothing happens.

var someNumber = 1;
var willItChange = true;
if (willItChange) {
  someNumber = 2;
}
// someNumber is now 2

For loops

The for-loop takes three expressions in the normal brackets:

  1. The initial expression: It's evaluated once in the beginning.

  2. A test expression: It's evaluated before every loop. The code in the curly is only run if that test is true.

  3. A final expression: It's evaluated after every loop.

For loops become very powerful when combined with arrays:

var someArray = [];
for (var i = 0; i < 1000000; i = i + 1) {
  someArray.push(i);  // push() is a function (what?) that pushes a value into an array
}
// someArray is not so empty anymore,
// but has a million values [0, 1, 2, 3, ..., 999998, 999999]
someArray.length  // Returns 1000000

// Let's take the sum of all values in someArray
var sum = 0;
for (var i = 0; i < someArray.length; i = i + 1) {
  sum = sum + someArray[i];
}
sum // Returns 49999950000

Functions

Once you start doing things over and over it's also smart to capture program tasks in functions. Functions take values (called arguments), do something, and return another value.

var someFunc = function (argument1, argument2, ...) {
  // Do something with my arguments when the function is called
  return someValue;
};

var square = function(a) {
  return a * a;
};

When defining a function, we name arguments in the normal brackets, and in the curly brackets describe what to do. If we want the code in a function to be run, we call the function with brackets and arguments:

var five = 5;
var fiveSquared = square(five); // 25, using the definition from above

Functions can also have their own variables.

var addToThree = function(someValue) {
  var three = 3;
  return three + someValue;
}

var five = 5;
var sum = addToThree(5);  // Sum is now 8
three  // There is now 'three' (it's undefined), the variable is hidden inside the function

Functions can also be used by other functions:

var sum = function(a, b) {
  return a + b;
}

var addToThree = function (a) {
  return sum(a, 3);
}

And functions are types like every other and can be passed to other languages as argument - a very elegant thing in JavaScript. Let's look at the forEach function: Like the length property, every array has that function. forEach takes another function as argument and runs that function for each element in the array.

// Let's take the sum of someArray from above again
var sum = 0;
var addToSum = function(a) {
  sum = sum + a;
};

addToSum(2);  // sum is now 2
addToSum(2);  // sum is now 4

sum = 0;
someArray.forEach(addToSum);  // Reads like natural language, right?
// sum is now 49999950000

// This does the same:
sum = 0;
for (var i = 0; i < someArray.length; i = i + 1) {
  addToSum(someArray[i]);
}

addToSum takes one argument a (a number that is added to sum). forEach fills that argument for us. It calls addToSum for every element in the array and passes each element as argument to addToSum.

Because functions are normal types, they can also be used as values in objects:

// Console is actually actually just an object that contains functions
typeof console // Returns "object"
var console = {
  log: function (...) {
    // Print to console
  }
}
console.log('Does this make sense?');

When we define functions inside of objects, we might want to manipulate values that are contained in that object. We can refer to an object from inside by using this:

var someObject = {
  value: 0,
  increment: function () {
    this.value = this.value + 1;
  }
};

// This is the same:
var someObject = { value: 0 };
someObject.increment = function () { 
  someObject.value = someObject.value + 1;
};

Clone this wiki locally