JavaScript (which began as Netscape's Mocha) was created in 1995 by Brendan Eich to allow HTML developers to write scripts in their webpages. Read this article to learn about features and functionality that supported the early development of the language. These included a Java-like syntax, basic data types, and objects with classes.
Syntax and Basic Types
SYNTAX
statements like Java
• while, for, if, switch, try/catch, return, break, throw
comments
• use //, avoid /**/
semicolons
• inserted if omitted (yikes!)
declarations
• function scoping with var
functions
• are expressions; closures (yippee!)
var MAX = 10; var line = function (i, x) { var l = i + " times " + x + " is " + (i * x); return l; } var table = function (x) { for (var i = 1; i <= MAX; i += 1) { console.log(line(i, x)); } } // display times table for 3 table(3);
1 times 3 is 3
2 times 3 is 6
3 times 3 is 9
4 times 3 is 12
5 times 3 is 15
6 times 3 is 18
7 times 3 is 21
8 times 3 is 24
9 times 3 is 27
10 times 3 is 30
< undefined
>
BASIC TYPES
primitive types
• strings, numbers, booleans
•
operators autoconvert
> 1 + 2 3 > 1 + '2' "12" > 1 * 2 2 > 1 * '2' 2
arrays
• can grow, and have holes
funny values
• undefined: lookup non-existent thing
• null: special return value
> a = [] [] > a[2] = 'hello' "hello" > a.length 3 > a[1] undefined > a[2] "hello" > a[3] undefined
equality
• use ===, !==
> 1 === 1 true > 1.0 === 1 true >'hello' === 'hello' true > [] === [] false