var pi = 3.14; // pi is a Number
var person = "John Doe"; // person is a string
var answer = 'Yes I am!'; // answer is a string
console.log(typeof answer); // string
answer = 10; // answer is now a number
console.log(typeof answer); // number
var a; // a is undefined
globalVariable = 'i am a global variable';
// one statement, many variables
var lastname = "Doe", age = 30, job = "carpenter";
var lastname; console.log(lastname); // still contains "Doe"
function max(x, y) { if (x > y) return x; else return y; };
max.description = 'return the maximum';
console.log(max.description); // 'return the maximum'
console.log(max(1, 2)); // 2
var person = new Object(); person.firstname = "Ami"; person.lastname = "Turgman"; person.age = 37; person.eyescolor = 'brown';
var anotherPerson = { firstname: 'John', lastname: 'Doe' }; anotherPerson.age = 50; // dot notation anotherPerson['eyescolor'] = 'blue'; // key notation
console.log(person, anotherPerson);
var anotherPerson = {
firstname: 'John', lastname: 'Doe', getFullName: function () { return this.firstname + ' ' + this.lastname; } }; console.log(anotherPerson.getFullName()); // John Doe
console.log(anotherPerson.getFullName.call(person));
var a = [], b = new Array(); // both equivalent
a[0] = 0, a[1] = 1, a[3] = 3; console.log(a.join(',')); // 0,1,,3 b.push(1, 'a', null, undefined, true); console.log(b); // [1, "a", null, undefined, true]
function myFunc(a, b) {
console.log(a, b);
}
var result = myFunc(1, 2); // 1 2
console.log(result); // undefined
myFunc('a'); // a undefined
function getAdder(sum) {
sum = sum || 0;
return function (num) {
sum += num;
return sum;
}
}
var adderFunc = getAdder(100);
console.log(adderFunc(1)); // 101
console.log(adderFunc(2)); // 103
console.log(adderFunc(3)); // 106
setTimeout(function(){ console.log('time expired'); }, 100);
function sayHello(name) {
var text = 'hello ' + name; return function () { console.log(text); } } var sayHelloFunc = sayHello('ami'); sayHelloFunc(); // hello ami
function say100() {
// Local variable that ends up within closure
var num = 100;
var logNum = function() { console.log(num); }
num++;
return logNum;
}
var logNumFunc = say100();
logNumFunc(); // 101
function foo(x) {
var tmp = 2; return function (y) { console.log(x.val + y + tmp); } } var obj = { val: 10 }; var bar = foo(obj); // bar is now a closure referencing obj. bar(3); // 15 obj.val = 20; bar(3); // 25
var u = { a: 1, b: 2 };
var v = { a: 3, b: 4 }; console.log(u, v); // {a: 1, b: 2} {a: 3, b: 4} (function (x, y) { var tempA = x.a, tempB = x.b; //local variables x.a = y.a; x.b = y.b; y.a = tempA; y.b = tempB; })(u, v); console.log(u, v); // {a: 3, b: 4} {a: 1, b: 2}
// This works because objects are passed by reference
var externalVar = 'external';
function myFunc() { var myFuncVar = 'myFunc'; function internalFunction() { var internalVar = 'internal'; console.log(externalVar, myFuncVar, internalVar, globalVar); } globalVar = 'global'; internalFunction(); // external myFunc internal global } myFunc(); console.log(globalVar); // global console.log(myFuncVar); // myFuncVar is not defined console.log(internalVar); // internalVar is not defined
function sumAll() {
var total = 0; for (var i = 0; i < arguments.length; i++) total += sumAll.arguments[i]; return total; } console.log(sumAll(1, 2, 3, 4, 5)); // 15
function doWebRequest(options) {
var scheme = options.scheme || 'http'; var port = options.port || 80; var url = scheme + '://' + options.host + ':' + port + options.path; console.log('calling', url); } doWebRequest({ host: 'microsoft.com', path: '/js' }); doWebRequest({ scheme: 'https', port: 441, host: 'microsoft.com', path: '/js' });
// calling http://microsoft.com:80/js // calling https://microsoft.com:441/js
function Person(name, age) {
this.name = name; this.age = age; this.getDetails = function () { return this.name + ', ' + age; }; } var p1 = new Person('ami', 37); var p2 = new Person('guy', 28); console.log(p1.getDetails()); // ami, 37 console.log(p2.getDetails()); // guy, 28
if (time < 10) {
x = "Good morning";
}
else if (time < 20) {
x = "Good day";
}
else {
x = "Good evening";
}
var day = new Date().getDay();
switch (day) {
case 6:
x = "Today is Saturday";
break;
case 0:
x = "Today is Sunday";
break;
default:
x = "Looking forward to the Weekend";
}
var numbers = [1, 2, 3], sum = 0;
for (var i = 0; i < numbers.length; i++) { sum += numbers[i]; } console.log(sum); // 6
var txt = "";
var person = { fname: "John", lname: "Doe", age: 25 };
for (var x in person) {
txt = txt + person[x];
}
console.log(txt); // JohnDoe25
var i = 0, x = 0;
while (i < 5) { x = x + i; i++; }
for (var i = 0; i <= 5; i++) { if (i == 3) continue; console.log(i); // 0, 2, 2, 4, 5 }
for (var i = 0; i <= 5; i++) { if (i == 3) break; console.log(i); // 0, 1, 2 }
function div(x, y) {
try {
if (!x && !y) throw 'please provide x and y';
if (y === 0) throw 'can not divide by 0';
console.log(x/y);
}
catch(err) {
console.log('error:', err);
}
}
div(10, 2); // 5
div(); // error: please provide x and y
div(10, 0); // error: can not divide by 0
function doWorkAndCallMeWhenDone(callback) {
console.log('starting work');
setTimeout(function () {
console.log('work completed, calling callback');
callback();
}, 1000);
}
var onCompleteHandler = function () {
console.log('work is completed, now i can proceed with
my next task');
};
doWorkAndCallMeWhenDone(onCompleteHandler);
function doWorkAndCallMeWhenDone(callback) {
console.log('starting work'); setTimeout(function () { console.log('work completed with error, notifying caller'); callback('some error occurred'); }, 1000); } doWorkAndCallMeWhenDone(function (err, result) { if (err) return console.error('error doing work:', err); console.log('work is completed, now i can proceed with next task'); });
function doWorkAndCallMeWhenDone(callback) {
console.log('starting work'); setTimeout(function () { console.log('work completed successfully, notifying caller'); callback(null, 'some result object'); }, 1000); } doWorkAndCallMeWhenDone(function (err, result) { if (err) return console.error('error doing work:', err); console.log('work is completed with result:', result); });
function async(x, cb) { cb(null, x + 1); } function executeAsyncSequence(cb) { async(0, function (err, res) { async(res, function (err, res) { async(res, function (err, res) { cb(null, res); }); }); }); } executeAsyncSequence(function (err, res) { console.log('result:', res); });
function asyncFun(param, cb) {
if (typeof param == 'function') cb = param;
cb = cb || function () {console.log('completed work');};
// do some async work
cb();
}
asyncFun('some value', function () {console.log('here!');});
asyncFun(function () { console.log('here!'); });
asyncFun();