Vous êtes sur la page 1sur 27

Lecture 1

JavaScript Basics and Syntax

1 / 27
Getting started
Fire up a REPL (Read-Execute-Print Loop) and follow along:

Alt+ ⌘ + jin Chrome

node in terminal (make sure you have NodeJS installed)

2 / 27
Literals
1. Numbers: 1, 2, 3, 1.28e4, NaN, Infinity
2. Strings: 'xyz', 'foo \n', '\u2603'
3. Boolean: true, false
4. Objects: {course: 'CIS 197', title: 'JavaScript'}
5. Array: [1, 2, 'ham', 'spam']
6. Functions:

var square = function (x) {


return x * x;
}

3 / 27
Numbers
Stored internally as a 64-bit value (like Java's double type)
NaN represents a non-number result
For example, Number('xyz') returns NaN
CANNOT be compared using equality operators –
only Number.isNaN() may be used
Infinity represents all numbers larger than
Number.MAX_VALUE

4 / 27
Strings
Strings can be written with single quotes or double quotes. Use
single quotes - it's bad style to mix them.
Exception: Strings like "I don't like double quotes"
that have single quotes inside them
Escape characters use backslash, like Java: '\n \t \\'
Strings are immutable - once created, you can't change them
Concatenating them with the + operator returns a new
string
No char type - just use strings of length 1
Many useful methods/properties –
.length, substring(), toLowerCase(), toUpperCase() ...
See the full list in the MDN string documentation

5 / 27
Booleans
true and false
Standard logical operators ( &&, ||, !)
Also bitwise operators ( &, |, ~) - don't use these!
JavaScript isn't statically typed - you can use ANY value with a
logical operator
Falsy values: false, null, undefined, 0, NaN, ''
Any other value is truthy (including 'false', [], {})

6 / 27
"Truthy" Control Flows
undefined is a falsy value, so code like this is common:

var course = {
title: 'JavaScript',
dept: 'CIS',
code: 197
};

if (course.instructor) {
console.log(course.instructor.name);
} else {
console.error("No instructor found!");
}

7 / 27
Arrays
Literal notation uses square brackets: ['foo', 'bar', baz']
Can be heterogenous: ['foo', 1, true] is valid
Contrast with Java, where elements must have the same type
Elements accessed with square bracket notation: arr[0]
Convenience methods like
push(), pop(), slice(), shift(), unshift()
See the full list in the MDN Array documentation

8 / 27
Objects
Lightweight, mutable key-value stores
Literal notation uses curly braces: {foo: 'bar', 'baz': 2}
Property names can be strings: {'foo': 'bar'}
Access with obj.propertyName or obj['propertyName']

var obj = {
someProperty: 'abcdef',
nestedObject: { a: 1, b: 2, c: 3 },
func: function () {
return 0;
}
}

obj.someProperty // --> 'abcdef'


obj['nestedObject'].a // --> 1

9 / 27
Functions
First-class JS object (this allows JavaScript to take advantage of
functional programming techniques)
Functions can return a value with the return keyword
If no value is returned, then the function returns undefined

var square = function (x) {


return x * x;
}

10 / 27
Functions vs Calls
Don't get confused about the difference between a
function call and the function itself! Remember, the
call will always end with some parentheses.

var square = function (x) {


return x * x;
}

console.log(square); // function
console.log(square(2)); // function call

11 / 27
Scoping - or, Always Use Var
Declaring a variable without var assigns it to the global object -
window in the browser, global in Node
Declaring a variable with var, at the top level, also assigns
to the global object...
This is generally not what you want, and can cause issues.

i = 4;

// later, in another file


for (i = 0; i < 10; i++) {
// 'i' unintentionally overridden!
}

12 / 27
Closures
Variables stay in scope when you create a nested
function. For example, the variable x below is still
available in the function y.

(function () {
var x = 123;
var y = function () {
console.log(x);
};
y();
})(); // 123

13 / 27
Closures, continued
Closures are very useful for creating private state - variables that
are not acccessible by any outside code. For instance, here's how
we'd use a closure to write a counting function:

var createCounter = function () {


var count = 0;
return function () {
count++;
return count;
};
};

var counter = createCounter();


counter(); // --> 1
counter(); // --> 2

14 / 27
Hoisting
Before JavaScript executes a function, it looks for all var
declarations within the current scope. It then declares all those
variables but doesn't assign them (effectively executing the
statement var foo; at the top of the function). Only then does the
function block get executed. Assignment of a variable occurs when
the function execution reaches the line where you actually assign a
variable.

15 / 27
Fun with Hoisting
var foo = 100;

var show = function () {


console.log(foo); // --> undefined

if (true) {
var foo = 123;
}
}

show();

Declaring var foo causes foo to be shadowed for the


console.log() statement – even though this is clearly not the
intention!

16 / 27
Fixed Version
var foo = 100;

var show = function () {


console.log(foo); // --> "100"

if (true) {
foo = 123;
}
}

show();

17 / 27
Objects and this

18 / 27
Everything is an Object
Aside from the primitive types (String, boolean, and Number) -
everything in JS is a kind of object
Even primitives can behave like objects (Strings, for example,
have properties/methods)
Array is an object with integer keys and specific methods (e.g.
splice(), indexOf())
Functions are also object-like, and can have properties and
methods
Can be thought of as executable objects

19 / 27
Using this
If a function is a property on an object, then we can access the
parent object from within that function using this. Simple!

var obj = {
prop: 'I am a property.',
printProp: function () {
console.log(this.prop);
}
};

obj.printProp();
// --> 'I am a property.'

20 / 27
Since functions are objects, you might be wondering
what happens if we reference this inside a function
object itself.

var func = function () {


return this;
};

func.prop = 'I am a property';

console.log(func);
// --> { [Function] prop: 'I am a property' }
console.log(func());
// [LOTS OF TEXT]

So what does func() actually return?

21 / 27
The Global Object
If a function isn't assigned to an object, then its
this context will be the global object ( window in a
browser, global in Node).

22 / 27
Diagnosing Global Object Errors
var numberPrinter = {
num: 3,
print2xNum: function () {
var doubleThisNum = function () {
return 2 * this.num;
};
console.log(doubleThisNum());
}
};

numberPrinter.print2xNum();
// --> NaN

We wanted 2 * 3 -- what's going on here?

23 / 27
Solution
var numberPrinter = {
num: 3,
print2xNum: function () {
var printer = this;
var doubleThisNum = function () {
return 2 * printer.num;
};
console.log(doubleThisNum());
}
};

numberPrinter.print2xNum();
// --> 6

24 / 27
Often, you'll see var self = this; - which can be
hard to read when it's overused. It's better to name the
variable something that reflects its type (like printer
in the previous example).

25 / 27
Even better solution
Use the built-in Function.bind() to manually assign the internal function the
correct this context!

var numberPrinter = {
num: 3,
print2xNum: function () {
var doubleThisNum = function () {
return 2 * this.num;
}.bind(this);
console.log(doubleThisNum());
}
};

numberPrinter.print2xNum();
// --> 6

26 / 27
Next time:
1. Callbacks and asynchronous
programming
2. The new Keyword
3. Prototypal Inheritence

27 / 27

Vous aimerez peut-être aussi