Posts Tagged ‘Prototype’

How to concatenate all arguments to a function in JavaScript?

Array’s have a join() method used for joining arrays that contain strings, but this can’t be used with function arguments, which are array-like, but are not actual arrays. Instead we can defer to the Array prototypes join function:   function concatenate() { return,""); }   var s = concatenate("a","b","c"); (s === "abc"); // true

How to find the last character of a string in JavaScript?

Using a simple function: function lastChar(s) { return s.charAt( s.length – 1 ); }   ( lastChar("hello") === "o" ); ( lastChar("h") === "h" ); ( lastChar("") === "" ); Augmenting the string prototype: String.prototype.lastChar = function() { return this.charAt( this.length – 1 ); }   ( "hello".lastChar() === "o" ); ( "h".lastChar() === "h" [...]

How to find the first character of a string in JavaScript?

1. Using an index We treat a string like an array of characters. s = "Hello World"; console.log( s[0] == "H" ); // true Note from Mozilla String documentation that this method “is not part of ECMAScript; it’s a JavaScript feature (and not supported in all browsers).” 2. Using charAt() Use the built in charAt() [...]

How to delete a property from an object in JavaScript?

We can use the delete operator to delete properties from objects. // Create a new empty object var o = {}; console.log( typeof == "undefined" );   // Add a name property = "Foo"; console.log( typeof == "string" );   // Delete the name property delete; console.log( typeof == "undefined" [...]

How to create a public method in JavaScript?

Public methods are assigned to the prototype property of the objects. function User(name) { this.type = "admin"; = name; }   User.prototype.getName = function() { return; } User.prototype.getType = function() { return this.type; }   var u = new User("Spock"); (u.getType() == "admin"); // true (u.getName() == "Spock"); // true

How to convert JavaScript function arguments into a real array?

JavaScript function arrays have array-like behaviour but are not real arrays. For example, we cannot iterate through function arguments using a for-in loop. To convert function arguments to a real array we can use the Array prototype slice() function. var args =; For example: function sum() { var args =; var total = [...]