var pi = 3.14; // pi is a Number
var person = "John Doe"; // person is a string
var answer = 'Yes I am!'; // Different quotes, answer is a
//string as well
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"
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";
}
if (a) - will evaluate to true if (a) isn't undefined, null, or NOT false.
if (a === false)
(a === b) - makes sure that a and b are of the same type. Will return false immediately if a and b aren't of the same type. Have better performance then ==.
a = a || 'hello'; // leave a as is, or set it to 'hello' if it
// evaluates to false
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 }
var numbers = [1, 2, 3], sum = 0;
numbers.forEach(function(item) {
sum += item;
}); console.log(sum); // 6
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
var person = new Object(); // can also be: var person= {}; 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);
delete person.age;
console.log(person.age); // will print 'undefined'
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'); // b 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 getName() {
return this.name;
} var o = {name : 'Nadav'};
o.getName = getName;
o.getName(); // returns Nadav;
getName(); // hmmm? - this == global
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 + ', ' + this.age; }; } var p1 = new Person('nadav', 29); var p2 = new Person('guy', 28); console.log(p1.getDetails()); // nadav, 37 console.log(p2.getDetails()); // guy, 28
function Person(name, age) {
if (!(this instanceof Person)) {
return new Person(name,age);
}
//...
}
var p1 = Person('nadav', 29); // equivalent to new Person
function Person(name, age) {
//...
}
// function will be "shared" among instances
Person.prototype.getDetails = function {
return this.name + ',' + this.age;
}
function Person(name, age, profession) {
//...
}
Person.prototype.getDetails = function() {...};
function Developer(name, age, lang) {
Person.call(this, name, age, 'developer');
this.lang = lang;
}
Developer.prototype = new Person();
var d = new Developer('Nadav', 29, 'JavaScript');
function func(b) = { return this.a + b;}
var o = {a : 1}
func.apply(o, [3]); // will return 4
func.call(o, [3]); // will also return 4
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// Create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
var o = {}; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, 'a', {
value: 37,
writable: true,
enumerable: true,
configurable: true
});
// Example of an object property added with defineProperty with an
// accessor property descriptor
var o = {}; var bValue = 38; Object.defineProperty(o, 'b', { get: function() { return bValue; }, set: function(newValue) { bValue = newValue; }, enumerable: true, configurable: true }); o.b; // 38
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();