What is a difference between a function expression and a function declaration
function fdecl() { return -1; } var fexpr = function() { return -1; };
Context and this keyword
var Obj = { field: 1, func: function() { return this.field; } }; console.log(Obj.func() === 1); // this is Obj var f = Obj.func; console.log(f() === undefined); // this is Window var solution = Obj.func.bind(Obj); console.log(solution() === 1); // this is Obj
Bind shim and currying
Function.prototype.bind = Function.prototype.bind || function(context) { var self = this; return function(){ return self.apply(context, Array.prototype.slice.call(arguments)); }; } Function.prototype.curry = function() { var self = this; var oldargs = Array.prototype.slice.call(arguments); return function() { var newargs = Array.prototype.slice.call(arguments); return self.apply(this, oldargs.concat(newargs)); }; }
Make a function that add a space between each character in a string
function spacify(str) { return str.split('').join(' '); } spacify('hello world');
For "inline" syntax:
String.prototype.spacify = function(){ return this.split('').join(' '); }; 'hello world'.spacify();
Palindrome check function
function isPalindrome(str) { str = str.replace(/\W/g, '').toLowerCase(); return str == str.split('').reverse().join(''); }
Example of usage:
console.log(isPalindrome("level")); // logs 'true' console.log(isPalindrome("levels")); // logs 'false' console.log(isPalindrome("A car, a man, a maraca")); // logs 'true'
use strict
-
Prevents accidental globals. For example
function() { var a = b = 1; }
fail becauseb
is global... -
Disallows duplicate property names or parameter value, like
{foo: "bar", foo: "baz"}
. -
Throws error on
delete
on non-configurable properties of the object.
Implicit semicolon
Each operator ended with implicit semicolon. So this is:
function() { return 1 }
equals to:
function() { return; 1; }
null vs undefined
undefined
appear in cases:
-
Lookups of non-existent properties in an object.
-
Function parameters that have not passed.
-
A variable is declared without assigning any value to it.
-
Implicit returns of functions because of missing return statements.
-
Return statements that do not explicitly return anything.
-
Anything that has been set to the value
undefined
. -
Any expression in the form of
void(expression)
. -
The value of the global variable
undefined
.
Except for cases of lookup of non-existent properties in object and missing parameters in function
call encountering undefined
usually represents an error in code.
On other hand null
represents "missing value" semantic by desing.
== vs ===
==
performed with type conversion of operands. ===
performed with respect of type of both
operands.
Find max value in array
Math.max.apply(null, arr);