From f5023cc9b35be5d1986a76ce1d6f44979a766afb Mon Sep 17 00:00:00 2001 From: greybird Date: Mon, 5 Aug 2013 17:22:53 +0400 Subject: fix immediately-executing function --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 9cc7617d..cc279b9a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -241,7 +241,7 @@ i // = 5 - not undefined as you'd expect in a block-scoped language // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. -function(){ +(function(){ var temporary = 5 // We can access the global scope by assiging to the 'global object', which // in a web browser is always 'window'. The global object may have a @@ -249,7 +249,7 @@ function(){ window.permanent = 10 // Or, as previously mentioned, we can just leave the var keyword off. permanent2 = 15 -}() +})() temporary // raises ReferenceError permanent // = 10 permanent2 // = 15 -- cgit v1.2.3 From 69c4e4e509019740cab8eb2074826b5c5c9f6ec3 Mon Sep 17 00:00:00 2001 From: Kyle Simpson Date: Wed, 14 Aug 2013 00:12:15 -0500 Subject: Made some corrections and clarifications --- javascript.html.markdown | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index cc279b9a..865edc36 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -104,9 +104,10 @@ false // There's also null and undefined null // used to indicate a deliberate non-value -undefined // used to indicate a value that hasn't been set yet +undefined // used to indicate a value is not currently present (although undefined + // is actually a value itself) -// null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. +// false, null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// @@ -142,7 +143,7 @@ myArray[1] // = 45 // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. -{key1: "Hello", key2: "World"} +var myObj = {key1: "Hello", key2: "World"} // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. @@ -211,9 +212,13 @@ function myFunction(thing){ myFunction("foo") // = "FOO" // Functions can also be defined "anonymously" - without a name: -function(thing){ +(function(thing){ return thing.toLowerCase() -} +}) +// Note: Stand-alone function declarations require an identifier name. +// Anonymous functions are values, not declarations, so they must be +// treated as a value. We wrap ours here in ( ) to do so, or you could assign +// it to a variable, or pass it as a parameter to another function. // (we can't call our function, since we don't have a name to refer to it with) // JavaScript functions are first class objects, so they can be reassigned to @@ -247,12 +252,15 @@ i // = 5 - not undefined as you'd expect in a block-scoped language // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10 - // Or, as previously mentioned, we can just leave the var keyword off. + // Or, as previously mentioned, if you leave the var keyword off, a + // global variable will be created when you assign it a value. However, + // this behavior is frowned upon, and in fact is disallowed in "strict + // mode". permanent2 = 15 })() temporary // raises ReferenceError permanent // = 10 -permanent2 // = 15 +permanent2 // = 15 <-- the accidental global variable // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the @@ -268,6 +276,12 @@ function sayHelloInFiveSeconds(name){ // access to the value of prompt. } sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s +// inner() has access to the variable "prompt" strictly because of lexical scope. +// A closure is being demonstrated because the inner() function is being executed +// at a later time, and in fact being executed "outside" the scope where it was +// declared (inside of the implementation of setTimeout()), but yet inner() STILL +// has access to the variable "prompt". It is said that inner() has a "closure" +// over the variables of sayHelloInFiveSeconds(). /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 02ea95377d4963c60a96976b4092bdcc2b638594 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 14 Aug 2013 17:20:34 +0930 Subject: Avoid telling people about techniques that are discouraged anyway --- javascript.html.markdown | 6 ------ 1 file changed, 6 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 865edc36..1f188832 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -252,15 +252,9 @@ i // = 5 - not undefined as you'd expect in a block-scoped language // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10 - // Or, as previously mentioned, if you leave the var keyword off, a - // global variable will be created when you assign it a value. However, - // this behavior is frowned upon, and in fact is disallowed in "strict - // mode". - permanent2 = 15 })() temporary // raises ReferenceError permanent // = 10 -permanent2 // = 15 <-- the accidental global variable // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the -- cgit v1.2.3 From a82859f95bb235074d740530dfa60afca7025223 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 14 Aug 2013 17:21:29 +0930 Subject: Explain anonymous functions after first-class, and more concisely --- javascript.html.markdown | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 1f188832..bcaf9a29 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -211,16 +211,6 @@ function myFunction(thing){ } myFunction("foo") // = "FOO" -// Functions can also be defined "anonymously" - without a name: -(function(thing){ - return thing.toLowerCase() -}) -// Note: Stand-alone function declarations require an identifier name. -// Anonymous functions are values, not declarations, so they must be -// treated as a value. We wrap ours here in ( ) to do so, or you could assign -// it to a variable, or pass it as a parameter to another function. -// (we can't call our function, since we don't have a name to refer to it with) - // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: @@ -229,9 +219,16 @@ function myFunction(){ } setTimeout(myFunction, 5000) +// Functions can also be defined "anonymously" - without a name: +var lowerFunction = function(thing){ + return thing.toLowerCase() +} +lowerFunction("Foo") // = "foo" +// (note: we've assigned our anonymous function to a variable - if we didn't, we +// wouldn't be able to access it) + // You can even write the function statement directly in the call to the other // function. - setTimeout(function myFunction(){ // this code will be called in 5 seconds' time }, 5000) -- cgit v1.2.3 From 5f2928df6b19337426bed0a60650be79bda437a1 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 14 Aug 2013 17:21:44 +0930 Subject: More concise explanation of closures --- javascript.html.markdown | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index bcaf9a29..9b87b022 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -185,7 +185,7 @@ do { input = getInput() } while (!isValid(input)) -// the for loop is the same as C and Java: +// the for loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times @@ -255,24 +255,19 @@ permanent // = 10 // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the -// outer function's variables. +// outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!" function inner(){ alert(prompt) } setTimeout(inner, 5000) - // setTimeout is asynchronous, so this function will finish without waiting - // 5 seconds. However, once the 5 seconds is up, inner will still have - // access to the value of prompt. + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the 'prompt' variable when it is finally called. } sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s -// inner() has access to the variable "prompt" strictly because of lexical scope. -// A closure is being demonstrated because the inner() function is being executed -// at a later time, and in fact being executed "outside" the scope where it was -// declared (inside of the implementation of setTimeout()), but yet inner() STILL -// has access to the variable "prompt". It is said that inner() has a "closure" -// over the variables of sayHelloInFiveSeconds(). /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 05c3ca90447e6f63fa02847468e8a95f250fbe50 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 15 Aug 2013 20:33:44 +0930 Subject: [javascript] Remove anonymous function assignment example. ref #215 --- javascript.html.markdown | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 9b87b022..25777578 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -219,17 +219,9 @@ function myFunction(){ } setTimeout(myFunction, 5000) -// Functions can also be defined "anonymously" - without a name: -var lowerFunction = function(thing){ - return thing.toLowerCase() -} -lowerFunction("Foo") // = "foo" -// (note: we've assigned our anonymous function to a variable - if we didn't, we -// wouldn't be able to access it) - -// You can even write the function statement directly in the call to the other -// function. -setTimeout(function myFunction(){ +// Function objects don't even have to be declared with a name - you can write +// an anonymous function definition directly into the arguments of another. +setTimeout(function(){ // this code will be called in 5 seconds' time }, 5000) -- cgit v1.2.3 From 80f97751a21b0c04ee077c23b715a8adc0063788 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 15 Aug 2013 21:05:27 +0930 Subject: [javascript] Add semicolons. Closes #214. --- javascript.html.markdown | 218 +++++++++++++++++++++++------------------------ 1 file changed, 109 insertions(+), 109 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 25777578..fb79949e 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -30,82 +30,82 @@ doStuff(); // wherever there's a newline, except in certain cases. doStuff() -// We'll leave semicolons off here; whether you do or not will depend on your -// personal preference or your project's style guide. +// So that we don't have to worry about those certain cases (for now), we'll +// leave them on. /////////////////////////////////// // 1. Numbers, Strings and Operators // Javascript has one number type (which is a 64-bit IEEE 754 double). -3 // = 3 -1.5 // = 1.5 +3; // = 3 +1.5; // = 1.5 // All the basic arithmetic works as you'd expect. -1 + 1 // = 2 -8 - 1 // = 7 -10 * 2 // = 20 -35 / 5 // = 7 +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 // Including uneven division. -5 / 2 // = 2.5 +5 / 2; // = 2.5 // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. -1 << 2 // = 4 +1 << 2; // = 4 // Precedence is enforced with parentheses. -(1 + 3) * 2 // = 8 +(1 + 3) * 2; // = 8 // There are three special not-a-real-number values: -Infinity // result of e.g. 1/0 --Infinity // result of e.g. -1/0 -NaN // result of e.g. 0/0 +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 // There's also a boolean type. -true -false +true; +false; // Strings are created with ' or ". -'abc' -"Hello, world" +'abc'; +"Hello, world"; // Negation uses the ! symbol -!true // = false -!false // = true +!true; // = false +!false; // = true // Equality is == -1 == 1 // = true -2 == 1 // = false +1 == 1; // = true +2 == 1; // = false // Inequality is != -1 != 1 // = false -2 != 1 // = true +1 != 1; // = false +2 != 1; // = true // More comparisons -1 < 10 // = true -1 > 10 // = false -2 <= 2 // = true -2 >= 2 // = true +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true // Strings are concatenated with + -"Hello " + "world!" // = "Hello world!" +"Hello " + "world!"; // = "Hello world!" // and are compared with < and > -"a" < "b" // = true +"a" < "b"; // = true // Type coercion is performed for comparisons... -"5" == 5 // = true +"5" == 5; // = true // ...unless you use === -"5" === 5 // = false +"5" === 5; // = false // You can access characters in a string with charAt -"This is a string".charAt(0) +"This is a string".charAt(0); // There's also null and undefined -null // used to indicate a deliberate non-value -undefined // used to indicate a value is not currently present (although undefined - // is actually a value itself) +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although undefined + // is actually a value itself) // false, null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". @@ -115,57 +115,57 @@ undefined // used to indicate a value is not currently present (although undefin // Variables are declared with the var keyword. Javascript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. -var someVar = 5 +var someVar = 5; // if you leave the var keyword off, you won't get an error... -someOtherVar = 10 +someOtherVar = 10; // ...but your variable will be created in the global scope, not in the scope // you defined it in. // Variables declared without being assigned to are set to undefined. -var someThirdVar // = undefined +var someThirdVar; // = undefined // There's shorthand for performing math operations on variables: -someVar += 5 // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10 // now someVar is 100 +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 // and an even-shorter-hand for adding or subtracting 1 -someVar++ // now someVar is 101 -someVar-- // back to 100 +someVar++; // now someVar is 101 +someVar--; // back to 100 // Arrays are ordered lists of values, of any type. -var myArray = ["Hello", 45, true] +var myArray = ["Hello", 45, true]; // Their members can be accessed using the square-brackets subscript syntax. // Array indices start at zero. -myArray[1] // = 45 +myArray[1]; // = 45 // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. -var myObj = {key1: "Hello", key2: "World"} +var myObj = {key1: "Hello", key2: "World"}; // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. -var myObj = {myKey: "myValue", "my other key": 4} +var myObj = {myKey: "myValue", "my other key": 4}; // Object attributes can also be accessed using the subscript syntax, -myObj["my other key"] // = 4 +myObj["my other key"]; // = 4 // ... or using the dot syntax, provided the key is a valid identifier. -myObj.myKey // = "myValue" +myObj.myKey; // = "myValue" // Objects are mutable; values can be changed and new keys added. -myObj.myThirdKey = true +myObj.myThirdKey = true; // If you try to access a value that's not yet set, you'll get undefined. -myObj.myFourthKey // = undefined +myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures // The if structure works as you'd expect. -var count = 1 +var count = 1; if (count == 3){ // evaluated if count is 3 } else if (count == 4) { @@ -182,7 +182,7 @@ while (true) { // Do-while loops are like while loops, except they always run at least once. var input do { - input = getInput() + input = getInput(); } while (!isValid(input)) // the for loop is the same as C and Java: @@ -193,23 +193,23 @@ for (var i = 0; i < 5; i++){ // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear" + house.contains = "bear"; } if (colour == "red" || colour == "blue"){ // colour is either red or blue } // && and || "short circuit", which is useful for setting default values. -var name = otherName || "default" +var name = otherName || "default"; /////////////////////////////////// // 4. Functions, Scope and Closures // JavaScript functions are declared with the function keyword. function myFunction(thing){ - return thing.toUpperCase() + return thing.toUpperCase(); } -myFunction("foo") // = "FOO" +myFunction("foo"); // = "FOO" // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for @@ -217,49 +217,49 @@ myFunction("foo") // = "FOO" function myFunction(){ // this code will be called in 5 seconds' time } -setTimeout(myFunction, 5000) +setTimeout(myFunction, 5000); // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ // this code will be called in 5 seconds' time -}, 5000) +}, 5000); // JavaScript has function scope; functions get their own scope but other blocks // do not. if (true){ - var i = 5 + var i = 5; } -i // = 5 - not undefined as you'd expect in a block-scoped language +i; // = 5 - not undefined as you'd expect in a block-scoped language // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. (function(){ - var temporary = 5 + var temporary = 5; // We can access the global scope by assiging to the 'global object', which // in a web browser is always 'window'. The global object may have a // different name in non-browser environments such as Node.js. - window.permanent = 10 -})() -temporary // raises ReferenceError -permanent // = 10 + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!" + var prompt = "Hello, " + name + "!"; function inner(){ - alert(prompt) + alert(prompt); } - setTimeout(inner, 5000) + setTimeout(inner, 5000); // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has // access to the 'prompt' variable when it is finally called. } -sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes @@ -267,44 +267,44 @@ sayHelloInFiveSeconds("Adam") // will open a popup with "Hello, Adam!" in 5s // Objects can contain functions. var myObj = { myFunc: function(){ - return "Hello world!" + return "Hello world!"; } -} -myObj.myFunc() // = "Hello world!" +}; +myObj.myFunc(); // = "Hello world!" // When functions attached to an object are called, they can access the object // they're attached to using the this keyword. myObj = { myString: "Hello world!", myFunc: function(){ - return this.myString + return this.myString; } -} -myObj.myFunc() // = "Hello world!" +}; +myObj.myFunc(); // = "Hello world!" // What this is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. -var myFunc = myObj.myFunc -myFunc() // = undefined +var myFunc = myObj.myFunc; +myFunc(); // = undefined // Inversely, a function can be assigned to the object and gain access to it // through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ - return this.myString.toUpperCase() + return this.myString.toUpperCase(); } -myObj.myOtherFunc = myOtherFunc -myObj.myOtherFunc() // = "HELLO WORLD!" +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" // When you call a function with the new keyword, a new object is created, and // made available to the function via this. Functions designed to be called // like this are called constructors. var MyConstructor = function(){ - this.myNumber = 5 + this.myNumber = 5; } -myNewObj = new MyConstructor() // = {myNumber: 5} -myNewObj.myNumber // = 5 +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 // Every JavaScript object has a 'prototype'. When you go to access a property // on an object that doesn't exist on the actual object, the interpreter will @@ -315,31 +315,31 @@ myNewObj.myNumber // = 5 // part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!", -} +}; var myPrototype = { meaningOfLife: 42, myFunc: function(){ return this.myString.toLowerCase() } -} -myObj.__proto__ = myPrototype -myObj.meaningOfLife // = 42 +}; +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 // This works for functions, too. -myObj.myFunc() // = "hello world!" +myObj.myFunc(); // = "hello world!" // Of course, if your property isn't on your prototype, the prototype's // prototype is searched, and so on. myPrototype.__proto__ = { myBoolean: true -} -myObj.myBoolean // = true +}; +myObj.myBoolean; // = true // There's no copying involved here; each object stores a reference to its // prototype. This means we can alter the prototype and our changes will be // reflected everywhere. -myPrototype.meaningOfLife = 43 -myObj.meaningOfLife // = 43 +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 // We mentioned that __proto__ was non-standard, and there's no standard way to // change the prototype of an existing object. However, there's two ways to @@ -347,8 +347,8 @@ myObj.meaningOfLife // = 43 // The first is Object.create, which is a recent addition to JS, and therefore // not available in all implementations yet. -var myObj = Object.create(myPrototype) -myObj.meaningOfLife // = 43 +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 // The second way, which works anywhere, has to do with constructors. // Constructors have a property called prototype. This is *not* the prototype of @@ -358,20 +358,20 @@ myConstructor.prototype = { getMyNumber: function(){ return this.myNumber } -} -var myNewObj2 = new myConstructor() -myNewObj2.getMyNumber() // = 5 +}; +var myNewObj2 = new myConstructor(); +myNewObj2.getMyNumber(); // = 5 // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. -var myNumber = 12 -var myNumberObj = new Number(12) -myNumber == myNumberObj // = true +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true // Except, they aren't exactly equivalent. -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' -myNumber === myNumberObj // = false +typeof(myNumber); // = 'number' +typeof(myNumberObj); // = 'object' +myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } @@ -382,9 +382,9 @@ if (Number(0)){ // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ - return this.charAt(0) + return this.charAt(0); } -"abc".firstCharacter() // = "a" +"abc".firstCharacter(); // = "a" // This fact is often used in "polyfilling", which is implementing newer // features of JavaScript in an older subset of JavaScript, so that they can be @@ -395,10 +395,10 @@ String.prototype.firstCharacter = function(){ if (Object.create === undefined){ // don't overwrite it if it exists Object.create = function(proto){ // make a temporary constructor with the right prototype - var Constructor = function(){} - Constructor.prototype = proto + var Constructor = function(){}; + Constructor.prototype = proto; // then use it to create a new, appropriately-prototyped object - return new Constructor() + return new Constructor(); } } ``` -- cgit v1.2.3 From cf90a62a7a21f93971bbf71e4d2188bbf97ab21e Mon Sep 17 00:00:00 2001 From: Billy Shih Date: Mon, 19 Aug 2013 15:19:48 -0700 Subject: Fixed a grammatical error --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index fb79949e..1dd6e2be 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -342,7 +342,7 @@ myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 // We mentioned that __proto__ was non-standard, and there's no standard way to -// change the prototype of an existing object. However, there's two ways to +// change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. // The first is Object.create, which is a recent addition to JS, and therefore -- cgit v1.2.3 From e546f9cd9c87733fc9e502746109a8abe0a12f86 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 2 Sep 2013 21:33:53 -0700 Subject: Add file download to javascript.js --- javascript.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 1dd6e2be..bc2a973a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -1,7 +1,8 @@ --- language: javascript -author: Adam Brenecki -author_url: http://adam.brenecki.id.au +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +filename: javascript.js --- Javascript was created by Netscape's Brendan Eich in 1995. It was originally -- cgit v1.2.3 From 3f9ba06563c580c4795228a822475bf305d5b694 Mon Sep 17 00:00:00 2001 From: jeroenransijn Date: Wed, 11 Sep 2013 15:51:21 +0200 Subject: Note aboute setTimeout --- javascript.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index bc2a973a..859d61a9 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -219,6 +219,7 @@ function myFunction(){ // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); +// Note: setTimeout isn't part of the JS language, but is provided by browsers and Node.js. // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. -- cgit v1.2.3 From 9d1015232c1c5cf90ccc8d4807d8c4216a2406dc Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 13 Sep 2013 20:21:14 +0930 Subject: Wrapped setTimeout note to 80 chars --- javascript.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 859d61a9..2f742574 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -219,7 +219,8 @@ function myFunction(){ // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); -// Note: setTimeout isn't part of the JS language, but is provided by browsers and Node.js. +// Note: setTimeout isn't part of the JS language, but is provided by browsers +// and Node.js. // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. -- cgit v1.2.3 From 49b30c38e2741162bd1661e020fe80c80759dee3 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:17:10 +0930 Subject: Add missing semicolon --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 2f742574..9adc0a6d 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -359,7 +359,7 @@ myObj.meaningOfLife; // = 43 // are given when they're created with that constructor and the new keyword. myConstructor.prototype = { getMyNumber: function(){ - return this.myNumber + return this.myNumber; } }; var myNewObj2 = new myConstructor(); -- cgit v1.2.3 From 750b2a2f21262fc011d5ee07362c667223d3de23 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Fri, 20 Sep 2013 19:22:00 +0930 Subject: [javascript] clarify constructor prototype example, as per #204 --- javascript.html.markdown | 3 +++ 1 file changed, 3 insertions(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 9adc0a6d..b15eae7c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -358,12 +358,15 @@ myObj.meaningOfLife; // = 43 // the constructor function itself; instead, it's the prototype that new objects // are given when they're created with that constructor and the new keyword. myConstructor.prototype = { + myNumber: 5, getMyNumber: function(){ return this.myNumber; } }; var myNewObj2 = new myConstructor(); myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. -- cgit v1.2.3 From a91b4fd300d0fc66b5d5d9c29d86d8b4c4cb5464 Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Thu, 3 Oct 2013 20:02:16 +0200 Subject: be consistent with PascalCasing of constructors --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index b15eae7c..6b6be34d 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -357,13 +357,13 @@ myObj.meaningOfLife; // = 43 // Constructors have a property called prototype. This is *not* the prototype of // the constructor function itself; instead, it's the prototype that new objects // are given when they're created with that constructor and the new keyword. -myConstructor.prototype = { +MyConstructor.prototype = { myNumber: 5, getMyNumber: function(){ return this.myNumber; } }; -var myNewObj2 = new myConstructor(); +var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 -- cgit v1.2.3 From 9c0e7c548d3fb0cf655f282e36b1c24b21bba83b Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 10 Oct 2013 08:33:39 +1030 Subject: [javascript] Add bit about array mutability. Closes #381. --- javascript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 6b6be34d..97c5b712 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -142,6 +142,10 @@ var myArray = ["Hello", 45, true]; // Array indices start at zero. myArray[1]; // = 45 +// Arrays are mutable and of variable length. +myArray.push("World"); +myArray.length; // = 4 + // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; -- cgit v1.2.3 From c149c619da0f258c55bfb355e9d9e3b02dc880c2 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Thu, 10 Oct 2013 10:52:56 +1030 Subject: [javascript] Added note about ints --- javascript.html.markdown | 2 ++ 1 file changed, 2 insertions(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 97c5b712..2ac98105 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -38,6 +38,8 @@ doStuff() // 1. Numbers, Strings and Operators // Javascript has one number type (which is a 64-bit IEEE 754 double). +// As with Lua, don't freak out about the lack of ints: doubles have a 52-bit +// mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 -- cgit v1.2.3 From cba64739f5e61f8fb524dc1cc88cbb31920d2b86 Mon Sep 17 00:00:00 2001 From: Steven Senatori Date: Sat, 2 Nov 2013 16:50:29 -0700 Subject: Deleted some bad syntax and tweaked an explanation for clarity --- javascript.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 2ac98105..36aad102 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -306,8 +306,8 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // When you call a function with the new keyword, a new object is created, and -// made available to the function via this. Functions designed to be called -// like this are called constructors. +// made available to the function via the this keyword. Functions designed to be called +// like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; @@ -323,14 +323,14 @@ myNewObj.myNumber; // = 5 // property __proto__. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. var myObj = { - myString: "Hello world!", + myString: "Hello world!" }; var myPrototype = { meaningOfLife: 42, myFunc: function(){ return this.myString.toLowerCase() } -}; + myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 -- cgit v1.2.3 From 34b0264620c540bcdc451c96996ff5a38a6d26db Mon Sep 17 00:00:00 2001 From: Steven Senatori Date: Sat, 2 Nov 2013 17:30:36 -0700 Subject: fixing one of my corrections, no idea why I delted the }; on line 333 previously...sorry --- javascript.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 36aad102..2d665e67 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -330,6 +330,7 @@ var myPrototype = { myFunc: function(){ return this.myString.toLowerCase() } +}; myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 -- cgit v1.2.3 From 9f0ae279d83a41bec3c9998c5245c46908942873 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Tue, 5 Nov 2013 12:47:58 +1030 Subject: [javascript/en] Enforce 80-char line width --- javascript.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 2d665e67..b6d4c8b7 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -107,10 +107,10 @@ false; // There's also null and undefined null; // used to indicate a deliberate non-value -undefined; // used to indicate a value is not currently present (although undefined - // is actually a value itself) +undefined; // used to indicate a value is not currently present (although + // undefined is actually a value itself) -// false, null, undefined, NaN, 0 and "" are falsy, and everything else is truthy. +// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// @@ -306,8 +306,8 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // When you call a function with the new keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be called -// like that are called constructors. +// made available to the function via the this keyword. Functions designed to be +// called like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; -- cgit v1.2.3 From ec3343839fb3b7bc548eb5cab8c716c97753c51b Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Tue, 26 Nov 2013 18:28:44 +1030 Subject: [javascript] Add notes about ASI. Closes #424. --- javascript.html.markdown | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index b6d4c8b7..348cbff5 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -31,8 +31,8 @@ doStuff(); // wherever there's a newline, except in certain cases. doStuff() -// So that we don't have to worry about those certain cases (for now), we'll -// leave them on. +// Because those cases can cause unexpected results, we'll keep on using +// semicolons in this guide. /////////////////////////////////// // 1. Numbers, Strings and Operators @@ -218,6 +218,18 @@ function myFunction(thing){ } myFunction("foo"); // = "FOO" +// Note that the value to be returned must start on the same line as the +// 'return' keyword, otherwise you'll always return 'undefined' due to +// automatic semicolon insertion. Watch out for this when using Allman style. +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: -- cgit v1.2.3 From 432eb6f53df3a78dd5d3f564a1bbaa551a970732 Mon Sep 17 00:00:00 2001 From: cubuspl42 Date: Sat, 14 Dec 2013 14:41:07 +0100 Subject: Note about how declaring functions affects scope. --- javascript.html.markdown | 2 ++ 1 file changed, 2 insertions(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 348cbff5..5f0b7951 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -271,6 +271,8 @@ permanent; // = 10 // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; + // Inner functions are put in the local scope local by default, as if they + // were declared with 'var'. function inner(){ alert(prompt); } -- cgit v1.2.3 From eafeb3b4611d705f0c83bd652089bab364a8b2db Mon Sep 17 00:00:00 2001 From: cubuspl42 Date: Sat, 14 Dec 2013 14:44:06 +0100 Subject: typo --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 5f0b7951..4584a28c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -271,8 +271,8 @@ permanent; // = 10 // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; - // Inner functions are put in the local scope local by default, as if they - // were declared with 'var'. + // Inner functions are put in the local scope by default, as if they were + // declared with 'var'. function inner(){ alert(prompt); } -- cgit v1.2.3 From 7927c1bf3a57538d39bfa3c5c5385b2cd8d84a91 Mon Sep 17 00:00:00 2001 From: Joel Birchler Date: Thu, 26 Dec 2013 22:50:17 -0800 Subject: Added call, apply, bind JavaScript examples --- javascript.html.markdown | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 4584a28c..7fb7ba55 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -319,6 +319,37 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" +// We can also specify a context for a function to execute in when we invoke it +// using 'call' or 'apply'. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// The 'apply' function is nearly identical, but takes an array for an argument list. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// This is useful when working with a function that accepts a sequence of arguments +// and you want to pass an array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use +// bind. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Bind can also be used to partially apply (curry) a function. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + // When you call a function with the new keyword, a new object is created, and // made available to the function via the this keyword. Functions designed to be // called like that are called constructors. -- cgit v1.2.3 From c43c033646f87b735246bb5c681945b72cc4855c Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Sun, 19 Jan 2014 16:10:58 +1030 Subject: Fixed `) {` vs `){` inconsistency --- javascript.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 7fb7ba55..a9d73cf1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -175,14 +175,14 @@ myObj.myFourthKey; // = undefined var count = 1; if (count == 3){ // evaluated if count is 3 -} else if (count == 4) { +} else if (count == 4){ // evaluated if count is 4 } else { // evaluated if it's not either 3 or 4 } // As does while. -while (true) { +while (true){ // An infinite loop! } @@ -327,7 +327,7 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// The 'apply' function is nearly identical, but takes an array for an argument list. +// The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -- cgit v1.2.3 From 08107bef21fad628b617bbc4a5e2e79d5638da72 Mon Sep 17 00:00:00 2001 From: Renjith G R Date: Wed, 22 Jan 2014 10:52:24 +0530 Subject: Fixed capitalization in the word JavaScript Changed Javascript to JavaScript in the first paragraph. --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index a9d73cf1..cef5b4b9 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -5,7 +5,7 @@ contributors: filename: javascript.js --- -Javascript was created by Netscape's Brendan Eich in 1995. It was originally +JavaScript was created by Netscape's Brendan Eich in 1995. It was originally intended as a simpler scripting language for websites, complimenting the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than -- cgit v1.2.3 From 845dc497adbfe2ec149f7ba7e62a25b146dd8e23 Mon Sep 17 00:00:00 2001 From: Renjith G R Date: Wed, 22 Jan 2014 11:22:07 +0530 Subject: Fix capitalization in the word JavaScript There were two more other places where JavaScript was written as Javascript. --- javascript.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index cef5b4b9..85c5d817 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -37,7 +37,7 @@ doStuff() /////////////////////////////////// // 1. Numbers, Strings and Operators -// Javascript has one number type (which is a 64-bit IEEE 754 double). +// JavaScript has one number type (which is a 64-bit IEEE 754 double). // As with Lua, don't freak out about the lack of ints: doubles have a 52-bit // mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. 3; // = 3 @@ -116,7 +116,7 @@ undefined; // used to indicate a value is not currently present (although /////////////////////////////////// // 2. Variables, Arrays and Objects -// Variables are declared with the var keyword. Javascript is dynamically typed, +// Variables are declared with the var keyword. JavaScript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. var someVar = 5; @@ -477,7 +477,7 @@ more about how to use JavaScript in web pages, start by learning about the [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts of the language. In addition to direct contributors to this article, some content is adapted -- cgit v1.2.3 From 0590851a648b7afbc1fd8df332307688b9784a84 Mon Sep 17 00:00:00 2001 From: Ariel Date: Mon, 10 Mar 2014 17:23:49 -0400 Subject: Added a bit of example code and resources. --- javascript.html.markdown | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c5d817..03a12372 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -2,6 +2,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] filename: javascript.js --- @@ -103,7 +104,13 @@ false; "5" === 5; // = false // You can access characters in a string with charAt -"This is a string".charAt(0); +"This is a string".charAt(0); // = 'T' + +//...or use substring to get larger pieces +"Hello world".substring(0, 5); // = "Hello" + +// length is a property, so don't use () +"Hello".length; // = 5 // There's also null and undefined null; // used to indicate a deliberate non-value @@ -148,6 +155,9 @@ myArray[1]; // = 45 myArray.push("World"); myArray.length; // = 4 +// Add/Modify at specific index +myArray[3] = "Hello"; + // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; @@ -171,6 +181,8 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures +// The syntax for this section is almost identical to Java's. + // The if structure works as you'd expect. var count = 1; if (count == 3){ @@ -209,6 +221,27 @@ if (colour == "red" || colour == "blue"){ // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; + +// switch statement checks for equality with === +// use 'break' after each case +// or the cases after the correct one will be executed too. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + /////////////////////////////////// // 4. Functions, Scope and Closures @@ -477,9 +510,13 @@ more about how to use JavaScript in web pages, start by learning about the [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts of the language. +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + In addition to direct contributors to this article, some content is adapted from Louie Dinh's Python tutorial on this site, and the [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -- cgit v1.2.3 From 6348a3adde95e72334bf8bfd1ca95079862c1c0b Mon Sep 17 00:00:00 2001 From: Ariel Date: Mon, 10 Mar 2014 18:08:50 -0400 Subject: space --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 03a12372..76017c17 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -106,7 +106,7 @@ false; // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' -//...or use substring to get larger pieces +// ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" // length is a property, so don't use () -- cgit v1.2.3 From 659bc7566f1791800a06995a610306cdc8430e71 Mon Sep 17 00:00:00 2001 From: Nati Date: Tue, 10 Jun 2014 16:54:32 -0700 Subject: Changed "complimenting" to "complementing". --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 76017c17..c59a90c3 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -7,7 +7,7 @@ filename: javascript.js --- JavaScript was created by Netscape's Brendan Eich in 1995. It was originally -intended as a simpler scripting language for websites, complimenting the use of +intended as a simpler scripting language for websites, complementing the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than Java in web frontends. -- cgit v1.2.3 From 7cf0bcb8283a0be92f77b40568355f02ac1811af Mon Sep 17 00:00:00 2001 From: m90 Date: Sat, 9 Aug 2014 21:41:12 +0200 Subject: [javascript/*] typeof is an operand and not a function/method - fix usage / remove parens --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index c59a90c3..7c869b28 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -460,8 +460,8 @@ var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Except, they aren't exactly equivalent. -typeof(myNumber); // = 'number' -typeof(myNumberObj); // = 'object' +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. -- cgit v1.2.3 From fb28f2c10258eb92dc40db648a304f3e5b78bd2f Mon Sep 17 00:00:00 2001 From: ml242 Date: Mon, 27 Oct 2014 00:43:20 -0400 Subject: Your Name: Matt Subject Line: Addresses Comparisons in Javascript What Happened: I believe that starting out with the double equals instead of the triple equals for strict comparison checking is incorrect. Because double equals uses type coercion, it is more of a feature the needs to be understood. Beginners looking at the language should look upon the stricter method as the proper one because it is less likely to give a surprising result. I also tried to address the behaviour by adding an example to the double equals comparison. Hope that the community is interested in pulling in these changes, they stem from teaching beginners javaScript but I am by no means the authority. --- javascript.html.markdown | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 76017c17..f190ff98 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -77,13 +77,13 @@ false; !true; // = false !false; // = true -// Equality is == -1 == 1; // = true -2 == 1; // = false +// Equality is === +1 === 1; // = true +2 === 1; // = false -// Inequality is != -1 != 1; // = false -2 != 1; // = true +// Inequality is !== +1 !== 1; // = false +2 !== 1; // = true // More comparisons 1 < 10; // = true @@ -97,11 +97,13 @@ false; // and are compared with < and > "a" < "b"; // = true -// Type coercion is performed for comparisons... +// Type coercion is performed for comparisons with double equals... "5" == 5; // = true +null == undefined; // = true // ...unless you use === "5" === 5; // = false +null === undefined; // = false // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' -- cgit v1.2.3 From eb43eb7ccdeaad7440d9fda90128691effda15e1 Mon Sep 17 00:00:00 2001 From: i Date: Tue, 28 Oct 2014 03:11:59 -0400 Subject: basic arithmetic *doesn't* work It's not really true that arithmetic is accurate in JavaScript. --- javascript.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index cc210c4a..792cab98 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -39,13 +39,14 @@ doStuff() // 1. Numbers, Strings and Operators // JavaScript has one number type (which is a 64-bit IEEE 754 double). -// As with Lua, don't freak out about the lack of ints: doubles have a 52-bit -// mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely. +// Doubles have a 52-bit mantissa, which is enough to store integers +// up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 -// All the basic arithmetic works as you'd expect. +// Some basic arithmetic works as you'd expect. 1 + 1; // = 2 +.1 + .2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -- cgit v1.2.3 From 3921d11155780f8219a8110d8fe4ede88c9fcadf Mon Sep 17 00:00:00 2001 From: i Date: Tue, 28 Oct 2014 03:56:12 -0400 Subject: more oddities JavaScript is full of oddities .. I definitely wouldn't claim everything works "as it should" .. you don't have to include the gotcha's but I don't know, they're not that confusing for me. --- javascript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index cc210c4a..2dece277 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -105,6 +105,10 @@ null == undefined; // = true "5" === 5; // = false null === undefined; // = false +// ...which can result in some weird behaviour... +13 + !0; // 14 +"13" + !0; // '13true' + // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' -- cgit v1.2.3 From 9324987c1fc465379060491d9a4b1c25cffde0fc Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Thu, 30 Oct 2014 16:43:49 +0100 Subject: use propernotation for decimals --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 792cab98..a92dcb4a 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -46,7 +46,7 @@ doStuff() // Some basic arithmetic works as you'd expect. 1 + 1; // = 2 -.1 + .2; // = 0.30000000000000004 +0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -- cgit v1.2.3 From e69ca623a73756c39c2fba7d61221fd59a291fa0 Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Tue, 3 Feb 2015 17:31:44 -0500 Subject: javascript/en: added some md formatting Added some markdown formatting to the comments throughout to clarify meaning. Also tweaked a couple of other quote marks as well. Also shortened a couple of long lines. More to do, but stopped here for now. :) --- javascript.html.markdown | 60 +++++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 29 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index aabd5e43..f61e6c74 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -110,19 +110,19 @@ null === undefined; // = false 13 + !0; // 14 "13" + !0; // '13true' -// You can access characters in a string with charAt +// You can access characters in a string with `charAt` "This is a string".charAt(0); // = 'T' -// ...or use substring to get larger pieces +// ...or use `substring` to get larger pieces. "Hello world".substring(0, 5); // = "Hello" -// length is a property, so don't use () +// `length` is a property, so don't use (). "Hello".length; // = 5 -// There's also null and undefined -null; // used to indicate a deliberate non-value +// There's also `null` and `undefined`. +null; // used to indicate a deliberate non-value undefined; // used to indicate a value is not currently present (although - // undefined is actually a value itself) + // `undefined` is actually a value itself) // false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". @@ -130,8 +130,9 @@ undefined; // used to indicate a value is not currently present (although /////////////////////////////////// // 2. Variables, Arrays and Objects -// Variables are declared with the var keyword. JavaScript is dynamically typed, -// so you don't need to specify type. Assignment uses a single = character. +// Variables are declared with the `var` keyword. JavaScript is dynamically +// typed, so you don't need to specify type. Assignment uses a single `=` +// character. var someVar = 5; // if you leave the var keyword off, you won't get an error... @@ -165,7 +166,7 @@ myArray.length; // = 4 // Add/Modify at specific index myArray[3] = "Hello"; -// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// JavaScript's objects are equivalent to "dictionaries" or "maps" in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; @@ -190,7 +191,7 @@ myObj.myFourthKey; // = undefined // The syntax for this section is almost identical to Java's. -// The if structure works as you'd expect. +// The `if` structure works as you'd expect. var count = 1; if (count == 3){ // evaluated if count is 3 @@ -200,7 +201,7 @@ if (count == 3){ // evaluated if it's not either 3 or 4 } -// As does while. +// As does `while`. while (true){ // An infinite loop! } @@ -211,7 +212,7 @@ do { input = getInput(); } while (!isValid(input)) -// the for loop is the same as C and Java: +// The `for` loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times @@ -229,7 +230,7 @@ if (colour == "red" || colour == "blue"){ var name = otherName || "default"; -// switch statement checks for equality with === +// The `switch` statement checks for equality with `===`. // use 'break' after each case // or the cases after the correct one will be executed too. grade = 'B'; @@ -252,14 +253,14 @@ switch (grade) { /////////////////////////////////// // 4. Functions, Scope and Closures -// JavaScript functions are declared with the function keyword. +// JavaScript functions are declared with the `function` keyword. function myFunction(thing){ return thing.toUpperCase(); } myFunction("foo"); // = "FOO" // Note that the value to be returned must start on the same line as the -// 'return' keyword, otherwise you'll always return 'undefined' due to +// `return` keyword, otherwise you'll always return `undefined` due to // automatic semicolon insertion. Watch out for this when using Allman style. function myFunction() { @@ -298,8 +299,8 @@ i; // = 5 - not undefined as you'd expect in a block-scoped language // scope. (function(){ var temporary = 5; - // We can access the global scope by assiging to the 'global object', which - // in a web browser is always 'window'. The global object may have a + // We can access the global scope by assiging to the "global object", which + // in a web browser is always `window`. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; })(); @@ -312,7 +313,7 @@ permanent; // = 10 function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; // Inner functions are put in the local scope by default, as if they were - // declared with 'var'. + // declared with `var`. function inner(){ alert(prompt); } @@ -320,7 +321,7 @@ function sayHelloInFiveSeconds(name){ // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has - // access to the 'prompt' variable when it is finally called. + // access to the `prompt` variable when it is finally called. } sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s @@ -336,7 +337,7 @@ var myObj = { myObj.myFunc(); // = "Hello world!" // When functions attached to an object are called, they can access the object -// they're attached to using the this keyword. +// they're attached to using the `this` keyword. myObj = { myString: "Hello world!", myFunc: function(){ @@ -352,7 +353,7 @@ var myFunc = myObj.myFunc; myFunc(); // = undefined // Inversely, a function can be assigned to the object and gain access to it -// through this, even if it wasn't attached when it was defined. +// through `this`, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); } @@ -360,37 +361,38 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // We can also specify a context for a function to execute in when we invoke it -// using 'call' or 'apply'. +// using `call` or `apply`. var anotherFunc = function(s){ return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// The 'apply' function is nearly identical, but takes an array for an argument list. +// The `apply` function is nearly identical, but takes an array for an argument +// list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -// This is useful when working with a function that accepts a sequence of arguments -// and you want to pass an array. +// This is useful when working with a function that accepts a sequence of +// arguments and you want to pass an array. Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use -// bind. +// But, `call` and `apply` are only temporary. When we want it to stick, we can +// use `bind`. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// Bind can also be used to partially apply (curry) a function. +// `bind` can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// When you call a function with the new keyword, a new object is created, and +// When you call a function with the `new` keyword, a new object is created, and // made available to the function via the this keyword. Functions designed to be // called like that are called constructors. -- cgit v1.2.3 From 08b0596e45feff0b292f295f52d82a80ab8624c2 Mon Sep 17 00:00:00 2001 From: Nimit Kalra Date: Wed, 25 Feb 2015 10:03:19 -0600 Subject: Add semicolon to maximine consistency. Added a semicolon to conform with statement at top of guide: // Because those cases can cause unexpected results, we'll keep on using // semicolons in this guide. --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index f61e6c74..95808d05 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -207,7 +207,7 @@ while (true){ } // Do-while loops are like while loops, except they always run at least once. -var input +var input; do { input = getInput(); } while (!isValid(input)) -- cgit v1.2.3 From 5e0964e2eee068b872fb0d61b5398997e0b76670 Mon Sep 17 00:00:00 2001 From: jasonqu Date: Fri, 6 Mar 2015 17:42:44 +0800 Subject: [javascript/zh] Translation tracking --- javascript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 95808d05..588ea86d 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -407,7 +407,7 @@ myNewObj.myNumber; // = 5 // look at its prototype. // Some JS implementations let you access an object's prototype on the magic -// property __proto__. While this is useful for explaining prototypes it's not +// property `__proto__`. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!" @@ -438,7 +438,7 @@ myObj.myBoolean; // = true myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// We mentioned that __proto__ was non-standard, and there's no standard way to +// We mentioned that `__proto__` was non-standard, and there's no standard way to // change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. -- cgit v1.2.3 From 87d0c402fb596c64a443a5374335508cb6941dc4 Mon Sep 17 00:00:00 2001 From: Philip Rowan Date: Thu, 1 Oct 2015 18:34:11 -0500 Subject: [javascript] Fix for issue 1248 https://github.com/adambard/learnxinyminutes-docs/issues/1248 --- javascript.html.markdown | 3 --- 1 file changed, 3 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index 588ea86d..ba2e8ce4 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -475,9 +475,6 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } -if (Number(0)){ - // This code *will* execute, because Number(0) is truthy. -} // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. -- cgit v1.2.3 From a793d16e3725bdaaf7ca40ff35a7cf0e1aba8488 Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Wed, 7 Oct 2015 22:22:12 -0400 Subject: remove extra whitespace, explain NaN --- javascript.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'javascript.html.markdown') diff --git a/javascript.html.markdown b/javascript.html.markdown index ba2e8ce4..754832f1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -64,7 +64,7 @@ doStuff() // There are three special not-a-real-number values: Infinity; // result of e.g. 1/0 -Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 +NaN; // result of e.g. 0/0, stands for 'Not a Number' // There's also a boolean type. true; @@ -189,7 +189,7 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures -// The syntax for this section is almost identical to Java's. +// The syntax for this section is almost identical to Java's. // The `if` structure works as you'd expect. var count = 1; @@ -231,8 +231,8 @@ var name = otherName || "default"; // The `switch` statement checks for equality with `===`. -// use 'break' after each case -// or the cases after the correct one will be executed too. +// use 'break' after each case +// or the cases after the correct one will be executed too. grade = 'B'; switch (grade) { case 'A': @@ -516,12 +516,12 @@ more about how to use JavaScript in web pages, start by learning about the [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts of the language. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. In addition to direct contributors to this article, some content is adapted from Louie Dinh's Python tutorial on this site, and the [JS -- cgit v1.2.3