In-class notes for 02/17/2020
CS 284 (MCA), Spring 2020
First quiz Wednesday; Topics below
Function expressions
We have examined function declarations, e.g.,
function add1(x) { return x+1; } add1(7); // returns 8
Scoping:
var
andlet/const
scoping within a functionnames defined outside of a function are accessible within that function unless there is a more local definition of that name (e.g., within that function). WS2 example
Hoisting functions themselves - function definition is hoisted too, unlike variables; enables functions to call each other. Example:
function odd(n) { if (n > 0) return even(n-1); if (n == 0) return false; // assert - n is negative return odd(-n); } function even(n) { if (n > 0) return odd(n-1); if (n == 0) return true; // assert - n is negative return even(-n); } even(17);
Nested function definitions allowed (unlike C/C++)
Functions are a type of object
A function created via function declaration has a
this
expression.There is also a
arguments
object accessible within function body that provides all arguments for a function call (somewhat array-like, but not an actual array)
JS supports anonymous functions, called function expressions in JS, e.g.,
var add1 = function (x) { return x + 1; } add1(20); // returns 21
(So does C++! But not typically included in SD)
The expression
function (x) { return x + 1; }
above returns a function that has no name.We assigned that (returned) function to the variable name
add1
.We didn't have to give that (returned) function a name in order to call it:
( function (x) { return x + 1; } )(10); // returns 11
JS function expressions are objects, equipped with
this
,arguments
object; may have default arguments, etc.Scope rules within a function follow the same rules, whether that function was created using function declaration or function expression
But a function expression's definition is not hoisted
PUZZLE 1: can you explain why?
(Hint: in the expression
var add1 = function (x) { return x+1; }
think about hoisting and the variableadd1
)
PUZZLE 2: Can you guess/discover a way to define a recursive function expression?
PUZZLE 3: Can you implement function expressions that call each other similar to
odd()
andeven()
above?
Reason this out without computation
Arrow function expressions or arrows.
To study for quiz
Javascript programming in HW1, WS1, and WS2.Basics
JS REPL - Read/Evaluate/Print Loop. Understand as a term
console.log() - standard output in JS
"Untyped" language
types are generally concealed.
typeof
operator
numbers
type coercion,+
operatorvar
vslet
orconst
hoisting
Avoid relying on hoisting for variables - give declaration earlier in the (function, block, global environment)
Hoisted functions needed, permissible
Most operators similar to C++, e.g.,
= += ==, *,
===
- strict equality (same type and same value, no type conversions)
Error handling:
throw
,try/catch
, exceptionsfunction declarations; function specs
language syntax
loops -
for, while, do/while
conditionals -
if
< >