background-image: url(../images/codecamp.png) background-color: #cacaca --- class: center, middle # Intro to JavaScript ## Part I: "Vanilla" JS --- ## Some JS History - Created in 10 days in 1995 as a language to be embedded in web browsers. -- - Has no explicit relationship to Java; using "Java" as part of the name was likely a marketing ploy. -- - JS is the only universally, natively-supported client-side/browser language. -- - For most of its history, JS was a browser-only language. More recently, the Node.js platform has led to widespread usage of JS as a server-side language. -- - In 2008, a young programmer named Chris Bay wrote a browser-based XML code editor in JavaScript that was capable of editing 20,000-line files, and ran in IE6 (quite possibley the worst browser ever). He still has the mental scars. --- ## High-level Characteristics - C-style language: brackets, parens, semicolons, and comments follow conventions of C, C++, Java, etc. -- - Dynamically typed -- - Object-oriented (prototype-based) -- - Functional -- - Interpreted -- - Has some quirks (we'll see some of these as we go) -- - The official standard defining JS is ECMAScript --- ## What JS Can Do - Manipulate the contents of web pages, including HTML and CSS -- - Make HTTP requests from a browser to a server -- - Respond to user actions --- ## What JS Can't Do* - Access resources outside the browser (e.g. reading/writing from/to files) -- - Run in multiple threads (most of the time) -- - Talk to databases -- - Make HTTP requests to a servers other than where the page originated, subject to some workaroudns ([same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)) -- - Give good error messages (get used to `undefined is not a function`) -- \* These rules all change when using Node.js. As a general note, in this lesson we'll be talking about ECMAScript 5 (ES5) running in the browser. --- ## Some Basics ```js // Prints to the "console" console.log("Hello, world!"); // Double and single quotes are interchangeable console.log('Hello, world!'); // Semi-colons are optional but should always be used! // This works, but you shouldn't do it! console.log('Hello, world!') ``` --- ## Data and Variables ## Declaration ```js // declare a "local" variable var a = 5; // declare a global variable; DON'T DO THIS b = 7; // declare without initializing var c; // declare multiple vars at once var d, e, f; ``` --- ## Data Types JS has 6 data types: boolean, null, undefined, number, string, object -- Variables are dynamically typed ```js var a = 5; typeof(a); // returns 'number' a = 'dog'; typeof(a); // returns 'string' var b; typeof(b); // returns 'undefined' typeof(true); // returns 'boolean' ``` --- ## Operators  --- ## Operators  --- ## Operators  --- ## == vs === == is "fuzzy" ```js // These each evaluate to true 0 == '' 0 == false 1 == true '' == false 1 == '1' undefined == null ``` --- ## == vs === === is "strict" ```js // These each evaluat to false 0 === '' 0 === false 1 === true '' === false 1 === '1' undefined === null ``` --- ## Stuff Gets Weird == is not transitive! ```js // These are true '' == 0 0 == '0' // Yet this is false '' == '0' ``` -- Implicit conversions don't work as you might expect ```js '5' + 3 // evalutes to '53' '5' - 3 // evalutes to 2 ``` --- ## Arrays ```js var magicNumbers = [42, 1, 6, 3]; console.log(magicNumbers[2]); // prints 6 console.log(magicNumbers.length); // append an item magicNumbers.push(7); // remove and return the last item magicNumbers.pop(); ``` --- ## Objects ```js var grades = {'chris': 3, 'sally': 4, 'haley': 3.5}; console.log(grades['haley']); // prints 3.5 grades["mike"] = 3.2; ``` -- ### Note JS objects are an amalgam of the concepts of maps and objects, as you've seen them in Java and Python. They are very rich and complex, but we'll only use them in simple ways here. --- ## Control Structures These are very similar to other C-style lanuages -- ### Conditionals ```js if (num % 2 == 0) { console.log('even'); } else { console.log('odd'); } ``` --- ## Control Structures ### For Loops ```js var nums = [1, 2, 3]; for (var i=0; i < nums.length; i++) { console.log(nums[i]); } ``` --- ## Control Structures ### While Loops ```js var str = "LaunchCode"; var i = 0; while (str[i] != 'C') { i++; } console.log("'C' is at index " + i); ``` --- ## Functions Defining a basic function: ```js function findMax(arr) { if (!arr.length) return; var maxSoFar = arr[0]; for (var i=0; i
maxSoFar) maxSoFar = arr[i]; } return maxSoFar; } ``` --- ## Function Arguments They're optional! ```js // returns 10 findMax([2, -2, 10]); // Allowed, but results in an error (arr is undefined) findMax(); ``` --- ## Defensive Programming Since arguments are optional, it's a good idea to assume the worst ```js function findMax(arr) { // defend against an undefined argument or empty array if (!arr || !arr.length) return; var maxSoFar = arr[0]; for (var i=0; i
maxSoFar) maxSoFar = arr[i]; } return maxSoFar; } ``` --- ## Anonymous Functions We can create anonymous functions (i.e. functions without a name) ```js function (name) { return 'Hello, ' + name + ', how are you today?'; } ``` --- ## Anonymous Functions This is really only useful if we either: 1) store the function in a variable ```js var hello = function (name) { return 'Hello, ' + name + ', how are you today?'; } hello('Johnny'); // returns 'Hello, Johnny, how are you today?' // and this is kind of cool var goodbye = hello; goodbye('Johnny'); // returns 'Hello, Johnny, how are you today?' ``` --- ## Anonymous Functions or: 2) call it right away. ```js (function (name) { return 'Hello, ' + name + ', how are you today?'; })('Johnny'); ``` --- ## First-Class Functions ### Functions as return values As we saw when we put a function in a variable, functions can be used as _values_ ```js function makeGreetingFunc (name) { var func = function() { return 'Hello, ' + name + ', how are you today?'; }; return func; } var greetJack = makeGreetingFunc('Jack'); greetJack(); // returns 'Hello, Jack, how are you today?' var greetJill = makeGreetingFunc('Jill'); greetJill(); // returns 'Hello, Jill, how are you today?' ``` --- ## First-Class Functions ### Functions as arguments We can also pass functions as arguments to other functions ```js function runThreeTimes(f) { for (var i=0; i<3; i++) f.call(); } var sayHello = function() { console.log('Hello!'); }; // prints 'Hello!' three times runThreeTimes(sayHello); ``` --- ## Hoisting and Scope Variables in JS have **function scope** ```js function findMax(arr) { var maxSoFar = arr[0]; for (var i=0; i
maxSoFar) maxSoFar = thisNum; } // Even after the loop, thisNum still exists console.log(thisNum); return maxSoFar; } ``` --- ## Hoisting and Scope Variables declared w/o the `var` keyword are in the global scope ```js a = 6; function scopeDemo () { a = 5; } scopeDemo(); console.log(a); // prints 5 ``` --- ## Hoisting and Scope Variables declared with the `var` keyword are in the scope of the given function ```js a = 6; function scopeDemo () { var a = 5; } scopeDemo(); console.log(a); // prints 6 ``` --- ## Hoisting and Scope Variable declarations are **hoisted**, which means that when the program is run they are pulled to the top of the function. ```js a = 6; function hoistDemo () { a = 5; var a; } console.log(a); ``` -- - The declaration in the second line will effectively be pulled to the top of the function (above all other lines) --- ## Hoisting and Scope ```js a = 6; function hoistDemo () { a = 5; var a; } console.log(a); ``` -- - In the first line, `a` will have been already declared, even though we're not explicitely declaring it in -- - In this final line, the value of `a` (the global var) is printed, which will be 6 --- ## Less Advanced Resources [w3c JavaScript Tutorial](https://www.w3schools.com/js/DEFAULT.asp) - An accessible tutorial for beginners. Note that this doesn't include some more recent additions such as classes. [MDN JavaScript Tutorials](https://developer.mozilla.org/en-US/docs/Web/JavaScript) - A set of JS tutorials of various levels of difficulty. [MDN JavaScript Documentation](https://developer.mozilla.org/en-US/docs/Web/javascript) - The best JS language reference. --- ## More Advanced Resources [Crockford on JavaScript](https://www.youtube.com/playlist?list=PL7664379246A246CB) - A great video lecture series by a veteran JS developer and evangelist on the origins and history of the language. While this is a "more advanced" resource, the first two lectures/chapters are very historical and are accessible to any programmer. [JavaScript: The Good Parts](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?ie=UTF8&qid=1501083628&sr=8-1&keywords=javascript+the+good+parts) - This is _not_ an introductory learning resource, but once you're familiar with the language, this book will walk you through some of the quirkier and more powerful aspects of JS.