Introduction to Javascript
/**
* Created by Gil Álvaro on 21/08/15.
*/
//Javascript
(function() {
// Single line of comment
/*
Multiple lines of comments
*/
//debugging
console.log('xD');
//Alerts
alert('Hello World!');
//Variables
var theVar; // == undefined
//avoid to set global variable
var oneVar = 42, // Assigned 42 to the var
secondVar = 22; // Assigned 22 to the secondVar (no need to add var)
theVar = 'Name';
theVar = oneVar; //overwriting
//DATA TYPES
/*
NUMBER -> If is not Octal, Exponential or Haxadecimal get Infinity or NaN (Not a Number) it can be cheched with isNan()
STRING -> Sequence of characters within single or double quotes, can nest quotes inside quotes but must match
To joind strings we use + sign like 'wait, ' + 'for'
BOOLEAN
Falsey values
-false
-0
-''
-null
-undefined
-NaN
Truely values
All others
UNDEFINED
NULL
*/
//ARRAYS
var myArray = [5,'something',true];
//access array
console.log( myArray[0] );
// OBEJCTS ARRAYS
var myObject = {
myNumber: 10,
myString: 'Woooho!'
};
var string = 'hello';
var stringObject = new String('An object string');
//access Object Array
console.log(myObject.myNumber); //10
console.log(myObject['myString']); //'Woooho!'
// incrementing
secondVar += 1;
//decrementing
secondVar -= 1;
//multiplication
secondVar *= 2;
//division
secondVar /= 2;
//Rest
secondVar %= 1;
//Comparison -> avoid non strict comparisons
1 == true; //non strict comparison = true
1 === true; //sctrict comparison = false
//Unary Operators
+true;
-true;
typeof true;
//Logical Operators
(1 && 2);
(true || false);
//Operator precedence
3 + 4 * 5; //returns 23
// FUNCTTIONS
function myFunction(){
console.log("This is a Function!!");
}
function getThingByColour(colour) {
var things = {
red: 'a red thing',
green: 'a green thing',
blue: 'a blue thing'
};
return things[colour] || 'Sorry, no thing of that colour exists';
}
//Run automaticly when the code is loaded
(function invokeImmediately() {
console.log('invoked automatically');
}());
!function alsoInvokedAutomatically() {
console.log('invoked automatically too');
}();
//SCOPE
//Global Vars
var global = 1;
function aFunction() {
var local = 2;
console.log(global);
console.log(local);
console.log(window.location.href);
}
//This
//usually an Object
//Strict Mode affect this
(function () {
'use strict';
console.log(this);
var object = {
property: 'I belong to this',
method: function () {
return this.property;
}
}
console.log(object.method());
function Person(name) {
this.name = name;
}
var bob = new Person('Bob');
console.log(bob.name);
}());
})();
<!DOCTYPE html>
<html>
<script src="intro.js" ></script>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>