Rediscovering Javascript basics
This will be just another quick reveiw of the Javascript language basics. For any seasoned developer this may seem a pointless effort but perhaps you find something useful, at least to become a js nitpicker or a soon-to-be guru :D.
Javascript properties
Javascript is a weakly typed, interpreted and multi-paradigm (functional,object oriented,..) language in its own way. It is case-sensitive and its basic sintax looks like C. But in a nutshell, its a c without explicit types, where you can store different kind of values in a variable and resize an array with ease.
Comments
the classic C style comments, both single line
// this is a comment
and multiline
/* This is a multiline comment */
For comments and doc generation check jsdoc
Instructions
In javascript, you don't need to end a sentence with a semicolon, unless you want to execute more than one sentence in the same line.
var a = 42
Anyway, people always use to end sentences with a semicolon. By the way, when declaring variables, it is recommended to do it using var because if you omit var your variable will become global!
Deleting elements
There is a delete operator in javascript, which converts any variable to undefined:
var beast = 666; typeof beast; "number" delete beast; typeof beast; undefined
Data types
Numbers, Strings and booleans are the primitive data types in Javascript.
Numbers
0 42 -15 3.1415 23e3 Infinity -Infinity
Strings
A string can be made of single or doble quotes:
"These aren't the droids you're looking for" 'Hello world' "We'll be \"friends\""
The scape character here is \, and we can use it for special values such as newline, tab, etc..:
Booleans
Two values, as usual
- true
- false
Falsy values: some values are interpreted as false:
- null
- empty string ""
- undefined
- number 0
- NaN
Other values
There are three other possible data types
Javascript distinguishes between a variables without any value or null value. There is a subtle difference:
- undefined: this is when a variable does not exist or it is declared but no value has been assigned.
- Null: a variable exists but its value is simply null.
- NaN: Not a Number, you get this value when trying to convert something to a number and you fail.
var number = 'example'; typeof number * 666: NaN
Some curious things about NaN
typeof NaN number NaN == NaN false 2 * undefined NaN but 2*null 0 2+null 2
Declaring and initializing variables
Always use var word to declare variables:
var number; var counter = 0; var a, b=42, c = 4; var x,y,z; x = y = z = 0;
Operators
Arithmetic
No surprises here, operators are the same as C
- +,-,*,/,%
- ++,--
- +=,-=,*=,/=,%=
Comparison
These are the usual operators we find in C, with some additions: <, >, <=, =>
equals
2==2 true 2=='2' true
not equals
2!=4 true 2!=2 false
equals in value and type:
2==='2' false 42===42 true
Non-equality
True when values or types are different
2 !== '2' true 2 !== 2 false
Boolean
The usual stuff as in C:
&& and operator
true && true true
|| or operator
true || false true
! not operator
!true false !false true
Arrays
These are indeed much more flexible than C, C++, etc.. we are not stuck to a fixed size and we can resize and reference new indexes of the array as needed.
var numbers = [4,8,2]; console.log(numbers[0]); 4
numbers[2] = 42; numbers[5] = 666; console.log(numbers); [4,8,42,undefined, undefined,666]
They can hold any kind of values:
var festival = [4, true, 'Jon', null, undefined, 666];
Even arrays containing arrays:
var matrix = [[0,5,1],[7,3,2],[3,7,4]]; matrix[0][1]; 5
var empty= [];
Control Structures
Same as usual two, condition with parentheses and blocks with curly brackets.
Conditional
if
if (a > 0) { console.log('a is greater than 0'); }
For example, test if a variable is defined and has any value different from undefined:
if (typeof someVar !== 'undefined') { console.log('someVar is defined '); }
if-else
Nothing to write home about:
if (a > 0) { console.log('a is greater than 0'); } else { console.log('a is not greater than 0'); }
Ternary operator
This is the well-known brief formula to code if-else, also known as elvis operator:
var number = (a > 0)?a:42;
is the same as:
if (a > 0) { number = a; } else { number = 42; }
if-else-if
There is no elseif or elsif keyword but you can build it that way:
if (a > 0) { console.log('a is greater than 0'); } else if (a < 0) { console.log('a is less than 0'); } else { console.log('a is 0'); }
switch-case
The same as C but better: we can switch on Strings!
switch (name) { case 'Bilbo': console.log('You are a hobbit'); break; case 'Legolas': console.log('You are an elf'); break; default: console.log('Unknown race'); break; }
Loops
We find the same structures with some useful variations in for statements
while
while (a > 0) { a--; console.log('printing a ' + a); }
do-while
The loop that is executed at least once
do { console.log('A printed at least once:' + a); a--; } while (a > 0);
for
The good old for
for (var i = 0;i < 10; i++) { console.log('This is i: ' + i); }
for in
This is some kind of foreach that iterates using the index:
var values = [5,42,666,15]; for (v in values) { console.log("index: "+ v + ", value:" + values[v]); }
Break or continue the loop
Inside a loop instruction we can use two statements:
- break: exits current loop inmediately.
- continue: ends current iteration and continues to next.
What happens when we try to break from double or even triple loops. We must use tags. If we break to a defined tag, we break the execution and we continue in the same level that the tag resides. Try this:
var i = 0; var j = 0; jump: for ( i = 0;i< 10;i++) { inside: for ( j = 0;j< 10;j++) { if (j == 5) { continue; } else if (i==0 && j==2) { continue jump; } else if (i==1 && j==6) { break; } else if (i==2 && j==2) { break jump; } console.log( i + ":" + j); } } console.log("out: " + i + ":" + j); Output: "0:0" "0:1" "1:0" "1:1" "1:2" "1:3" "1:4" "2:0" "2:1" "out: 2:2"
Functions
Javascript does not distinguish between procedures and functions. There are only functions and all of them must return a value. If no value is returned explicitly, undefined is returned by default
function sayHello() { return 'hello'; }
We call to this function by just writing its name with parenthesis:
sayHello();
We can pass parameters to our function:
function sayHelloRepeatedly (repeat) { var result = ''; for (var i = 0;i<repeat;i++) { result = result + 'hello'; } } sayHelloRepeatedly(5); hellohellohellohellohello
If we don't pass a parameter when the function is called, the parameter's value becomes undefined.
We can have more than one parameter:
function saySomethingRepeatedly (repeat, what) { var result = ''; for (var i = 0;i<repeat;i++) { result = result + what; } } saySomethingRepeatedly('3','Cheese'); CheeseCheeseCheese
Parameter number can be dynamic. We can deal with them using the special arguments variable.
function average () { var result = 0; var size = 0; for (var i = 0; i < arguments.length; i++) { result = result + arguments[i]; } if (result) { result = result / arguments.length; } return result; } console.log(average()); 0 console.log(average(1,4)); 2.5 console.log(average(3,3,7,2)); 3.75
To sum up.
- Types: number, String, boolean, null, undefined, NaN, arrays, functions
- Operators: +,-,*,/,%,=,++,--,+=,-=,*=,/=,%=
- Comparison: <,==,>,<=,!=,=>,===,!==
- booleans: &&,||,!
- others: typeof, instanceof, delete
Code conventions
The general rule is always to be consistent. If you want to follow some rules these by google have proper explanations