Cool JavaScript stuff I learned at the Open TechSchool workshop

If you are not aware of Open TechSchool, it is a community initiative offering free programming workshops to technology enthousiasts and is located in cities all around the globe.

Today and yesterday I participated at the workshop "Javascript for Absolute Beginners" of Open Techschool in Dortmund, and I would like to share with you what I learned.


JavaScript cheat sheet

In this cheat sheet you can find basic tips about the syntax of Javascript.

Array definition

Arrays may not have keys like in php, they only have indexes. If you want to have keys, create an object. An array is defined using square braces:

var myArray = [1, 2, 3];

Object definition

You can define an object like this:

var myObject = { 
    myProperty: "myValue",
    myMethod: function() { }
}

Object properties

Object’s properties can be accessed in two ways:

myObject.myProperty;
myObject["myPropery"];

The second line allows get the property in a dynamic way, by providing a string for the property's name.

Functions are objects

Yes, functions are objects. You can define functions inside them which is cool!

About the "var"

When defining a variable inside a function without a "var" in front, this variable is defined in the global scope. Scary!

You can override a global variable by defining a local one inside a function:

var a = 'a';
var b = 'b';

function doSomething() {
    
    var b = 'B';
  
    console.log(a); // prints a
    console.log(b); // prints B
}

DOM elements

You can get a DOM element by its id like this:

var photos = document.getElementById("photos");

We can change the html inside an element by setting the innerHTML parameter:

photos.innerHTML = "<p>No photos available yet!</p>";

Some DOM element properties like "offsetLeft" are read only, while others like "innerHTML" are writeable.

Small functions

To protect the global namespace from being polluted while writing small scripts, you can add your code inside an anonymous function, and call it right after:

(function () {

    // do stuff
})();

Style guide

It is a good rule of thumb write the opening curly brace of a function in the first line of the function's definition:

function amazeMe () {

    // do some stuff
}

The book

In today's lottery, I was the lucky one to win this book! So it's time to learn more about JavaScript and finally improve my german! A big thanks to Open TechSchool for this! If you want to do the workshop from home, the material is free and shared here.

Conclusion

As a PHP developer learning JavaScript, I was very happy having someone to answer those silly questions I had. I want to say a big thanks to all the coaches and everyone else volunteering for this nice event. Cu next time!