We learned how to produce values from using operators on other values. We created expressions!.
27
, "YES!"
27;
, "YES!";
// Expression (no semicolon), evaluates to 6
1 + 5
// Statement, contains an expression
1 + 5;
// Statement, contains multiple expressions
parseInt("4" + "2");
// Even these are statements:
1;
"hi";
If you declare a function using this (function declaration) syntax: →
// function declaration, a single statement
function f() {
// do stuff
}
… you have a single statement (note, no semicolon at the end).
However, any statement that:
function
const foo = function bar(bax) {}; // <-- function expression
const qux = function(corge) {}; // <-- function expression
JavaScript has a feature that automatically inserts semicolons at the end of statements (Automatic Semicolon Insertion / ASI) →
;
immediately after return
!)
return
{
name: 'John'
}
What's a function? →
JavaScript comes with a bunch of built in functions (and objects) that are available globally. Here are a couple:
parseInt("100", 2)
→parseInt("100", 10)
→console.log("hi")
console.log("hi", "hello")
Variables are symbolic names for values; you can use a variable's name wherever you want to use that value.
To create a variable, start with one of the following keywords:
=
and a value or expression
const s = 'hello';
let i = 21 * 2;
console.log(s);
console.log(++i);
We can create identifiers, or variable names, based on these rules:
Speaking of reserved words….
abstract
boolean break byte
case catch char class const continue
debugger default delete do double
else enum export extends
false final finally float for function
goto
if implements import in instanceof int interface
let long
native new null
package private protected public
return
short static super switch synchronized
this throw throws transient true try typeof
var volatile void
while with
Wait, so it looks like there are three ways to declare variables. What's the difference? Let's look at const
and let
first →
const
and let
is the block that they're contained in
{
const s = 'in'; // just need two curly braces to make a block!
}
for(let i = 0; i < 10; i++) {
const s = 'also in'; // for loop body is a block!
}
function f() {
const s = 'in too'; // function body is a block!
}
Accessing a variable when it's out of scope produces a run-time error (specifically a ReferenceError
)!
console.log('out there');
{
const s = 'in here';
}
console.log(s);
(heeeey… sort of just like Java)
Variables in an outer scope are visible from an inner scope:
{
const first = 'out there';
{
const full = `${first} in here`;
console.log(full);
}
}
This may seem obvious, but accessing a variable declared by let
or const
before it's declared will give a syntax error. →
console.log(s);
let s = 'after!';
// ReferenceError! s was used before it was declared
var
does not behave this way!? (we'll see this in the slides on hoisting)OK… so what's the difference between const
and let
then? →
const
can't be assigned a different value after it had been declaredconst
reassignment will result in a run-time error (TypeError
)
const dontChangeMe = "I told you so";
dontChangeMe = "why not?";
const
declared variable is mutable, it can still be changed without error
const arr = [1, 2, 3];
arr[0] = 'wat? this is ok!?';
console.log(arr);
let
declared variables can be reassigned
let i = 0;
i = i + 2;
console.log(i);
Again, a value cannot be assigned to a const
declared variable after it's been declared. This implies that… →
const
const foo;
foo = 'bar'
// SyntaxError: Missing initializer in const declaration
When you declare a variable without assigning a value to it, it will be initialized to undefined
(this is really only valid for let
and var
, of course). →
For example, the output of this…
let a;
console.log(a);
is
undefined
If a variable has already been declared (with let
, const
, or var
)… →
let
and const
will result in a SyntaxError
let i = 0;
let i = 1;
let
and const
behavior in loops: →
for(let i = 0; i < 10; i++) { console.log(i); }
let
or const
in a loop body does not count as redeclaration (works fine; it's another scope!)
for(let i = 0; i < 10; i++) {
const j = i * 2;
console.log(j);
}
What's the output of this code? No output and error are possible →
if(true) {
let name = 'Joe';
} else {
let name = 'Not Joe';
}
console.log(name);
ReferenceError: name is not defined
// name is not in scope (name is declared within the if statement)
What's the output of this code? No output and error are possible →
let name;
if(true) {
name = 'Joe';
{
let full = name + ' Versoza';
console.log(full);
}
} else {
name = 'Not Joe';
}
console.log(full);
Joe Versoza
ReferenceError: full is not defined
// name is in scope, so full is Joe Versoza
// but full is not in scope in last line
What's the output of this code? No output and error are possible →
for(const i = 0; i < 4; i++) {
console.log(i);
}
TypeError
// assignment to constant (i is incremented)
var
creates a variable in function level scope, regardless of where it appears in the function
What's the output of the following code? →
function foo() {
if(true) {
var bar = 'baz';
}
console.log(bar);
}
foo();
baz
bar
is in a block, its scope is the entire function!var
was the only keyword for declaring variables in ES5If a variable has already been declared var
… →
var
again is ok!
// no syntax error
var a = 'bar';
var a = 'baz';
var
but not assigning a value will have no effect on the original value:
// no syntax error
var a = 'bar';
var a;
// a is still 'bar'
const
or let
(or var
, I guess) when declaring variable names!If you don't declare variables with these keywords:
What happens if you don't use const
, let
or var
? →
function foo() {
wat = 'uh oh!';
}
foo();
console.log(wat);
What happens if you don't declare a variable at all? →
const
, let
, or var
)ReferenceError: variable is not defined
What are the rules for a valid identifier (variable name) again? →
_
), or dollar ( $
)BTW, Unicode characters are allowed in variable names!!! →
const ಠ_ಠ = "disapproval";
console.log(ಠ_ಠ);
// totally works (O_o !?)
Thanks Stackoverflow! Also, here's more about that look.
Oh, and this is a site that let's you check if a variable name is valid or not.
Because JavaScript is dynamically typed… variable reassignment (for let
and var
, even of different types, is ok →
let x = 25;
x = "foo";
Lastly, a quick aside…
const
vs let
vs var
… There are a few ways to approach this (what do you think): →
var
, block level scoping - use const
or let
var
const
, and only use let
when you know you need reassignment (like incrementing a loop variable)let
and use const
to signify a constant
My preference is default to using const
(#2, #1), mainly because it seems to be way the community is moving (preventing reassignment may reduce side effects / bugs).
From Speaking JavaScript:
console
object is an available variable from the start of your program!