Multi-paradigm script language
This is the only script language that is supported in all browsers
/*
declared at the beginning of script
global scope
*/
'use strict';
function functionName() {
// code block here
}
/*
declared inside a function
local scope
useful for browser-, client-side
projects and modular code
*/
function functionName() {
'use strict';
// code block here
}
<!-- Recommended way of including JavaScript -->
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
// an empty variable, also called undefined
var foo;
// variable with a string
var foo = 'This is a string';
// variable with a number
var foo = 10;
// boolean
var foo = false;
// Bad
var averylongname;
var p1;
// Good
var aVeryLongName;
var person1;
// true
var foo = true;
// false
var foo = false;
// a pop-up dialogue
alert('This is a message');
// directly onto the page
document.write('This is a message');
// "hidden" message in the console
console.log('This is a message');
// prompt command
prompt('How old are you?');
// prompt command in a variable
var age = prompt('How old are you?');
// using the + to combine strings
var firstName = 'John';
var lastName = 'Doe';
var fullName = firstName + ' ' + lastName;
// using the concat() method
var firstName = 'John ';
var lastName = 'Doe';
var fullName = firstName.concat(lastName);
// output will be:
John Doe
// Single-line comment
/*
Multiple -line
comment
*/
if (10 === '10') { // condition
console.log('foo'); // statement
} else { // condition
console.log('bar'); // statement
}
// Integers
10
3
-15
-989
0
// Scientific notation
5e-6 // Which is .000005
3e+6 // Which is 3000000
2e+2 // Which is 200
// Floating point numbers
4.56
-0.9342
1.5
.26
// ParseInt
parseInt('210');
// Outcome = 210
parseInt('This is 210');
// Outcome = NaN
parseInt('2.10');
// Outcome = 2
// ParseFloat
parseFloat('5.10');
// Outcome = 5.10
// Addition // Multiplication
10 + 5 10 * 5
// Subtraction // Division
10 - 5 10 / 5
var totalScore;
var playerScore1 = 10,
playerScore2 = 5,
playerScore3 = 6,
playerScore4 = 2;
// Addition
totalScore = playerScore1 + playerScore2;
console.log(totalScore);
// Subtraction
totalScore = playerScore4 - playerScore3;
console.log(totalScore);
// Multiplication
totalScore = playerScore3 * playerScore1;
console.log(totalScore);
// Division
totalScore = playerScore1 / playerScore4;
console.log(totalScore);
var yourAge = prompt('What is your Age?'),
myAge = 30,
ourAge = yourAge + myAge;
console.log(ourAge);
var yourAge = prompt('What is your Age?'),
myAge = 30,
ourAge = parseInt(yourAge) + myAge;
console.log(ourAge);
var yourAge = 15,
myAge = yourAge * 2,
ourAge = myAge + yourAge;
console.log(ourAge);
// addition: output = 15 // modulus: output = 2
10 + 5; 12 % 5;
// subtraction: output = 45 // incement
145 - 100; ++
// multiplication: output = 12 // decrement
2 * 6; --
// division: output = 3
12 / 4;
== // equal to
=== // equal value and equal type (recommended)
!= // not equal
!== // not equal value or not equal type (recommended)
> // greater than
< // less than
>= // greater than or equal to
<= // less than or equal to
&& // and
|| // or
! // not
if (condition) {
action = 'do something';
}
else {
action = 'do something else';
}
// can be written as
action = (condition) ? 'do something' : 'do something else';
// Declaring a function
function nameOfFunction () {
}
// Calling the function
nameOfFunction();
// Declaring a function expression
var message = function() {
var askAge = prompt('What is your age?');
alert(askAge);
};
// Calling a function expression
message();
function myFavorite(band) {
alert(band + ' is awesome!');
}
myFavorite('ColdPlay');
function myFavorite(band, serie) {
alert(band + ' & ' + serie + ' are awesome!');
}
myFavorite('ColdPlay', 'Mr. Robot');
// Declaring a function, which then calls itself immediately
// It creates a new scope
(function() {
function foo() {
console.log('Text here');
}
foo();
})();
// Function expression
function foo() {
console.log('foobar');
}
foo();
// Create a function
function functionName() {
// Private variable in functionName scope
var totalDevs = 0;
// An inner function that has access to the private variable
function innerFunction() {
totalDevs++;
console.log('Total devs = ' + totalDevs);
}
return innerFunction;
}
// Create a new private scope every time "functionName" gets called
devCount = functionName();
devCount();
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
var person = {
firstName:"John",
lastName:"Doe",
age:25
};
var text = "";
var x;
for (x in person) {
text += person[x];
}
while (condition) {
// code block to be executed
}
while (i < 10) {
text += 'The number is ' + i;
i++;
}
do {
// code block to be executed
}
while (condition);
do {
text += 'The number is ' + i;
i++;
}
while (i < 10);
var arrayName = [];
var arrayName = ['name1', 'name2', 'name3'];
// If you have a long list
var arrayName = [
'name1',
'name2',
'name3',
'name4',
'name5',
'name6'
];
// Current Array
var arrayName = [22, 23, 24, 25, 26];
// Add data to Array
arrayName.push(27);
// Result
arrayName = [22, 23, 24, 25, 26, 27];
var list = [
[1, 2, 3, 4], // index 0
['Phil', 'Peter', 'Mitchell'], // index 1
[true, false] // index 2
];
var developers = [
'Phil',
'Joe',
'Ryan',
'David',
'Carla'
];
for( var i = 0; i < developers.length; i += 1) {
console.log(developers[i]);
}
var developers = [
'Phil',
'Joe',
'Ryan',
'David',
'Carla'
];
function printDevelopers(list){
for( var i = 0; i < list.length; i++ ) {
console.log(list[i]);
}
}
printDevelopers(developers);
var developers = [
'Phil',
'Joe',
'Ryan'
];
var designers = [
'Jeroen',
'Kathy',
'Billy'
];
developers.concat(designers);
// Output would be:
[
'Phil',
'Joe',
'Ryan',
'Jeroen',
'Kathy',
'Billy'
];
// Object literal
var objectName = {};
var developer = {
name: 'John',
age: 30,
hobbies: ['Coding', 'Gaming']
};
var person = {
firstName: 'Klaas',
lastName: 'Jansen',
age: 30,
job: 'Software developer'
};
var person = {
firstName: 'Klaas',
lastName: 'Jansen'
age: 30,
job: 'Software developer',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
var person = {
name: 'John Doe',
age: 30,
profession: 'developer',
hobbies: ['Coding', 'Gaming'],
single: true
};
// Option 1: Using the properties name as string
person['name']
person['age']
// Option 2: Dot notation (more common!)
person.name
person.age
var person = {}
person.firstName = 'Klaas';
person.lastName = 'Jansen';
person.age = '30';
person.job = 'Software developer';
person.fullName = function() {
return this.firstName + ' ' + this.lastName;
};
var person = {
firstName: 'Klaas',
lastName: 'Jansen'
age: 30,
job: 'Software developer',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
var person = new Object();
person.firstName = 'Klaas';
person.lastName = 'Jansen';
person.age = '30';
person.job = 'Software developer';
person.fullName = function() {
return this.firstName + ' ' + this.lastName;
};
function Person(firstName, lastName, age, job) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.job = job;
this.fullName = function() {
return this.firstName + ' ' + this.lastName;
};
}
// Creating a new instance with the "new" keyword
var developer1 = new Person('Klaas', 'Jansen', 30, 'Software developer');
var developer2 = new Person('Timo', 'de Jong', 18, 'Front-end developer');
var person = {
name: 'John Doe',
age: 30,
profession: 'developer',
hobbies: ['Coding', 'Gaming'],
single: true
};
person.name = 'Jane Doe';
person.age = 28;
person.email = 'jane.doe@mail.com';
console.log(person);
var person = {
name: 'John Doe',
age: 30,
profession: 'developer',
hobbies: ['Coding', 'Gaming'],
single: true
};
// Gives you access to the properties
for (var item in person) {
console.log(item);
}
// Give you full access to all data in Object
for (var item in person) {
console.log(item, ':', person[item]);
}
var developers = [
{
name: 'John',
age: 20,
skills: ['HTML', 'CSS', 'JavaScript']
},
{
name: 'Jane',
age: 25,
skills: ['Java', 'PHP', 'AngularJS']
}
];
// An array with an object
var developers = [
{
name: 'John',
age: 20,
skills: ['HTML', 'CSS', 'JavaScript']
},
{
name: 'Jane',
age: 25,
skills: ['Java', 'PHP', 'AngularJS']
}
];
// Looping through with a for loop
for( var i = 0; i < developers.length; i += 1) {
console.log(developers[i].name + ' is ' + developers[i].age + ' years old');
}
document
<html>
<head>
<body>
<title>
<link>
<h1>
<p>
<strong>
lorem ipsum
lorem ipsum
lorem ipsum
document
element
text
By accessing element nodes you can reach attribute and text nodes
It's possible to select an individual and multiple element nodes or moving an element node to a related node
// methods returning a single node
document.getElementById('id');
document.querySelector('css selector');
// methods returning a nodelist
document.getElementsByClassName('class');
document.getElementsByTagName('tagName');
document.querySelectorAll('css selector');
// creating a new element, a text node attach them
var newElement = document.createElement('<p>'),
newContent = document.createTextNode('Hi all');
newElement.appendChild(newContent);
// place them into its position
var positionElement = document.getElementsByTagName('div')[0];
positionElement.appendChild(newElement);
// getting value of an attribute
var foo = document.getAttribute();
// check if element has an attribute
var foo = document.hasAttribute();
// set value
var foo = document.setAttribute();
// remote attribute
var foo = document.removeAttribute();
// example: find an element and get value of attribute
var foo = document.getElementById('bar').getAttribute('class');
// retrieve or amend the content of a text node with nodeValue
var foo = document.getElementById('bar').firstChild.nodeValue = 'Hi all';
// collect or update text in the containing element with textContent
var foo = document.getElementById('bar').textContent = 'Hi all';
// access or amend content of an element incl. it's children
var foo = document.getElementById('bar').innerHTML = 'Hi all';
var size = 50 + 20;
document.write(size);
function size(height, width) {
var size = height + width;
return size;
}
SyntaxError: Unexpected EOF
ReferenceError: Can't find variable: variableName
TypeError: 'null' is not an object
RangeError: Array size is not a small enough positive integer
URIError: URI error