- Function Declariation
function whatDoyouDo(job, firstName)
{
}
whatDoyouDo('teacher',John);
- function expression
var whatDoyouDo = function(job, firstName)
{
};
whatDoyouDo('teacher',John);
2. Array
- Initialise new array
var names = ['John', 'Mike', 'Jane'];
var years = new Array(1990,1969,1948);
- Length of array
console.log(years.length);
- Mutate array data
names[1] = 'Ben';
names[names.length] = 'Mary';
names[8] = 'Kim';
- Different data types
var john = ['John', 1999, 'happy', false];
- Method
john.push('bule');
john.unshift('Mr');
john.pop();
john.indexOf(1999);
3. Objects
- Difference between Array and Objects: Array has order but objects don't.
- Initialise new Object
var john = {
firstName: 'John',
lastName: 'Smith',
birthYear: 1990,
family: ['Jame', 'mark', 'Bob', 'Emily'],
job: 'teacher',
isMarried: false
};
var jane = new Object();
jane.name = 'Jane';
jane.birthYear = 1998;
jane['lastName'] = 'Smith';
- Method
var john = {
firstName: 'John',
lastName: 'Smith',
birthYear: 1990,
family: ['Jame', 'mark', 'Bob', 'Emily'],
job: 'teacher',
isMarried: false,
calAge: function()
{
this.age = 2019 - this.birthYear;
}
};
john.calAge();
console.log(john);
4. Hoisting
- Declaration works with variables and functions
num+=6;
var num;
calculateAge(1997);
function calculateAge(year)
{
console.log(2019-year);
}
- Expression works fine with variables but does NOT work with functions
num+=6;
var num = 0;
calculateAge(1997);
var calculateAge = function (year)
{
console.log(2019-year);
}
5. Scoping
var a = 'Hello!';
first();
function first() {
var b = 'Hi!';
second();
function second() {
var c = 'Hey!';
console.log(a + b + c);
}
}
var a = 'Hello!';
first();
function first() {
var b = 'Hi!';
second();
function second() {
var c = 'Hey!';
third();
}
}
function third() {
var d = 'John';
console.log(a + b + c + d);
}