Upload
qiong-wu
View
177
Download
3
Embed Size (px)
Citation preview
JavaScript Basics
Patrick Wiethgfnork webentwicklungsunternehmen
syntax, operators, loops, conditionals, functions
2
What is Javascript?
Multi-paradigm:object-oriented, prototype-basedfunctionalscriptingImperative
Syntax adopted from C
What is Javascript not?The little brother of Java!
3
var iable = 'hello world';iable = 5;global_var = 'hello world';let knowledge = '';
47 + 11;'47' + '11';47 + '11';47 + Number('11');
Javascript Basics - Syntax
584711
4711
58
4
Declaration
Variables are declared in a scope. This means they are accessible only in this scope, e.g. the function in which it was declared.If you foget the keyword var, global scoping is assumed.let is not known by all interpreters! Everything works like var, but the scope is smaller.
Javascript‘s typing discipline is:weak / duckdynamic
5
Typing Discipline
weak means:You can override the type of a variable. A string can become a number if you assign it a number. No error will be thrown, as in strong typing languages.
dynamic means:The type of an object is determined by its context. If you place an object in an environment, where it needs to behave specifically, the interpreter will try to make it behave like this. Or in other words type casting is done automatically.
duck means:When I see a bird that walks like duck and swims like a duck and quacks like a duck, I call that bird a duck. (quote by James Whitcomb Riley)In other words: It doesn‘t matter how you name something (which type you assign), what it does, decides what it is.
6
Operators
4 * 10 + 2;4 * (10 + 2);
var i = 3;iable += i++;iable = ++i;
42
48
8
4
7
Operators
Parentheses go first. Then multiplication and division happens. Addition and Subtraction are done at last
Tabs and whitespaces have no meaning. But increase the readability of code significantly!
Operators behave according to their context. A plus sign will add numbers but concatenate strings. We will see more examples of this behavior.
8
Logical Operators
var tru = 1, fals = 0, wtf = 2;
tru || fals;
wtf || fals;
wtf || tru;
tru || wtf;
1
2
1
2
var tru = 1, fals = 0, wtf = 2;
tru && fals;
wtf && fals;
wtf && tru;
tru && wtf;
0
0
1
2
9
Logical Operators
Logical or and logical and behave in the usual way, if used on booleans. Truth-tables tell us the results.
But as Javascript is duck-typed, operators also work on objects, which cannot be compared in a logical meaning. For example strings.In short:the || operator returns the the value of the first true operandthe && operator returns the value of the first false operandif there is no true operand, || returns the value of the last operandif there is no false operand, && returns the value of the last operand
10
The Truth
So let‘s have a look at what evaluates to true or false:
TRUE FALSE
'any string';[];{ };1;
'';NaN;null;undefined;
11
var one = 1, two = 2, two_in_words = '2';
one == two;one != two;two == two_in_words;two === two_in_words;two < one;two >= two_in_words;
Comparison Operators
false
Remember that objects will behave different depending on which operator acts on
them? Here is another example
truetrue
false
false
true
12
Comparison Operators
Javascript does not just have the ordinary comparison operators. There are some more.=== does not only compare the value but also the type. So both operands must be identical. This operator makes it possible to distinguish between a grey and a black duck. Both ducks walk like a duck and quack like a duck, but they are not identical! !==, >, <= also exist. No examples were given, since their behavior is quite obvious, when the other examples are understand.
Never forget: An object can be successfully compared to a different object, if one of both can be casted to an according type.
13
if (one) console.log('hello noob!') else console.log('wtf');console.log(true ? 'hello noob!' : 'wtf');
var mind_twist = 'happens' && 'is annoying' ? 'with strange statements' && 'is real terror' : 'even if your skill' > 9000 || 'you work alone';
mind_twist == "is real terror" ? console.log("hello pro!") : 'wtf';
Conditional Statements
hello noob!
hello pro!
14
Conditional Statements
if (cond) {…} else if (cond) {…} else {…} is the classical way to build conditionals.You may also use: cond ? expression1 : expression2;Which behaves equivalent in many situations, but it is not identical!if//else acts imperative procedural and a ? b : c; is a ternary operator and acts functional. We will see an example later.
Never forget:You may feel like „Uber McHaxx0r“, if you build big labyrinths of conditional or regular expressions, but the scent of bullshit will always remain.
15
switch (something) { case 'really interesting': alert('wow this case is really interesting!'); break;
case 42: alert('ok makes sense'); break;
default: alert('no specific case was evaluated -> default'); break;}
SwitchSwitch works as you might
know from a lot of other programming languages. But
it is not used often.
The reason will be shown in an example later.
16
for(var i = 0; i <= 9000; i++) console.log('power level ' + i );
var go_on = true;while( go_on ) if( Math.random()*6 >= 5 ) go_on = false;
do { // interesting thing still_interesting ? continue : break;} while ( i++ < 100 );
Loops
power level 0power level 1power level 2power level 3power level 4
…..
17
Loops
Loops can be implemented in different ways. You even don‘t need any of the shown expressions (for, while or do) to build loops. Basically loops are just repeatedly executed code. But these expressions exist for a good reason. They make code a lot more readable.The for-loop shows right in the beginning how often the enclosing code will be evaluated. Therefore it is easy to understand why a loop does something this specific number of times.
Again you might become „Haxx0r McLeet“ if you build complicated loops with functions that mystically call each other. But if this is really necessary, just use something like do and put a boolean variable with a represantative name into the closing while.
18
var Story = ['this', 'is', 'a story', 'all about', 'how my code', 'got', 'flipped turned upside down'];
Story[2] + Story[5] + Story[6]; a
var Story2 = [];Story2.push(Story[0], Story[1], Story[4], Story[5], Story[2]);
console.log(Story2 = Story2.join(' '));
console.log(Story2.split(' '));Story2.length;
Arraysa storygot flipped turned upside
down
[ 'this', 'is', 'how my code', 'got', 'a story' ]
this is how my code got a story
[ 'this', 'is', 'how', 'my', 'code', 'got', 'a', 'story' ]
31
19
Arrays
Arrays contain data. They are organized by indices. In fact arrays are just objects. So we should have a look at objects next…
We have seen some nice examples how mighty functions like split and join can be.Strings are arrays as well.
20
var myObject = { sayHello : function() { console.log('hello'); }, myName : ‘gfnork' };
myObject.sayHello(); console.log(myObject.myName);
Objects
We have heard a lot about objects already, because almost everything is an object!
‘hello’
‘gfnork’
21
Objects
Objects consist of key-value pairs. The key is a stringThe value can be anything. The only limit is yourself!
Almost everything in Javascript is an object.Numbers and Strings are no objects.Instructions are no objects (var, if, for etc.)Everything else is an object. arrays as well as functions. This is why you can put functions into arrays.
22
myObject.sayName = function () { console.log('my name is: ' + this.myName);};
myObject.sayName();var testObj = { sayName: myObject.sayName };testObj.sayName();
This
my name is undefined
my name is Gfnork
23
This
The this-operator gives you access to the key-value pairs of the object where this is placed.
You will need this in JS more often than in C or Java, because member functions of an object must use this to access other members (key-value pairs).
this can be in another scope as intended! Don‘t forget that this is evaluated when the function is called, not when it is defined.
24
Functions
var TalkTo = function(person, msg) { var text = msg + ', ' + person; console.log(text);};
TalkTo('Gfnork', 'What’s up');
var TextTo = function(person, msg) { return = msg + ', ' + person;};
What‘s up, Gfnork
25
var insult = function () { console.log('idiot!') };var praise = function () { console.log('good boy!') };
var teacher = function () { if (Math.random() < 0.5) return insult(); else return praise();};
teacher();teacher();
Function returns
idiot! idiot!good boy! idiot!
or good boy! good boy!
good boy! idiot!
26
Functions
If one considers objects as nouns in JS, then functions are the verbs.
JS should not be seen as mainly functional. The same applies for object-oriented. Which paradigm fits more, depends on how you design your code. Of course, in the same project some parts may be described better as functional and others as object-oriented.
Functions do not only use or manipulate objects. They also create new objects, thus invoking their specific behavior (prototyping).
27
(function () { console.log('This output will be printed once!');})();
var teacher = function () { var reaction = Math.random() < 0.5 ?function () { console.log('idiot!') }() :function () { console.log('good boy!') }(); return reaction;};
Anonymous Functions
This output will be printed once!
Remember that there was a difference mentioned between if/else and ? :Here you can spot it!
28
Anonymous Functions
other names: „lambda“ / l, function literal, function constant
provide a very useful tool for in-place creation of new objects (and functions of course)
might look like poorly documented code at first glance, but are very readable when familiar to it, so adapt to using them!also make life a lot easier, when it comes to paradigms like asynchronous programming
29
Reserved WordsWe have already seen several of reserved words of Javascript.Here is a complete list:
abstract boolean break byte
case catch char class
const continue debugger default
delete do double else
enum export extends final
finally float for function
goto if implements import
in instanceof int interface
long native new package
private protected public return
short static super switch
synchronized this throw throws
Transient try typeof var
void volatile while with
30
Javascript Basics
The reserved words were put on the last slide for completion and to show what was not explained in these slides.
Now you have seen the most important things one encounters when working with JS!
Summary:JS is a very dynamic language - with all implicated drawbacks and benefits. Pedants will hate it, whereas creative people will love it. Nice for the real „Haxx0r Mc1337“!