There is no official JavaScript documentation; it's important to note that what we colloquially refer to as JavaScript is really called ECMAScript.
Mozilla has excellent documentation of its brand of ECMAScript, JavaScript, at Mozilla Developer Center: https://developer.mozilla.org/en/javascript
You can read Microsoft's documentation of their brand of ECMAScript, JScript, here: http://msdn.microsoft.com/en-us/library/yek4tbz0(VS.85).aspx
Welcome to closures. Once you understand this you will be much more productive in Javascript.
The way you are doing it, all your click handlers are sharing the same variable 'i' with the same scope. So by the time you get around to executing any of those click handlers, they all look up the value of i, and of course it's the last value it was set to.
Solution: create a function that returns the function you want, with a value that is captured in its own private scope. This is a closure.
function makeLinkRevealer(x) {
return function() {
$('.divs').hide();
$('#' + links[x] + '_div').show();
};
}
for(i in links) { $('#' + links[i] + '_link').click( makeLinkRevealer(i) ); }
You can even create that function-returning function inline. The pattern looks like
function(x){ return function() { ... code that uses the value of x ... }; }(i)
You see what's happening? the function(x) { } (i) will, within the scope of {}, bind x to whatever i is at that moment. But because we return a function that uses x, we can say that x is "closed over", and the function reference is itself a "closure".
>Do I understand you right? You're saying that function scope is a "fundamental issue" that "no one wants" and was "fixed" by let? Is that a joke?
Block scope is a super set of function scope. The body of a function happens to be a block. There can be also many other blocks inside.
Once let
is supported, there won't be any reason whatsoever to use var
. (FWIW, Crockford agrees with this.)
>do you really think block scope is the most important of all "New in JavaScript 1.7"?
Yes, it makes your code a bit nicer and it's also something you'd use dozens of times each and every day.
Edit: Read this: https://developer.mozilla.org/en/JavaScript/Reference/Statements/let
Read all the chapters here. This is all you need to become very proficient in JS.
https://developer.mozilla.org/en/JavaScript/Guide
After this you can start checking out design patterns. I am very proficient in JS and wish I started this path.
The WRONG thing to do is to start with jQuery right away. Don't do that.
Here you go
http://eloquentjavascript.net/ (I would recommend this as it is clear, concise and easy to understand, also there is an interactive environment for you to play around)
https://developer.mozilla.org/en/JavaScript/Guide (This is more like a reference guide, than a tutorial)
When you are finished reading those two, have a look at this http://bonsaiden.github.com/JavaScript-Garden/
I recommend Mozilla Developer Network's JavaScript Reference - https://developer.mozilla.org/en/JavaScript (It's a HTML Version Tutorial).
Also, These are must watch JavaScript Videos from Crockford - http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/
Hope this helps! :)
Many of these problems can be fixed in new versions of Javascript, e.g. the "use strict;" mode in the ES5 version.
Ditto with new data structures. Mozilla have created more efficient array types.
Global scope is probably the most difficult to fix because of a huge NIH syndrome.
You want toFixed. Keep in mind that all numbers in JavaScript are floating-point numbers. They don't lose or gain precision. So to show a number at a certain precision means you have to format it as a string (which is what toFixed
does).
(3.14159).toFixed(); "3" (3.14159).toFixed(0); "3" (3.14159).toFixed(1); "3.1" (3.14159).toFixed(2); "3.14"
W3Schools isn't terrible as a basic introduction to HTML, though IIRC it's a bit outdated and doesn't cover semantic markup at all (though you could probably argue that's a more advanced topic). The real problem with W3Schools and the reason so many of us get upset when it's mentioned is its Javascript documentation -- not only does it not teach good practices, it actually teaches you some of the worst practices out there. The last thing we need is more people out there writing terrible Javascript.
Mozilla Developer Network is probably the definitive place for everything Javascript, but it's more of a reference than a proper tutorial. For an introduction to the language itself, I'd recommend Javascript: The Good Parts.
> it works in 100% of cases in this framework.
It's for when you add other frameworks. They might use the second parameter of indexOf().
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
EDIT: Considering this is a game framework, my criticism is a little harsh.
Some languages (JS in particular) benefit from vastly simpler regular expression implementations.
Compare the perlre man page: http://perldoc.perl.org/perlre.html
vs this one documenting Javascript regexps: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
Here are some remarks:
e.g.:
var j = new List(); alert(j.hasKey("toString"));
at line 257:
if (typeof(obj[entry]) === 'string' || 'number')
with:
if (typeof(obj[entry]) === 'string' || typeof(obj[entry]) === 'number')
e.g.:
if (typeof(obj[entry]) [...])
should be written
if (typeof obj[entry] [...])
at line 260:
copied[entry] = (typeof(obj[entry])) ? true : false;
did you mean ?
copied[entry] = obj[entry];
[...] clear: function () { this.table = {}; }
It has but most browsers haven't implemented the changes, if you want the newer mozilla spec stuff check here. As far as I know its only supported by Firefox, but I have no idea about chrome/opera/safari. Pretty certain ie doesn't support anything fancy.
Note: Java and JavaScript are completely different languages. Codecademy uses JavaScript, not Java.
i=i-1
and i=i--
are certainly not the same thing. There are some interesting things at play here, especially since you are assigning the same variable that you are decrementing. If you take a look at the [MDN site](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#--_(Decrement\)) they detail the implementation of the postfix decrement operator:
>If used postfix (for example, x--), then it returns the value before decrementing.
So in the statement, the order of operations looks something like this:
i--
returns the current value of i
, such as 10
.i--
then performs the decrement, setting i
to 9
.i = 10
left to evaluate. Obviously, this sets i
back to its original value.But really, just don't decrement and assign to the same variable. If you REALLY want to, use the prefix operator (--i
) as opposed to the postfix one (i--
).
I think you're being downvoted for linking to w3schools[0], better use MDN for references. Otherwise, I'd give the same advice :)
I can tell you have invested a bit of time into this, it would be really nice if you could put together a nicely formatted readme which documents how to use your library.
You might also consider packaging your library into a global name spaced object. So that one might be able to call
solarCalculator.findRecentSunrise(jd, latitude, longitude)
Also it looks like you have a lot of code here just to handle dates, javascript has a native Date() format. I suspect you will be much happier using it.
One thing that will invariably bite you in the ass when you first start experimenting with a lot of array.map:
Array.map on MDC > callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.
So you're out there having fun mapping and reducing and then one day you pass a variadic function to map (with optional arguments for example) and then wonder what the hell is going on.
Luckily this might lead you to ask yourself "but then how can i sink arguments?" and push you towards even more fun stuff to do with functions.
If you're able to use jQuery, you probably already know the Javascript basics, since the vast majority of the things you use jQuery for are DOM manipulation, XMLHttpRequests and minor convenience things (.each() for example).
The basics of Javascript are pretty much the same as any other C-like language. For that, I would highly recommend the Mozilla Developer Network's Javascript docs.
In JavaScript, the value of this
is determined when you enter a function, by the code calling it — in an event handler, this
will be the element which triggered the event (c
). The usual answer is to create a variable in the function which is called with the this
you want, and use it:
function optionBox(objname){ var self = this; … c.addEventListener('touchend', function(){ self.close(); }, false); }
(Name the variable whatever you want, "self" is just my go-to choice.) Another option is to bind the handler to the this
you want. Some frameworks have utilities which do this (e.g. <code>_.bind()</code>), and it's built into newer browsers as <em>function</em><code>.bind()</code>.
A couple of other notes:
Declare obj
as a variable, or it will be set globally:
obj = document.getElementById(objname);
Make sure you call optionBox
with new
, or this
will be the global object (you may already be doing this):
new optionBox(objname)
Constructors like this (which are called with new
and create new objects) are traditionally capitalized (OptionBox
).
When in doubt, MDN:
https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Variable_scope
Also, be sure to use the var
keyword whenever you declare a variable. Always. The only exception is when you explicitly want to attach a variable to the global window object, and even then you should be assigning it like window.myGlobalVar = ...
I found http://eloquentjavascript.net/ to be a good lecture.... and you should be familiar with jQuery
Edit: oh and the mozilla guide
Look through the resources linked on MDN.
Also, look at MDN's JavaScript Reference for details on various constructs.
Get in the habit of looking things up on MDN, for example: <code>indexOf</code>. Note that there are two different <code>indexOf</code> methods, but since you're invoking it on a string object, it should be clear which one to look at.
this
will be set to the object that generated the event, in this case the anchor. Returning false from an event handler prevents the default action from happening. In the case of a link that's been clicked, if you want it to go somewhere other than where it would normally go then you need to prevent that default behavior by returning false, otherwise as soon as the function returns the default handler will run which will navigate to the value of the href attribute.
Your text turned blue because in markdown, you indicate a second level heading by drawing a line with dashes on the next line after the heading. Also, JavaScript != Java.
Thanks for responding! Great to be able to speak to yourselves directly.
I wasn't aware MDN was a wiki and community driven however makes perfect sense.
My initial idea which could help would be to create something similar to https://developer.mozilla.org/en/JavaScript/Guide with a nice hierarchy focused around "How To" posts. If the common answers on sites like StackOverflow could link directly to the content then it would help MDN and as such the entire Javascript eco-system. In theory anyway.
Well if you looking for online documentation the web is full of tutorials. If you prefer to learn by video I would suggest Pluralsight. They have some great tutorials on Javascript and Jquery. You could try the free trial. Additionally Mozilla has the best Javascript reference I have found https://developer.mozilla.org/en/JavaScript
Web Developer here. I use the Mozilla Developer Network every day, all day for my javascript needs.
I don't know how many true tutorials they have, but their docs are pretty comprehensive and usually include examples.
A lot of those are being fixed. Strict mode turns accidentally manipulating the global scope into an error (among other things). The let statement introduces block (or even expression) scope and should show up in browsers other than Firefox whenever they implement Harmony.
Binding this
is easy. JS 1.8.5 provides Function.prototype.bind which creates a portable closure around your function with this
bound to a value of your choice. No need for extra variables like me
or the more common that
. Libraries like Prototype provide a polyfill, and if you feel like writing it yourself it's just
Function.prototype.bind = function bind(ctx) { var fn = this; return function bound() { return fn.apply(ctx, arguments); }; };
Javascript does have issues that most of us would do differently given the chance, but this is a design decision. It enables powerful techniques like method borrowing which don't exist in more static languages. It's too bad you don't like it but for a thoughtful person like yourself it's possible to use it to your advantage.
This is the most uninformed drivel on javascript I've ever read.
A correct summary:
"""
Javascript sucked a long time ago. It defaulted to global variables, and requires "var" to pin variables to local (function) scope. It is now "fixed" in modern browsers when you "use strict"; but not all browsers treat it as a syntax error. https://developer.mozilla.org/en/JavaScript/Strict_mode#Converting_mistakes_into_errors
"""
If you want to talk about magic bullcrap in javascript (not what he's talking about), try:
function foo() { var a = 1; try { return 2; } finally { var c = 3; } }
...as well documented here: http://geekswithblogs.net/FrostRed/archive/2008/11/29/127440.aspx
--Robert
It's javascript.
If you know nothing you'll want to go over syntactical differences between that and a language you do know.
After that you'll want to know that mozilla has the best javascript reference for firefox.
Document Object Model - interacting with the page.
And for future reference there are better places for questions like this than compsci.
here you have a great introduction on Mozilla developer center: https://developer.mozilla.org/en/A_re-introduction_to_JavaScript then you can move on to their guide, for more in depth explanations: https://developer.mozilla.org/en/JavaScript/Guide
Also, Eloquent javascript is a really well written and fun book to learn from: http://eloquentjavascript.net/ the online version has an interactive console, so you can play and experiment with code snippets along your reading.
Happy JS learning! ;)
I think the answer in this thread makes things far clearer. Also, __proto__ is deprecated in favor of getPrototypeOf.
Yes, all Number methods work on number literals. There just aren't very many of them.
MAX_VALUE is a static variable (a property on the constructor). Instances don't have it. You can, however do things like:
(10000).toExponential(); // "1e+4" (10000).toLocaleString(); // "10,000" (10000).toFixed(10); // "10000.0000000000"
I never looked these up, some of them are useful :)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number
Can you get it working in a browser other than Chrome? Safari 5 errors out pretty early because Safari doesn't implement Function#bind
yet. (Test for its existence and if it's not there, use this version.)
EDIT: A nitpick:
if (initFn == undefined) {
This line is nearly useless, by which i mean it's almost equivalent to saying if (initfn)
. undefined == null
is true
, so all you're doing is checking that the value is falsy, and there are more concise ways to do the same thing. Also, undefined
isn't a named value in JavaScript the way null
is, so you probably want this line to read if (typeof initFn === "undefined")
.
EDIT 2: Your JavaScript isn't getting served as UTF-8, so the up and down arrow glyphs you're using in the source code look like this.
> and I have to hard code every single one. I can't even imagine how to make an object and then an array full of them!
This is where Classes come in very useful!
Javascript doesn't come with Classes, a very useful code structure, but you can simulate it with this 25-line code snippet from the freaking creator of jQuery himself.
That way, you can do something like
var Enemy = Class.extend({ init: function(){ this.kickAss(); this.chewGum(); }, kickAss: function(){ ... }, chewGum: function(){ ... } }); var enemies = [ new Enemy(), new Enemy(), new Enemy(), ... ];
Learning this is the moment Javascript "clicked" for me. If you want to learn more, read up on prototypical inheritance. It's better than classical inheritance, and with it I've been able to implement multiple inheritance, which most OOP languages can't even do!
P.S: For drawing shtuff, let a library such as CreateJS handle it. Not only is CreateJS easy-to-use, performant, and powerful, but it even got acquired by Adobe. Adobe! Because if anyone's going to "kill" Flash it's going to be themselves.
Edit: Formatting
Javascript only deals with 16 bit code units. It does not deal with 32 bit characters well. To get those, you have to encode two separate 16 bit code units in the string. Basically, you have to encode the string in UTF-16 (or use two \uXXXX\uXXXX escape sequences).
Edit: MDN's documentation shows how to do this with string.fromCharCode(). See the example function fixedFromCharCode().
You can use <code>defineProperty()</code> or <code>Object.create()</code> and set enumerable
to false, but these are ES5 features and won't work everywhere (e.g. IE < 9, Fx < 4).
Also, it's not really hidden. ES5 also gives <code>getOwnPropertyNames()</code> which will return a list of all own properties, even those that are non-enumerable.
Random code tips:
Avoid passing set/clearTimeout a string
Use array literals syntax, look how these arrays are defined
Edit: And use var!!
Also, reserved words need quotes.
// invalid var foo = { default : 2 } // valid var foo = { 'default' : 2 }
The official jQuery docs are pretty good. Just keep a tab open. For JavaScript, MDN is my favorite resource. Also try hanging out in #javascript on freenode and maybe #jquery too.
I'm not sure. One possibility is to go via the HTML wrapping String method 'link', but that requires a 'k' which I'm not sure if we can reach. If 'k' is reachable, we have the following solution:
> ([][[]]+[])["link"]()[3] 'h'
What strings do we know are reachable for sure? These are the ones I can remember off the top of my head: 'undefined', 'NaN', 'false', 'true', 'Infinity', '[object Object]', 'function filter() { [native code ] }' (not sure on the last one, but I remember that some array method is reachable at least).
There are a few small errors in your code and one large one.
The big one first:
You never set the DIVs height after you calculate a new one with "d+=125;"! Presumably you want something like:
$("#test1").height(d);
...at the end of the function someplace.
Now, the small things:
parseFloat() doesn't accept a second argument (the radix) - that is only for parseInt(). See here.
You should just hook the buttons directly instead of grabbing every single input element on the page. The way you have it written, every input element on the page will trigger this function every time the input is clicked on. You could just do $("#large,#small")... and it would be much faster and more specific.
Finally, without the actual HTML or an example of similar HTML showing the same issue, we can't be sure that there isn't a nice simple CSS solution to your problem. You may want to post a bit more of an example at http://jsfiddle.net/ if you still need more help.
I have a request for a site to remove: W3Schools. It's really nowhere near the best reference.
https://developer.mozilla.org/en/JavaScript for Javascript is a much more accurate and clearer guide.
See w3fools for more.
A lot of those things are already fixed by strict mode. This exists today, in plenty of released browser versions: Fx >= 4, Safari >= 5.1, Chrome >= 13, Opera >= 12. There's no IE support though.
This uses the incredibly handsome and useful Array.filter function. I haven't tested it, use at your own risk.
function countBlogEntries() { var ul = document.getElementById('blog-entries'), lis = ul.getElementsByTagName('li');
return lis.filter(function(el) { return el.parentNode === ul; }).length; }
And for compatibility with IE8 & below, include:
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
(workaround code from MDN. Horrible use of hoisted vars abound. Always be wrappin' this code in a closure.)
Let's take forEach that work in all modern browsers https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach
if you try this code [1, 2 ,3, 4].forEach(alert); on every modern browser it will loop and alert: 1 then 2 then 3 then 4.
forEach is cool and is used for loop through arrays, unfortunately forEach will not work in older browsers like Internet Explorer 6 or 7 or 8.
That is why underscore.js is used.
The same code in underscore will be:
_.each([1, 2, 3, 4], function(num){ alert(num); });
And it will work in older browsers.
The purpose of underscore.js is to bring cool stuff from modern browsers into older browsers.
underscore.js also provides some utility functions like template, chaining and other cools stuff.
>Why? We're seeking DOM nodes with a specific property set. There's no going up the prototype chain here. Either the developer wants the DOM node targetted or they don't.
The OP didn't explain it fully. hasOwnProperty is required if they're using a library that pollutes the namespace (like Prototype does/used to do) or if they have polluted the namespace themselves. Otherwise the loop iterates over every property that the object has inherited through the prototype chain. In this case it would be the properties of the Array object.
What this means is that in some cases Tags[Idx] will return undefined, which means that you will get an error
when you try to access the attributes property.
Also I think you meant: for(Idx in Tags)
and not: foreach(Idx in Tags)
Typically for arrays I use the traditional for-loop syntax since it has a known length, and I don't have to use the hasOwnProperty test either. More information.
You might be able to use generators for this. If you've been playing with Python, you might know what they are. I think Firefox is the only browser that implements them, but I haven't researched them in a year or so.
https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators
|| is a logical operator, not a comparison operator like == or !=. A comparison operator returns a boolean, however a logical operator returns the proper expression based on the operator.
So in this case, if domain could be evaluated as true, then domain is returned (it 'short circuits'), because true || anything is always true. If it could be evaluated as false, then it returns the other expression, "www.reddit.com". This works in an if statement understands all of this, since defined, non-empty variables are considered "true".
You can see more Logical Operators.
Mozilla's JS engine, introduced in JS 1.7 with the feature Destructuring Assignment, which was implemented for parity with the dead ES4. As far as I know, this feature was proposed by Jeff Dyer of Adobe along with Brendan Eich of Mozilla.
The Crockford Videos are a good way to get yourself adjusted to the space you're working in.
Keep the MDC Reference handy and work on a substantial project: a library, a game, whatever. Read, write, ask questions—it's the only way.
What? No, php is a terrible language. And why the downvotes? I'm right dammit!
http://www.quirksmode.org/js/associative.html
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
The last one says stay elements are nothing more than object properties and are accessed as such.
I invite you to provide contradicting links.
You mean dynamically changing a webpage? Like how you could click a button and the webpage changes, such as a new box poping up or a text field changing?
It sounds like you're looking for Javascript. Javascript allows you to change a webpage without having to recreate the entire html file or generate a new one from PHP. Javascript allows you to do things when the user clicks or does something on a webpage.
For example: Here on Reddit when you create a comment, you click the reply button which brings up a text box to enter your comment. That's Javascript. And when you press the Save button and it saves the comment to Reddit's database then displays the comment on the page to you and other users. That's Javascript working along with PHP and a database.
In other words to get a fully dynamic site like Facebook or Reddit you need to use a combination of all of these things: HTML, CSS, Javascript, PHP and a database.
For a few tutorials and lessons on Javascript:
Here are some good places to start
MDN JavaScript Reference:
https://developer.mozilla.org/en/JavaScript/Reference
And if you are writing javascript for websites, you will likely want to use a library such as jquery, so here is a guide to getting started with it:
http://jqfundamentals.com/book/book.html
and here is a guide to debugging it focuses on jquery, but is good for vanilla javascript as well:
<code>parseInt()</code> is fine to use so long as you provide the radix.
parseInt("01010"); // 520 parseInt("01010", 10); // 1010 +"01010"; // 1010
That amendment seems much too restrictive. If I understand your definition, the callback function passed to [].forEach()
would not be considered a callback, because it is only called immediately during the execution of forEach()
. It isn't "called later when the receiver is done or in the case of a certain event like an error".
But Mozilla describes that function as a callback, and so do I:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
A callback is simply any function you pass to another function for the purpose of calling it back. It doesn't matter when that call is made or what event leads to the call, it's still a callback.
Well javascript uses some 'notable' things in it's scoping.
The name of it is Lexical Scoping
http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping
wikipedia does a decent job of explaining some of these CS topics if you follow the link chain deep enough.
The reason it's important to understand that is because it defines some of whats going on in terms of "what variables are accessed where".
You can isolate things inside of the scope, or you can opt to pull things in to it as well. The call and apply functions let you do some more fancy functional things as well as commonly used things.
And of course - Mozilla has some of the best references for javascript
heres one for call - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call
First of all, it's always faster to use native methods. If you have access to JavaScript 1.6, you can use the Array filter() method, which I'd recommend. If you don't have access to that, then your method is pretty good.
Second, ElementsFound
should be called elementsFound
to follow convention. Capital first letter if it's not an instance (Employee
) and camelCased if it's an instance (elementsFound
).
Third, you're declaring a couple of variables in the global scope, which you don't want to be doing. Change it to var elementsFound = []
and for (var e = 0 ...
.
Worth noting a slightly faster JavaScript for
loop that goes backwards through an array, but does it faster because it doesn't have to look up the length
property every time (which is a computed property).
var e = this.all.length; while (e --) { // ... }
So, to put it all together...
Object.prototype.getElementzByClassName = function() { var elementsFound = [];
var e = this.all.length; while (e --) { if (arguments[0] && this.all[e].className == arguments[0]) elementsFound.push(this.all[e]); }
return elementsFound; }
Specifically: https://developer.mozilla.org/en/JavaScript/A_re-introduction_to_JavaScript
if you're looking to learn.
The MDN in general is awesome for a proper reference place for JS and HTML as well.
Check out Mozilla's Javascript Documentation -- I find it really clearly-written & hopefully it can help you get a handle on the basics of Javascript, which will be immeasurably helpful for you working with jQuery!
Void in this case is not a function. It's an operator: https://developer.mozilla.org/en/JavaScript/Reference/Operators/void
JavaScript inserts semi-colons automatically, so the above example is 100% valid JavaScript.
It's always worked fine for IE as long as I can remember (unless you already have IE set up for debugging and are running the script in "debugging mode", IE traditionally just ignored the whole statement) . The android browser crash seems to be a limited, platform- or browser-specific bug.
It's been in the javascript spec since v1.0.
Certainly. Here it is with comments. If there's something specific I missed that you'd like explained, feel free to ask :)
function getWeekday(date, month, year) {
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], d; // best practice is to declare all variables at the top of a function // this mimics what JavaScript will do anyway, a 'feature' known as variable hoisting
if(typeof month === 'number') { // check if the month argument given is a number // if so, we give the Date constructor 3 arguments: year, month, date
d = new Date(year, month-1, parseInt(date, 10)); // month-1 because months go 0-11 // parseInt() will extract just the number from '19th', '1st', etc // the second argument, 10, specifies the radix as decimal // otherwise, if a date beginning with 0 (e.g. 09) is passed in, it will assume the radix is 8 (octal)
} else { // otherwise, assume it's a string // (a more robust solution might check that it's a string and throw an error otherwise)
d = new Date(month + ' ' + parseInt(date, 10) + ', ' + year); // this will give the Date constructor a single string argument // of the format 'February 19, 2012' or 'Mar 5, 1999'
}
return days[ d.getDay() ]; // the getDay() method of a date object returns 0-6 // so we use that to grab the human-readable format from the 'days' array
}
Here is a good reference for the Date object.
Or another option (if you have a recent version of javascript):
success: this.init.bind(this)
Or:
var self = this;
...
success: function () { self.init(); }
Every time you boost W3Schools' PageRank, an inexperienced JavaScript developer dies :-(
It's not just inaccurate in places, it's also incomplete - someone in ##javascript the other day was having trouble with a complex String replace - they were using W3Schools as their reference, but it doesn't even document that you can use special replacement patterns or pass a replacement function.
I like this guide from Mozilla, more resources can be found with a little digging I'm sure.
edit: fixed link
Right, my code above demonstrates why Math.min() === Infinity, and Math.max() === -Infinity.
EDIT: In case you were unaware, "Infinity" is a global variable in JS
delete is to remove a property of an object, if you want to remove an element in an array you have to use splice (splice, not slice).
var a = [1,2,3]; a.splice(0, 1); // Remove element(s) from index 0 and remove 1 element
That's how you remove an element from an array. See this for full reference : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Yeah the primitives are all wrapped in objects, which can be extended because the OO model is prototypical.
I think the big issue here is a realization that objects are mutable after being created.
Arrays are objects, so you would have the primitive "array" of data as per a typical array, but you have the object wrapper that lets you deal with it, for instance, [undefined, 1,2].length, where length is part of the array object, as are methods such as .slice. You can add your own methods/properties to the array object, so if you wanted to create [].foo, you could do that in the same way [].slice can be re-defined, and you can actually extend objects via the prototype chain, so lets say you want that really cool ECMA5 feature that came out recently that IE8 doesn't support called [].map, well, you can actually just do Array.prototype.map=function(){/...code that does a map.../} and now you have legacy browsers compatible with future features.
Another way to actually "see" the differences between objects and arrays is by iterating over it and doing performance test. So, an array of [1, 2, 3] can be iterated over up-to 90% faster than an object of {"0":1, "1":2, "2":3}. The other issue is when you add a method/property to an object (or array object) that property can show up when doing a for (x in y) style loop, where you should really be using y.hasOwnProperty(x) inside an if statement or you'll end up passing it into your normal logic.
Array === fast, Object === slow, Object === might pass a property that isn't it's own.
I'm looking for a good way to explain this distinction.
I'm not familiar with how jQuery works. Can you explain what $.extend does here? Intuitively, it looks like something I'd use Object.create for.
As someone who actually writes in Node everyday, there are some legitimate criticisms here. Looking at examples of Node callback chains are pretty brutal and make the code almost undecipherable to most developers.
It is worth noting that you don't have to write your code like that, however. You can organize your commonly used callbacks into defined functions and utilize bind and call to maintain correct scope references. Callback chains like the Fibonacci example (a pile of nested functions) shouldn't end up in your final code.
That said, Node.js requires an advanced level of javascript to use in a way that won't make you rip your hair out. If you hate javascript, or simply don't know it that well, Node will just aggravate you.
> And how do we test for an Array?
Array.isArray, assuming you're okay with that not working in Firefox 3.6 and some other browsers
I guess these are the best sites for JavaScript.
https://developer.mozilla.org/en/JavaScript
The best for jQuery is the jQuery Website, which also has some nice links.
assuming you only want to learn web programming here are some FREE tutorials that i found really helpful when I was learning. * HTML/CSS * javascript * PHP
I tend to agree with you. I work in advertising; the code I write gets executed against hundreds of DOMs that I had no part in creating, so I try to Leave No Trace as often as possible.
That said, if there is an open-source, pure-JS implementation of a standard method provided by one of the browser vendors, I will happily add it to prototype. Mozilla is generally good for this:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
If indexOf is undefined, use the one that Mozilla ships with Firefox. If the author's page works in Firefox, it will probably still work with this addition.
Yup, just adding in missing information from todays date to the matches and passing it to Date should be all that's needed.
[00:09:13.248] d = new Date("2011 06 29 8:00 PDT") [00:09:13.253] Wed Jun 29 2011 17:00:00 GMT+0200 (CEST) [00:09:15.128] d = new Date("2011 06 29 8:00 EDT") [00:09:15.132] Wed Jun 29 2011 14:00:00 GMT+0200 (CEST) [00:09:18.984] d = new Date("2011 06 29 8:00 UTC") [00:09:18.989] Wed Jun 29 2011 10:00:00 GMT+0200 (CEST)
The easiest and ugliest way to update the content is probably to use innerHTML.replace like so: function convertTime (str, hours, minutes, half, zone) { var now = new Date() hours = (half == 'PM') ? hours + 12 : hours return '' + now.getFullYear() + (now.getMonth() + 1) + now.getDate() + hours + ':' + minutes + zone } document.body.innerHTML = document.body.innerHTML.replace(/(\d\d?):?(?:\d\d)?\s+?(PM|AM)?\s+?([a-z]{3,4})/ig, convertTime)
The above isn't tested, but it should work or at least be close to working.
~~If everything is parsed as a number, why does "a" (when converted to number is NaN, I assume) == "a"?~~
Meh, bad example because of the same type, but still, this article suggets that. In my opinion, the MDC decribes the operator way better.
No, he means the cool shit that SpiderMonkey prototyped but that never made it in the standard; mostly chunks of the defunct ES4.
Stuff like
var [host, port] = "reddit.com:80".split(":");
or yield operators, {}-scoped variables, and a bunch of other things that can pretty much never be used in web pages since no other browser implements it.
Server-side JS on the other hand is a great place for this kind of stuff to flourish.
Honestly, E4X support alone makes this rather tempting to me.
In terms of end result, they're both the same thing - App.Subclass
referencing an instance of an Object
, which has some properties set on it.
The former could be made to do more - you could define and pass arguments to the anonymous function, or declare helper functions or data structures in the function body prior to returning, all of which would only be accessible during definition of the returned object and within any functions defined.
In terms of your understanding, I supposeApp.Subclass
is a bit more like a singleton; you're just using an Object
as a container for a bunch of stuff - there's no concept of creating more of them. The concepts "class" and "instance of a class" map a bit more closely to constructor Functions and using the <code>new</code> operator on them, respectively.
It's basically this table, reading down. The tweet is cute and snarky, but also misleading, since it breaks out multiple operators that share the same precedence.
A more accurate one would be "MFIUPSuShCoEBaXBoLaLoCnACm":
If you consider how rare the bitwise operators are, it's actually not that bad. In practice, all you really need to be aware of most of the time is:
This reminded me about something I read a while back... https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Parameters (specifically the arraylength property)
It appears there is a max length to array (at least in mozilla), although it doesn't seem you have anywhere near ~4.3 billion elements.
The Mozilla reference is good for more than DOM manipulation, here you also find a complete JavaScript Reference and a nice guide through the language
mozillas javascript guide and mozillas canvas guide. almost nothing is more fun and satisfying than writing code that doodles around on a canvas.
Came here to suggest this website. You might also want to check out documentation for PHP and JavaScript, which I find are just as useful.
Depending on what you're trying to do, I also suggest checking out Google's Python Class. They also have some lessons on Youtube.
Also...HTML is not really a scripting language, it's a markup language (just being nitpicky).
Good luck!