adambard · GitHub

Jun 29, 2013

Jun 29, 2013

1

---

Dec 9, 2024

Dec 9, 2024

2

name: JavaScript

Sep 3, 2013

Sep 3, 2013

3

contributors:

Feb 13, 2020

Feb 13, 2020

4

- ["Leigh Brenecki", "https://leigh.net.au"]

Mar 10, 2014

Mar 10, 2014

5

- ["Ariel Krakowski", "http://www.learneroo.com"]

Sep 3, 2013

Sep 3, 2013

6

filename: javascript.js

Jun 29, 2013

Jun 29, 2013

7

---

8

Jan 22, 2014

Jan 22, 2014

9

JavaScript was created by Netscape's Brendan Eich in 1995. It was originally

Jun 10, 2014

Jun 10, 2014

10

intended as a simpler scripting language for websites, complementing the use of

Jun 30, 2013

Jun 30, 2013

11

Java for more complex web applications, but its tight integration with Web pages

12

and built-in support in browsers has caused it to become far more common than

13

Java in web frontends.

Jun 29, 2013

Jun 29, 2013

14

Jul 4, 2013

Jul 4, 2013

15

JavaScript isn't just limited to web browsers, though: Node.js, a project that

16

provides a standalone runtime for Google Chrome's V8 JavaScript engine, is

17

becoming more and more popular.

18

Oct 28, 2015

Oct 28, 2015

19

JavaScript has a C-like syntax, so if you've used languages like C or Java,

20

a lot of the basic syntax will already be familiar. Despite this, and despite

21

the similarity in name, JavaScript's object model is significantly different to

22

Java's.

23

Jul 4, 2013

Jul 4, 2013

24

```js

Oct 28, 2015

Oct 28, 2015

25

// Single-line comments start with two slashes.

26

/* Multiline comments start with slash-star,

Jun 29, 2013

Jun 29, 2013

27

and end with star-slash */

28

29

// Statements can be terminated by ;

30

doStuff();

31

32

// ... but they don't have to be, as semicolons are automatically inserted

33

// wherever there's a newline, except in certain cases.

34

doStuff()

35

Nov 26, 2013

Nov 26, 2013

36

// Because those cases can cause unexpected results, we'll keep on using

37

// semicolons in this guide.

Jun 29, 2013

Jun 29, 2013

38

Jul 4, 2013

Jul 4, 2013

39

///////////////////////////////////

40

// 1. Numbers, Strings and Operators

Jun 29, 2013

Jun 29, 2013

41

Jan 22, 2014

Jan 22, 2014

42

// JavaScript has one number type (which is a 64-bit IEEE 754 double).

Oct 28, 2014

Oct 28, 2014

43

// Doubles have a 52-bit mantissa, which is enough to store integers

Oct 28, 2015

Oct 28, 2015

44

// up to about 9✕10¹⁵ precisely.

Aug 15, 2013

Aug 15, 2013

45

3; // = 3

46

1.5; // = 1.5

Jun 29, 2013

Jun 29, 2013

47

Oct 28, 2014

Oct 28, 2014

48

// Some basic arithmetic works as you'd expect.

Aug 15, 2013

Aug 15, 2013

49

1 + 1; // = 2

Oct 30, 2014

Oct 30, 2014

50

0.1 + 0.2; // = 0.30000000000000004

Aug 15, 2013

Aug 15, 2013

51

8 - 1; // = 7

52

10 * 2; // = 20

53

35 / 5; // = 7

Jun 29, 2013

Jun 29, 2013

54

Jun 30, 2013

Jun 30, 2013

55

// Including uneven division.

Aug 15, 2013

Aug 15, 2013

56

5 / 2; // = 2.5

Jun 29, 2013

Jun 29, 2013

57

Oct 18, 2015

Oct 18, 2015

58

// And modulo division.

59

10 % 2; // = 0

60

30 % 4; // = 2

61

18.5 % 7; // = 4.5

62

Jul 3, 2013

Jul 3, 2013

63

// Bitwise operations also work; when you perform a bitwise operation your float

64

// is converted to a signed int *up to* 32 bits.

Aug 15, 2013

Aug 15, 2013

65

1 << 2; // = 4

Jul 3, 2013

Jul 3, 2013

66

Jul 4, 2013

Jul 4, 2013

67

// Precedence is enforced with parentheses.

Aug 15, 2013

Aug 15, 2013

68

(1 + 3) * 2; // = 8

Jun 29, 2013

Jun 29, 2013

69

Jun 30, 2013

Jun 30, 2013

70

// There are three special not-a-real-number values:

Aug 15, 2013

Aug 15, 2013

71

Infinity; // result of e.g. 1/0

72

-Infinity; // result of e.g. -1/0

Oct 8, 2015

Oct 8, 2015

73

NaN; // result of e.g. 0/0, stands for 'Not a Number'

Jun 30, 2013

Jun 30, 2013

74

Jun 29, 2013

Jun 29, 2013

75

// There's also a boolean type.

Aug 15, 2013

Aug 15, 2013

76

true;

77

false;

Jun 29, 2013

Jun 29, 2013

78

79

// Strings are created with ' or ".

Aug 15, 2013

Aug 15, 2013

80

'abc';

81

"Hello, world";

Jun 29, 2013

Jun 29, 2013

82

83

// Negation uses the ! symbol

Aug 15, 2013

Aug 15, 2013

84

!true; // = false

85

!false; // = true

Jun 29, 2013

Jun 29, 2013

86

Oct 27, 2014

Oct 27, 2014

87

// Equality is ===

88

1 === 1; // = true

89

2 === 1; // = false

Jun 29, 2013

Jun 29, 2013

90

Oct 27, 2014

Oct 27, 2014

91

// Inequality is !==

92

1 !== 1; // = false

93

2 !== 1; // = true

Jun 29, 2013

Jun 29, 2013

94

95

// More comparisons

Aug 15, 2013

Aug 15, 2013

96

1 < 10; // = true

97

1 > 10; // = false

98

2 <= 2; // = true

99

2 >= 2; // = true

Jun 29, 2013

Jun 29, 2013

100

101

// Strings are concatenated with +

Aug 15, 2013

Aug 15, 2013

102

"Hello " + "world!"; // = "Hello world!"

Jun 29, 2013

Jun 29, 2013

103

Oct 28, 2015

Oct 28, 2015

104

// ... which works with more than just strings

105

"1, 2, " + 3; // = "1, 2, 3"

Oct 27, 2017

Oct 27, 2017

106

"Hello " + ["world", "!"]; // = "Hello world,!"

Oct 28, 2015

Oct 28, 2015

107

Aug 25, 2023

Aug 25, 2023

108

// ...which can result in some weird behaviour...

109

13 + !0; // 14

110

"13" + !0; // '13true'

111

Jun 29, 2013

Jun 29, 2013

112

// and are compared with < and >

Aug 15, 2013

Aug 15, 2013

113

"a" < "b"; // = true

Jun 29, 2013

Jun 29, 2013

114

Oct 27, 2014

Oct 27, 2014

115

// Type coercion is performed for comparisons with double equals...

Aug 15, 2013

Aug 15, 2013

116

"5" == 5; // = true

Oct 27, 2014

Oct 27, 2014

117

null == undefined; // = true

Jun 29, 2013

Jun 29, 2013

118

Jun 30, 2013

Jun 30, 2013

119

// ...unless you use ===

Aug 15, 2013

Aug 15, 2013

120

"5" === 5; // = false

Oct 18, 2015

Oct 18, 2015

121

null === undefined; // = false

Jun 29, 2013

Jun 29, 2013

122

Feb 3, 2015

Feb 3, 2015

123

// You can access characters in a string with `charAt`

Mar 10, 2014

Mar 10, 2014

124

"This is a string".charAt(0); // = 'T'

125

Feb 3, 2015

Feb 3, 2015

126

// ...or use `substring` to get larger pieces.

Mar 10, 2014

Mar 10, 2014

127

"Hello world".substring(0, 5); // = "Hello"

128

Feb 3, 2015

Feb 3, 2015

129

// `length` is a property, so don't use ().

Mar 10, 2014

Mar 10, 2014

130

"Hello".length; // = 5

Jun 29, 2013

Jun 29, 2013

131

Feb 3, 2015

Feb 3, 2015

132

// There's also `null` and `undefined`.

133

null; // used to indicate a deliberate non-value

Nov 5, 2013

Nov 5, 2013

134

undefined; // used to indicate a value is not currently present (although

Feb 3, 2015

Feb 3, 2015

135

// `undefined` is actually a value itself)

Jun 30, 2013

Jun 30, 2013

136

Nov 5, 2013

Nov 5, 2013

137

// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy.

Jun 30, 2013

Jun 30, 2013

138

// Note that 0 is falsy and "0" is truthy, even though 0 == "0".

Jun 29, 2013

Jun 29, 2013

139

Jul 4, 2013

Jul 4, 2013

140

///////////////////////////////////

Mar 1, 2017

Mar 1, 2017

141

// 2. Variables, Arrays and Objects

Jun 29, 2013

Jun 29, 2013

142

Feb 3, 2015

Feb 3, 2015

143

// Variables are declared with the `var` keyword. JavaScript is dynamically

144

// typed, so you don't need to specify type. Assignment uses a single `=`

145

// character.

Aug 15, 2013

Aug 15, 2013

146

var someVar = 5;

Jun 29, 2013

Jun 29, 2013

147

Oct 28, 2015

Oct 28, 2015

148

// If you leave the var keyword off, you won't get an error...

Aug 15, 2013

Aug 15, 2013

149

someOtherVar = 10;

Jun 29, 2013

Jun 29, 2013

150

Jun 30, 2013

Jun 30, 2013

151

// ...but your variable will be created in the global scope, not in the scope

152

// you defined it in.

153

154

// Variables declared without being assigned to are set to undefined.

Aug 15, 2013

Aug 15, 2013

155

var someThirdVar; // = undefined

Jun 29, 2013

Jun 29, 2013

156

Oct 28, 2015

Oct 28, 2015

157

// If you want to declare a couple of variables, then you could use a comma

Oct 15, 2015

Oct 15, 2015

158

// separator

159

var someFourthVar = 2, someFifthVar = 4;

160

Jun 30, 2013

Jun 30, 2013

161

// There's shorthand for performing math operations on variables:

Aug 15, 2013

Aug 15, 2013

162

someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now

163

someVar *= 10; // now someVar is 100

Jun 30, 2013

Jun 30, 2013

164

165

// and an even-shorter-hand for adding or subtracting 1

Aug 15, 2013

Aug 15, 2013

166

someVar++; // now someVar is 101

167

someVar--; // back to 100

Jun 30, 2013

Jun 30, 2013

168

Jun 29, 2013

Jun 29, 2013

169

// Arrays are ordered lists of values, of any type.

Aug 15, 2013

Aug 15, 2013

170

var myArray = ["Hello", 45, true];

Jun 30, 2013

Jun 30, 2013

171

172

// Their members can be accessed using the square-brackets subscript syntax.

173

// Array indices start at zero.

Aug 15, 2013

Aug 15, 2013

174

myArray[1]; // = 45

Jun 29, 2013

Jun 29, 2013

175

Oct 9, 2013

Oct 9, 2013

176

// Arrays are mutable and of variable length.

177

myArray.push("World");

178

myArray.length; // = 4

179

Mar 10, 2014

Mar 10, 2014

180

// Add/Modify at specific index

181

myArray[3] = "Hello";

182

Oct 31, 2017

Oct 31, 2017

183

// Add and remove element from front or back end of an array

184

myArray.unshift(3); // Add as the first element

185

someVar = myArray.shift(); // Remove first element and return it

186

myArray.push(3); // Add as the last element

187

someVar = myArray.pop(); // Remove last element and return it

188

Nov 12, 2017

Nov 12, 2017

189

// Join all elements of an array with semicolon

Oct 31, 2017

Oct 31, 2017

190

var myArray0 = [32,false,"js",12,56,90];

Dec 28, 2019

Dec 28, 2019

191

myArray0.join(";"); // = "32;false;js;12;56;90"

Oct 31, 2017

Oct 31, 2017

192

193

// Get subarray of elements from index 1 (include) to 4 (exclude)

194

myArray0.slice(1,4); // = [false,"js",12]

195

Jun 29, 2026

Jun 29, 2026

196

// Remove 4 elements starting from index 2, and insert three strings

Nov 12, 2017

Nov 12, 2017

197

// "hi","wr" and "ld"; return removed subarray

198

myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90]

199

// myArray0 === [32,false,"hi","wr","ld"]

Oct 31, 2017

Oct 31, 2017

200

Feb 3, 2015

Feb 3, 2015

201

// JavaScript's objects are equivalent to "dictionaries" or "maps" in other

Jun 29, 2013

Jun 29, 2013

202

// languages: an unordered collection of key-value pairs.

Aug 15, 2013

Aug 15, 2013

203

var myObj = {key1: "Hello", key2: "World"};

Jun 29, 2013

Jun 29, 2013

204

205

// Keys are strings, but quotes aren't required if they're a valid

206

// JavaScript identifier. Values can be any type.

Aug 15, 2013

Aug 15, 2013

207

var myObj = {myKey: "myValue", "my other key": 4};

Jun 29, 2013

Jun 29, 2013

208

Jun 30, 2013

Jun 30, 2013

209

// Object attributes can also be accessed using the subscript syntax,

Aug 15, 2013

Aug 15, 2013

210

myObj["my other key"]; // = 4

Jun 29, 2013

Jun 29, 2013

211

212

// ... or using the dot syntax, provided the key is a valid identifier.

Aug 15, 2013

Aug 15, 2013

213

myObj.myKey; // = "myValue"

Jun 29, 2013

Jun 29, 2013

214

Jun 30, 2013

Jun 30, 2013

215

// Objects are mutable; values can be changed and new keys added.

Aug 15, 2013

Aug 15, 2013

216

myObj.myThirdKey = true;

Jun 29, 2013

Jun 29, 2013

217

Jun 30, 2013

Jun 30, 2013

218

// If you try to access a value that's not yet set, you'll get undefined.

Aug 15, 2013

Aug 15, 2013

219

myObj.myFourthKey; // = undefined

Jun 30, 2013

Jun 30, 2013

220

Jul 4, 2013

Jul 4, 2013

221

///////////////////////////////////

222

// 3. Logic and Control Structures

Jun 29, 2013

Jun 29, 2013

223

Feb 3, 2015

Feb 3, 2015

224

// The `if` structure works as you'd expect.

Aug 15, 2013

Aug 15, 2013

225

var count = 1;

Jun 30, 2013

Jun 30, 2013

226

if (count == 3){

227

// evaluated if count is 3

Jan 19, 2014

Jan 19, 2014

228

} else if (count == 4){

Jun 30, 2013

Jun 30, 2013

229

// evaluated if count is 4

230

} else {

Jul 3, 2013

Jul 3, 2013

231

// evaluated if it's not either 3 or 4

Jun 30, 2013

Jun 30, 2013

232

}

233

Feb 3, 2015

Feb 3, 2015

234

// As does `while`.

Jan 19, 2014

Jan 19, 2014

235

while (true){

Jun 30, 2013

Jun 30, 2013

236

// An infinite loop!

237

}

238

239

// Do-while loops are like while loops, except they always run at least once.

Feb 25, 2015

Feb 25, 2015

240

var input;

Jun 30, 2013

Jun 30, 2013

241

do {

Aug 15, 2013

Aug 15, 2013

242

input = getInput();

Oct 27, 2017

Oct 27, 2017

243

} while (!isValid(input));

Jun 30, 2013

Jun 30, 2013

244

Feb 3, 2015

Feb 3, 2015

245

// The `for` loop is the same as C and Java:

Feb 24, 2017

Feb 24, 2017

246

// initialization; continue condition; iteration.

Jun 30, 2013

Jun 30, 2013

247

for (var i = 0; i < 5; i++){

248

// will run 5 times

249

}

250

Oct 30, 2016

Oct 30, 2016

251

// Breaking out of labeled loops is similar to Java

252

outer:

253

for (var i = 0; i < 10; i++) {

254

for (var j = 0; j < 10; j++) {

255

if (i == 5 && j ==5) {

256

break outer;

257

// breaks out of outer loop instead of only the inner one

258

}

259

}

260

}

261

Feb 24, 2017

Feb 24, 2017

262

// The for/in statement allows iteration over properties of an object.

Oct 6, 2015

Oct 6, 2015

263

var description = "";

Oct 18, 2015

Oct 18, 2015

264

var person = {fname:"Paul", lname:"Ken", age:18};

Oct 8, 2015

Oct 8, 2015

265

for (var x in person){

Oct 6, 2015

Oct 6, 2015

266

description += person[x] + " ";

Feb 24, 2017

Feb 24, 2017

267

} // description = 'Paul Ken 18 '

Oct 6, 2015

Oct 6, 2015

268

Jul 1, 2018

Jul 1, 2018

269

// The for/of statement allows iteration over iterable objects (including the built-in String,

270

// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set,

271

// and user-defined iterables).

Jul 1, 2018

Jul 1, 2018

272

var myPets = "";

273

var pets = ["cat", "dog", "hamster", "hedgehog"];

274

for (var pet of pets){

275

myPets += pet + " ";

276

} // myPets = 'cat dog hamster hedgehog '

277

Jun 30, 2013

Jun 30, 2013

278

// && is logical and, || is logical or

279

if (house.size == "big" && house.colour == "blue"){

Aug 15, 2013

Aug 15, 2013

280

house.contains = "bear";

Jun 30, 2013

Jun 30, 2013

281

}

282

if (colour == "red" || colour == "blue"){

283

// colour is either red or blue

284

}

285

Jul 3, 2013

Jul 3, 2013

286

// && and || "short circuit", which is useful for setting default values.

Aug 15, 2013

Aug 15, 2013

287

var name = otherName || "default";

Jun 30, 2013

Jun 30, 2013

288

Feb 3, 2015

Feb 3, 2015

289

// The `switch` statement checks for equality with `===`.

Oct 28, 2015

Oct 28, 2015

290

// Use 'break' after each case

Oct 8, 2015

Oct 8, 2015

291

// or the cases after the correct one will be executed too.

Mar 10, 2014

Mar 10, 2014

292

grade = 'B';

293

switch (grade) {

294

case 'A':

295

console.log("Great job");

296

break;

297

case 'B':

298

console.log("OK job");

299

break;

300

case 'C':

301

console.log("You can do better");

302

break;

303

default:

304

console.log("Oy vey");

305

break;

306

}

307

308

Jul 4, 2013

Jul 4, 2013

309

///////////////////////////////////

310

// 4. Functions, Scope and Closures

Jun 29, 2013

Jun 29, 2013

311

Feb 3, 2015

Feb 3, 2015

312

// JavaScript functions are declared with the `function` keyword.

Jul 4, 2013

Jul 4, 2013

313

function myFunction(thing){

Aug 15, 2013

Aug 15, 2013

314

return thing.toUpperCase();

Jul 4, 2013

Jul 4, 2013

315

}

Aug 15, 2013

Aug 15, 2013

316

myFunction("foo"); // = "FOO"

Jul 4, 2013

Jul 4, 2013

317

Nov 26, 2013

Nov 26, 2013

318

// Note that the value to be returned must start on the same line as the

Feb 3, 2015

Feb 3, 2015

319

// `return` keyword, otherwise you'll always return `undefined` due to

Nov 26, 2013

Nov 26, 2013

320

// automatic semicolon insertion. Watch out for this when using Allman style.

Oct 19, 2015

Oct 19, 2015

321

function myFunction(){

Nov 26, 2013

Nov 26, 2013

322

return // <- semicolon automatically inserted here

Oct 27, 2017

Oct 27, 2017

323

{thisIsAn: 'object literal'};

Nov 26, 2013

Nov 26, 2013

324

}

325

myFunction(); // = undefined

326

Jul 4, 2013

Jul 4, 2013

327

// JavaScript functions are first class objects, so they can be reassigned to

328

// different variable names and passed to other functions as arguments - for

329

// example, when supplying an event handler:

330

function myFunction(){

331

// this code will be called in 5 seconds' time

332

}

Aug 15, 2013

Aug 15, 2013

333

setTimeout(myFunction, 5000);

Sep 13, 2013

Sep 13, 2013

334

// Note: setTimeout isn't part of the JS language, but is provided by browsers

335

// and Node.js.

Jul 4, 2013

Jul 4, 2013

336

Oct 19, 2015

Oct 19, 2015

337

// Another function provided by browsers is setInterval

338

function myFunction(){

339

// this code will be called every 5 seconds

340

}

Oct 19, 2015

Oct 19, 2015

341

setInterval(myFunction, 5000);

Oct 19, 2015

Oct 19, 2015

342

Aug 15, 2013

Aug 15, 2013

343

// Function objects don't even have to be declared with a name - you can write

344

// an anonymous function definition directly into the arguments of another.

345

setTimeout(function(){

Jul 4, 2013

Jul 4, 2013

346

// this code will be called in 5 seconds' time

Aug 15, 2013

Aug 15, 2013

347

}, 5000);

Jul 4, 2013

Jul 4, 2013

348

349

// JavaScript has function scope; functions get their own scope but other blocks

350

// do not.

351

if (true){

Aug 15, 2013

Aug 15, 2013

352

var i = 5;

Jul 4, 2013

Jul 4, 2013

353

}

Aug 15, 2013

Aug 15, 2013

354

i; // = 5 - not undefined as you'd expect in a block-scoped language

Jul 4, 2013

Jul 4, 2013

355

356

// This has led to a common pattern of "immediately-executing anonymous

357

// functions", which prevent temporary variables from leaking into the global

358

// scope.

Aug 5, 2013

Aug 5, 2013

359

(function(){

Aug 15, 2013

Aug 15, 2013

360

var temporary = 5;

Oct 18, 2015

Oct 18, 2015

361

// We can access the global scope by assigning to the "global object", which

Feb 3, 2015

Feb 3, 2015

362

// in a web browser is always `window`. The global object may have a

Jul 4, 2013

Jul 4, 2013

363

// different name in non-browser environments such as Node.js.

Aug 15, 2013

Aug 15, 2013

364

window.permanent = 10;

365

})();

366

temporary; // raises ReferenceError

367

permanent; // = 10

Jul 4, 2013

Jul 4, 2013

368

369

// One of JavaScript's most powerful features is closures. If a function is

370

// defined inside another function, the inner function has access to all the

Aug 14, 2013

Aug 14, 2013

371

// outer function's variables, even after the outer function exits.

Jul 4, 2013

Jul 4, 2013

372

function sayHelloInFiveSeconds(name){

Aug 15, 2013

Aug 15, 2013

373

var prompt = "Hello, " + name + "!";

Dec 14, 2013

Dec 14, 2013

374

// Inner functions are put in the local scope by default, as if they were

Feb 3, 2015

Feb 3, 2015

375

// declared with `var`.

Jul 4, 2013

Jul 4, 2013

376

function inner(){

Aug 15, 2013

Aug 15, 2013

377

alert(prompt);

Jul 4, 2013

Jul 4, 2013

378

}

Aug 15, 2013

Aug 15, 2013

379

setTimeout(inner, 5000);

Aug 14, 2013

Aug 14, 2013

380

// setTimeout is asynchronous, so the sayHelloInFiveSeconds function will

381

// exit immediately, and setTimeout will call inner afterwards. However,

382

// because inner is "closed over" sayHelloInFiveSeconds, inner still has

Feb 3, 2015

Feb 3, 2015

383

// access to the `prompt` variable when it is finally called.

Jul 4, 2013

Jul 4, 2013

384

}

Aug 15, 2013

Aug 15, 2013

385

sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s

Jul 4, 2013

Jul 4, 2013

386

Jul 4, 2013

Jul 4, 2013

387

///////////////////////////////////

388

// 5. More about Objects; Constructors and Prototypes

Jun 29, 2013

Jun 29, 2013

389

Jun 30, 2013

Jun 30, 2013

390

// Objects can contain functions.

391

var myObj = {

Jun 29, 2013

Jun 29, 2013

392

myFunc: function(){

Aug 15, 2013

Aug 15, 2013

393

return "Hello world!";

Jun 29, 2013

Jun 29, 2013

394

}

Aug 15, 2013

Aug 15, 2013

395

};

396

myObj.myFunc(); // = "Hello world!"

Jun 29, 2013

Jun 29, 2013

397

Jun 30, 2013

Jun 30, 2013

398

// When functions attached to an object are called, they can access the object

Feb 3, 2015

Feb 3, 2015

399

// they're attached to using the `this` keyword.

Jun 29, 2013

Jun 29, 2013

400

myObj = {

401

myString: "Hello world!",

402

myFunc: function(){

Aug 15, 2013

Aug 15, 2013

403

return this.myString;

Jun 29, 2013

Jun 29, 2013

404

}

Aug 15, 2013

Aug 15, 2013

405

};

406

myObj.myFunc(); // = "Hello world!"

Jun 29, 2013

Jun 29, 2013

407

Mar 14, 2024

Mar 14, 2024

408

// What `this` is set to has to do with how the function is called, not where

Jun 30, 2013

Jun 30, 2013

409

// it's defined. So, our function doesn't work if it isn't called in the

410

// context of the object.

Aug 15, 2013

Aug 15, 2013

411

var myFunc = myObj.myFunc;

412

myFunc(); // = undefined

Jun 29, 2013

Jun 29, 2013

413

414

// Inversely, a function can be assigned to the object and gain access to it

Feb 3, 2015

Feb 3, 2015

415

// through `this`, even if it wasn't attached when it was defined.

Jun 29, 2013

Jun 29, 2013

416

var myOtherFunc = function(){

Aug 15, 2013

Aug 15, 2013

417

return this.myString.toUpperCase();

Oct 27, 2017

Oct 27, 2017

418

};

Aug 15, 2013

Aug 15, 2013

419

myObj.myOtherFunc = myOtherFunc;

420

myObj.myOtherFunc(); // = "HELLO WORLD!"

Jun 29, 2013

Jun 29, 2013

421

Dec 27, 2013

Dec 27, 2013

422

// We can also specify a context for a function to execute in when we invoke it

Feb 3, 2015

Feb 3, 2015

423

// using `call` or `apply`.

Dec 27, 2013

Dec 27, 2013

424

425

var anotherFunc = function(s){

426

return this.myString + s;

Oct 27, 2017

Oct 27, 2017

427

};

Dec 27, 2013

Dec 27, 2013

428

anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"

429

Feb 3, 2015

Feb 3, 2015

430

// The `apply` function is nearly identical, but takes an array for an argument

431

// list.

Dec 27, 2013

Dec 27, 2013

432

433

anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"

434

Feb 3, 2015

Feb 3, 2015

435

// This is useful when working with a function that accepts a sequence of

436

// arguments and you want to pass an array.

Dec 27, 2013

Dec 27, 2013

437

438

Math.min(42, 6, 27); // = 6

439

Math.min([42, 6, 27]); // = NaN (uh-oh!)

440

Math.min.apply(Math, [42, 6, 27]); // = 6

441

Feb 3, 2015

Feb 3, 2015

442

// But, `call` and `apply` are only temporary. When we want it to stick, we can

443

// use `bind`.

Dec 27, 2013

Dec 27, 2013

444

445

var boundFunc = anotherFunc.bind(myObj);

446

boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"

447

Feb 3, 2015

Feb 3, 2015

448

// `bind` can also be used to partially apply (curry) a function.

Dec 27, 2013

Dec 27, 2013

449

Oct 27, 2017

Oct 27, 2017

450

var product = function(a, b){ return a * b; };

Dec 27, 2013

Dec 27, 2013

451

var doubler = product.bind(this, 2);

452

doubler(8); // = 16

453

Feb 3, 2015

Feb 3, 2015

454

// When you call a function with the `new` keyword, a new object is created, and

Oct 16, 2015

Oct 16, 2015

455

// made available to the function via the `this` keyword. Functions designed to be

Nov 5, 2013

Nov 5, 2013

456

// called like that are called constructors.

Jun 29, 2013

Jun 29, 2013

457

458

var MyConstructor = function(){

Aug 15, 2013

Aug 15, 2013

459

this.myNumber = 5;

Oct 27, 2017

Oct 27, 2017

460

};

Aug 15, 2013

Aug 15, 2013

461

myNewObj = new MyConstructor(); // = {myNumber: 5}

462

myNewObj.myNumber; // = 5

Jun 29, 2013

Jun 29, 2013

463

Oct 27, 2017

Oct 27, 2017

464

// Unlike most other popular object-oriented languages, JavaScript has no

Mar 1, 2017

Mar 1, 2017

465

// concept of 'instances' created from 'class' blueprints; instead, JavaScript

466

// combines instantiation and inheritance into a single concept: a 'prototype'.

467

Jun 30, 2013

Jun 30, 2013

468

// Every JavaScript object has a 'prototype'. When you go to access a property

469

// on an object that doesn't exist on the actual object, the interpreter will

470

// look at its prototype.

471

472

// Some JS implementations let you access an object's prototype on the magic

Mar 6, 2015

Mar 6, 2015

473

// property `__proto__`. While this is useful for explaining prototypes it's not

Jun 30, 2013

Jun 30, 2013

474

// part of the standard; we'll get to standard ways of using prototypes later.

475

var myObj = {

Nov 2, 2013

Nov 2, 2013

476

myString: "Hello world!"

Aug 15, 2013

Aug 15, 2013

477

};

Jun 29, 2013

Jun 29, 2013

478

var myPrototype = {

479

meaningOfLife: 42,

Jun 30, 2013

Jun 30, 2013

480

myFunc: function(){

Oct 27, 2017

Oct 27, 2017

481

return this.myString.toLowerCase();

Jun 29, 2013

Jun 29, 2013

482

}

Nov 3, 2013

Nov 3, 2013

483

};

Nov 2, 2013

Nov 2, 2013

484

Aug 15, 2013

Aug 15, 2013

485

myObj.__proto__ = myPrototype;

486

myObj.meaningOfLife; // = 42

Jun 30, 2013

Jun 30, 2013

487

488

// This works for functions, too.

Aug 15, 2013

Aug 15, 2013

489

myObj.myFunc(); // = "hello world!"

Jun 29, 2013

Jun 29, 2013

490

491

// Of course, if your property isn't on your prototype, the prototype's

492

// prototype is searched, and so on.

493

myPrototype.__proto__ = {

494

myBoolean: true

Aug 15, 2013

Aug 15, 2013

495

};

496

myObj.myBoolean; // = true

Jun 29, 2013

Jun 29, 2013

497

498

// There's no copying involved here; each object stores a reference to its

499

// prototype. This means we can alter the prototype and our changes will be

500

// reflected everywhere.

Aug 15, 2013

Aug 15, 2013

501

myPrototype.meaningOfLife = 43;

502

myObj.meaningOfLife; // = 43

Jun 30, 2013

Jun 30, 2013

503

Feb 24, 2017

Feb 24, 2017

504

// The for/in statement allows iteration over properties of an object,

505

// walking up the prototype chain until it sees a null prototype.

506

for (var x in myObj){

507

console.log(myObj[x]);

508

}

509

///prints:

510

// Hello world!

Jun 8, 2017

Jun 8, 2017

511

// 43

Feb 24, 2017

Feb 24, 2017

512

// [Function: myFunc]

Jan 21, 2019

Jan 21, 2019

513

// true

Feb 24, 2017

Feb 24, 2017

514

515

// To only consider properties attached to the object itself

516

// and not its prototypes, use the `hasOwnProperty()` check.

517

for (var x in myObj){

518

if (myObj.hasOwnProperty(x)){

519

console.log(myObj[x]);

520

}

521

}

522

///prints:

523

// Hello world!

524

Mar 6, 2015

Mar 6, 2015

525

// We mentioned that `__proto__` was non-standard, and there's no standard way to

Aug 19, 2013

Aug 19, 2013

526

// change the prototype of an existing object. However, there are two ways to

Jul 3, 2013

Jul 3, 2013

527

// create a new object with a given prototype.

Jun 29, 2013

Jun 29, 2013

528

Jun 30, 2013

Jun 30, 2013

529

// The first is Object.create, which is a recent addition to JS, and therefore

530

// not available in all implementations yet.

Aug 15, 2013

Aug 15, 2013

531

var myObj = Object.create(myPrototype);

532

myObj.meaningOfLife; // = 43

Jun 29, 2013

Jun 29, 2013

533

Jul 3, 2013

Jul 3, 2013

534

// The second way, which works anywhere, has to do with constructors.

535

// Constructors have a property called prototype. This is *not* the prototype of

536

// the constructor function itself; instead, it's the prototype that new objects

537

// are given when they're created with that constructor and the new keyword.

Oct 3, 2013

Oct 3, 2013

538

MyConstructor.prototype = {

Sep 20, 2013

Sep 20, 2013

539

myNumber: 5,

Jul 3, 2013

Jul 3, 2013

540

getMyNumber: function(){

Sep 20, 2013

Sep 20, 2013

541

return this.myNumber;

Jul 3, 2013

Jul 3, 2013

542

}

Aug 15, 2013

Aug 15, 2013

543

};

Oct 3, 2013

Oct 3, 2013

544

var myNewObj2 = new MyConstructor();

Aug 15, 2013

Aug 15, 2013

545

myNewObj2.getMyNumber(); // = 5

Oct 27, 2017

Oct 27, 2017

546

myNewObj2.myNumber = 6;

Sep 20, 2013

Sep 20, 2013

547

myNewObj2.getMyNumber(); // = 6

Jul 3, 2013

Jul 3, 2013

548

549

// Built-in types like strings and numbers also have constructors that create

550

// equivalent wrapper objects.

Aug 15, 2013

Aug 15, 2013

551

var myNumber = 12;

552

var myNumberObj = new Number(12);

553

myNumber == myNumberObj; // = true

Jul 3, 2013

Jul 3, 2013

554

555

// Except, they aren't exactly equivalent.

Aug 9, 2014

Aug 9, 2014

556

typeof myNumber; // = 'number'

557

typeof myNumberObj; // = 'object'

Aug 15, 2013

Aug 15, 2013

558

myNumber === myNumberObj; // = false

Jul 3, 2013

Jul 3, 2013

559

if (0){

560

// This code won't execute, because 0 is falsy.

561

}

Oct 28, 2015

Oct 28, 2015

562

if (new Number(0)){

563

// This code will execute, because wrapped numbers are objects, and objects

564

// are always truthy.

565

}

Jun 29, 2013

Jun 29, 2013

566

Jul 3, 2013

Jul 3, 2013

567

// However, the wrapper objects and the regular builtins share a prototype, so

568

// you can actually add functionality to a string, for instance.

Jun 29, 2013

Jun 29, 2013

569

String.prototype.firstCharacter = function(){

Aug 15, 2013

Aug 15, 2013

570

return this.charAt(0);

Oct 27, 2017

Oct 27, 2017

571

};

Aug 15, 2013

Aug 15, 2013

572

"abc".firstCharacter(); // = "a"

Jun 29, 2013

Jun 29, 2013

573

Jul 3, 2013

Jul 3, 2013

574

// This fact is often used in "polyfilling", which is implementing newer

575

// features of JavaScript in an older subset of JavaScript, so that they can be

576

// used in older environments such as outdated browsers.

Jun 30, 2013

Jun 30, 2013

577

578

// For instance, we mentioned that Object.create isn't yet available in all

Jul 3, 2013

Jul 3, 2013

579

// implementations, but we can still use it with this polyfill:

580

if (Object.create === undefined){ // don't overwrite it if it exists

Jun 30, 2013

Jun 30, 2013

581

Object.create = function(proto){

582

// make a temporary constructor with the right prototype

Aug 15, 2013

Aug 15, 2013

583

var Constructor = function(){};

584

Constructor.prototype = proto;

Jul 3, 2013

Jul 3, 2013

585

// then use it to create a new, appropriately-prototyped object

Aug 15, 2013

Aug 15, 2013

586

return new Constructor();

Oct 27, 2017

Oct 27, 2017

587

};

Jun 30, 2013

Jun 30, 2013

588

}

Sep 30, 2019

Sep 30, 2019

589

590

// ES6 Additions

591

592

// The "let" keyword allows you to define variables in a lexical scope,

Jan 3, 2022

Jan 3, 2022

593

// as opposed to a function scope like the var keyword does.

Sep 30, 2019

Sep 30, 2019

594

let name = "Billy";

595

596

// Variables defined with let can be reassigned new values.

597

name = "William";

598

599

// The "const" keyword allows you to define a variable in a lexical scope

600

// like with let, but you cannot reassign the value once one has been assigned.

601

602

const pi = 3.14;

603

604

pi = 4.13; // You cannot do this.

605

606

// There is a new syntax for functions in ES6 known as "lambda syntax".

607

// This allows functions to be defined in a lexical scope like with variables

608

// defined by const and let.

609

610

const isEven = (number) => {

611

return number % 2 === 0;

612

};

613

614

isEven(7); // false

615

616

// The "equivalent" of this function in the traditional syntax would look like this:

617

618

function isEven(number) {

619

return number % 2 === 0;

620

};

621

622

// I put the word "equivalent" in double quotes because a function defined

Dec 10, 2022

Dec 10, 2022

623

// using the lambda syntax cannot be called before the definition.

Sep 30, 2019

Sep 30, 2019

624

// The following is an example of invalid usage:

625

626

add(1, 8);

627

628

const add = (firstNumber, secondNumber) => {

629

return firstNumber + secondNumber;

630

};

Jun 29, 2013

Jun 29, 2013

631

```

Jun 30, 2013

Jun 30, 2013

632

633

## Further Reading

634

Feb 22, 2025

Feb 22, 2025

635

The [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) (MDN) provides excellent documentation for

636

JavaScript as it's used in browsers.

Oct 23, 2015

Oct 23, 2015

637

Feb 22, 2025

Feb 22, 2025

638

MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) covers much of the concepts covered

Oct 23, 2015

Oct 23, 2015

639

here in more detail. This guide has quite deliberately only covered the

640

JavaScript language itself; if you want to learn more about how to use

Feb 22, 2025

Feb 22, 2025

641

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).

Oct 23, 2015

Oct 23, 2015

642

Feb 22, 2025

Feb 22, 2025

643

[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts

Oct 23, 2015

Oct 23, 2015

644

of the language.

Jul 4, 2013

Jul 4, 2013

645

Feb 22, 2025

Feb 22, 2025

646

[JavaScript: The Definitive Guide](https://www.amazon.com/gp/product/0596805527/) is a classic guide and reference book.

Mar 10, 2014

Mar 10, 2014

647

Feb 22, 2025

Feb 22, 2025

648

[Eloquent JavaScript](https://eloquentjavascript.net/) by Marijn Haverbeke is an excellent JS book/ebook with

Feb 24, 2017

Feb 24, 2017

649

attached terminal

Oct 31, 2015

Oct 31, 2015

650

Feb 22, 2025

Feb 22, 2025

651

[javascript.info](https://javascript.info/) is a modern JavaScript tutorial covering the basics (core language and working with a browser)

Feb 22, 2025

Feb 22, 2025

652

as well as advanced topics with concise explanations.

Read the original on github.com ↗