- Local variables are defined with the
var
keyword. - Variables defined without
var
are automatically global.
- Two ways to define functions:
function someFunc(arg1, arg2) {}
var someFunc = function(arg1, arg2) {}
- All arguments are inherently optional. Calling someFunc() without arguments will NOT error out. The arguments will have
undefined
values. - Functions must return explicitly. There is no implicit return.
- Default return value is
undefined
. - Functions can be referred to without calling them. Brackets are used for calling the functions.
- There is no .each
- You will find yourself using
for(var i=0; i<arr.length; i++)
a lot when looping through arrays.
- Functions can be declared without names. This is useful when a function needs to be passed in as an argument to another function, but doesn't need to be used anywhere else.
-
example 1:
setTimeout(function(){ console.log("three seconds later") }, 3000);
-
example 2:
function map(array, operation) { var new_arr = []; for(var i=0; i<arr.length; i++) { new_arr[i] = operation(arr(i)); } return new_arr } var results = map([1, 4, 7] function(elem) { return elem * 2; });
-
-
Script gets executed when browser parses it from top to bottom of the HTML source.
-
Three important built-in global variables:
document
, the parsed, in-memory HTML documentwindow
, the "tab"navigator
, the whole browser
-
Javascript runs a continuous event loop. Constantly checks for new events. Events can be "listened" on, and tied to functions they can call.
document.addEventListener("click", function(){ console.log("YOU CLICKED OMGXOR"); })
-
Javascript is embedded into the browser with the script tag.
<script type="text/javascript"> console.log("Hello World"); <script>
-
or linked to from a file
<script type="text/javascrscript" src="path/script.js"></script>
- Any elements that javascript accesses must be loaded on the page. So if javascript is executed Before an HTML element is loaded, it won't be able to access the element.
- Events can be used to time actions appropriately. Hint:
document.onload