introduction to javascript
By Eran Medan, NICE Actimize
objective
Learn JS basics, and be able to find what this prints out:
var app = function () { return { func: function (f, range, multipliesOf, modifiers) { var ret = []; for (var i = range.from; i <= range.to; i++) { if (i % multipliesOf === 0) { ret.push(f(i)); } } return ret; } } };var result = app().func(function (x) { return x * x },{from: 1, to: 50}, 2); result[2] = result[0] + result[1]; // modify array element var answer = result[2] * 2 + 2;console.log(answer);
Fun facts
- JavaScript is 18 years old (released in 1995)
- Developed by Brendan Eich at Netscape
- Was initially named "Mocha", then "LiveScript"
- Has basically very little to do with Java
Basic Language features
- Interpreted (vs compiled)
- Dynamically typed (vs static typed, e.g. Java, C++)
-
Functional - functions are first class citizens
- Prototype inheritance - inherit from an object not a class
How to run Javascript?
- Create an HTML file and put your code in a
<script></script>tag, then open that HTML file in a browser -
Using Chrome / FileFox go to http://repl.it/languages/JavaScript
- Open the chrome JavaScript console (we'll use this one)
JavaScript as a calculator
enter:
1 + 1; you'll get:
2
enter:
(1 + 3) * 2; you'll get:
8
basic
arithmetic operators:
+ / * - ( ) % variables
enter:
var x = 3;
this stores the value of 3 in a global variable named x.
enter:
x * x;
you get:
9
VARIABLES
You can also overwrite an existing variable, just reassign it
enter:
x = 4;
then again:
x * x; you get now:
16 strings
enter:
var part1 = "Hello";
then enter:
var part2 = "World";
You can concatenate Strings with the + sign
enter:
var full = part1 + " " + part2;
you get:
"Hello World" JAVAScript core "primitive" Types
- String (
"Hello World") - Boolean (
true, false) -
Number (
1, 0.5)
comments
single line //
var x = 2; // everything after "//" is ignored on the same line multiline /* */
var x = 2;/* now I can write my commenton multiple linesJavaScript code is also ignoredx = 3; */console.log(x); //still 2
conditions
if (something is true) {
//then part
} else {
//else part
} example
if (1 + 1 == 2) {
console.log("one plus one is still two");
} else {
console.log("the world is ending!");
} conditions
you don't need to have an else clause
if( 5 > 3) {console.log("five is greater than three");}
boolean expressions
conditions use something called Boolean expressions
why? because they are expressions that return a Boolean
which is basically a "yes/no" question
for example
var x = true; //true and false are reserved keywords in JavaScriptvar y = (1 + 2 == 3); //y is equal to true, as 1 + 2 equals to 3var z = 2 < 1; // z is equal to false, as 2 is not less than 1
boolean expressions
there are more operators used for Boolean expressions
some operators work on 2 Boolean (true/false) variables
e.g. AND, OR
e.g.
true AND true → true
true AND false → false
true OR false → true
false OR false → false
boolean expressions
in JavaScript, this
true AND true → true
true OR false → true
becomes this
var x = true && true;// x will be equal to true as both left AND right = truevar y = true || false;// y will be equal to true as either left OR right are true
boolean expressions summary
- AND (true if both operands are true) - &&
- OR (true if either operands is true) - ||
- NOT (changes true to false and false to true) - !
- EQUALS (true if both sides are the same) - == / ===*
- NOT EQUALS (true if both sides are different) - !=
- LESS THAN (true if left is less than right) - <
- GREATER THAN (true if left is greater than right) - >
- LESS THAN OR EQUAL (same as < OR ==) - <=
- GREATER THAN OR EQUAL (like > OR ==) - >=
* difference between == and === will be explained later
boolean expressions exercise
try to find out what will be printed
var x = (true && true) || false;var y = (1 >= 0) || x == !false;if (!x || (y != false)) {console.log("condition is true");} else {console.log("condition is false");}
solution
let's try to find the value of x
var x = (true && true) || false;this becomes
var x = (true) || false;which becomes
var x = true || false;which becomes
var x = true;SOLUTION
let's try to find the value of y
var y = (1 >= 0) || x == !false;
this becomes
var y = (true) || x == !false;
which becomes
var y = (true) || x == true;
which becomes
var y = true || true; // we already found that x is equal to true
which becomes
var y = true;solution
now let's see the if condition
!x || (y != false)
let's replace it with the values we found
!true || (true != false)
becomes
false || true
becomes
true
so, what will be printed?
while loops
while (condition is true) {
//keeps running until condition is false or a call to "break"
}
example
while (true) { // will run forever, AKA infinite loop }while (false) { // will never run }
example2
var counter = 0;// read: as long as variable counter is less than 10, repeat this codewhile (counter < 10) {console.log(counter);//read: increment counter by 1. (= is for assignment, not equality)counter = counter + 1;}
while loops
to increment a counter, there are few shortcuts
+=
var counter = 0;while (counter < 10) {counter += 1; // same as counter = counter + 1;}
++ (same as += 1)
var counter = 0;while (counter < 10) {counter ++; // same as += 1}
for loops
for loops are like while loops basically, with conveniences
let's look at our while loop, it has 3 main parts
var i = 0; //initializationwhile (i < 10) { //conditioni++; //increment}
for-loops simply arrange it in a nice syntax
for (initialization; condition; increment) {}
for example
for (var i = 0; i < 10; i++) {}
for loops
what is the order of execution?
for (initialization; condition; increment) {// iteration}
-
initialization - happens only once
-
condition - before each iteration
-
increment - after each iteration
break
break - will stop the loop (for / while) immediately
e.g.
var counter = 0;while (true) {if (counter == 10){break; // when counter reaches 10, the loop will end}counter += 1;}
continue
continue will skip to the next iteration
e.g.
for (var i = 1; i <= 100; i++) {//read: if the remainder of i divided by 3 is 0, i.e. a multiple of 3if (i % 3 == 0) {continue; // then stop this iteration and move to the next one}console.log(i);}
this will print all numbers from 1 to 100 except multiples of 3
arrays
an array in JavaScript is an object
how to create an array?
method 1
var myArray1 = new Array(); // empty arrayvar myArray2 = new Array(1,2,3); array with elements 1 2 3
method 2 (array literal)
var myArray1 = []; // empty arrayvar myArray2 = [1,2,3]; array with elements 1 2 3
arrays - accessing elements
array elements have indexes, which start at 0.
in other words the first element has index 0
the second element has index 1
the last element has index n-1 where n is the size of the array
Example
var array = ["a", "b", "c"];console.log( array[0] ); //will print "a"console.log( array[1] ); //will print "b"console.log( array[2] ); //will print "c"
array - adding elements
method 1
var array = [];array[0] = "a";array[1] = "b";array[2] = "c";//array contains ["a", "b", "c"]
method 2
var array = [];array.push("a");array.push("b");array.push("c");//array contains ["a", "b", "c"]
array - modifying elements
to modify an element simply assign it a new value
e.g.
var languages = ["JavaScript", "C++", "Erlang"];// let's change "Erlang" to "Java"// "Erlang" is in the 3rd place, but we count from 0, so it's index 2languages[2] = "Java";console.log(languages);// this will print ["JavaScript", "C++", "Java"]
useful array methods / properties
length - get the size of the array
var myArray = [1,2,3];console.log( myArray.length ); //prints 3
concat - concatenates two arrays
var myArray1 = [1,2,3];var myArray2 = [4,5,6];console.log( myArray1.concat(myArray2) ); //prints [1,2,3,4,5,6];
for more array functions and properties see
mixed arrays
Arrays can hold mixed types, for example
var myMixedArray = ["Strings", true, false, 1, 2.4];Actually, arrays can contain... Arrays!
var myMatrix = [[1,2,3],[4,5,6],[7,8,9]];console.log(myMatrix[0]); //prints [1,2,3]console.log(myMatrix[1]); //prints [4,5,6]var innerArray = myMatrix[2]; //innerArray = [7,8,9]console.log(innerArray[0]); //prints 7console.log(innerArray[1]); //prints 8console.log(myMatrix[1][0]); //prints 4 - why? myMatrix[1]=[4,5,6]
iterate over an array
method 1
var myArray = [1,2,3];for(var i = 0; i < myArray.length ; i++){var curElement = myArray[i];console.log("Array element at index " + i + " is " + curElement);}
method 2 (advanced)
var myArray = [1,2,3];for(var i in myArray){if (myArray.hasOwnProperty(i)){ //will be explained in future sessionvar curElement = myArray[i];console.log("Array element at index " + i + " is " + curElement);}}
objects
Just like Arrays, there are mainly two methods to create
method 1
var myObject = new Object();method 2 (object literal)
var myObject = {};objects
objects are a key-value store
in other languages it may be called a
"hash" (Ruby) or "dict" (Python) or "map" (Java)
example 1
var myObject = new Object();myObject.firstName = "John";myObject.lastName = "Doe";
example 2 (literal JS object notation)
this is equal to code above
// : instead of = and , instead of ;var myObject = { firstName: "John", lastName: "Doe" }
objects
just like arrays, objects can contain other objects and arrays!
example
var myObject = {firstName: "John",lastName: "Doe",emails: ["john.doe@gmail.com", "jdoe@example.com"],address: {line1: "1 Main st.",city: "New York",state: "NY",zip: 10001}}
JSON
This leads to what is commonly known as JSON
which stands for
JavaScript Object Notation
more on the JSON standard: http://www.json.org/
functions
functions in JavaScripts are also objects
again, two (main) ways to create a function
method 1 - Function Declaration
function square(x) { return x*x; }method 2 - Function Expression
var square = function(x) { return x*x }there are subtle differences but out of scope for this lesson
functions
functions can have some or no params
functions can have one or no return value
examples:
function foo() {console.log("No params, no return value");}function bar(x) {console.log("Param is " + x + " no return value");}function add(x, y) {return x + y;}
function
so what is a function?
a function is just a predefined piece of code called by name
it can be used to encapsulate a single, reusable piece of code
So how do you call / execute a function?
simply by stating it's name,
and passing 0 or more parameters between parentheses ( )
e.g.
function square(x) { return x*x;}square(2); //-> square(2){ return 2*2 } -> square(2){ return 4 } -> 4
functions
How function parameters work?
this is called the substitution model of evaluation
basically, it means replacing the function name with it's body
this works from the inside out, e.g.
function add(x, y) { return x + y; }function square(x) { return x * x; }add(square(2), square(3));add(2 * 2, 3 * 3);add(4, 9);4 + 9;13;
functions
a function can get another function as a parameter, this is called a higher order function, for example:
// filter array to keep only items for which the predicate returns truefunction filter(array, predicate) {var result = [];for(var i = 0; i<array.length; i++){var element = array[i];if (predicate(element)) result.push(element);}return result;}function isLargerThan3(x) { return x > 3; }filter([1,2,3,4,5], isLargerThan3); //returns [4,5]
anonymous functions
a way to slightly simplify the previous example:
an anonymous function is a function with no name
// filter array to keep only items for which the predicate returns true function filter(array, predicate) { var result = []; for(var i = 0; i<array.length; i++){ var element = array[i]; if (predicate(element)) result.push(element); } return result; }filter([1,2,3,4,5], function (x) { return x > 3; }); //returns [4,5]
can you figure it out now?
var app = function () { return { //return an object with key "func", and a function value func: function (f, range, multipliesOf, modifiers) { var ret = []; for (var i = range.from; i <= range.to; i++) { if (i % multipliesOf === 0) { ret.push(f(i)); //add items to an array } } return ret; } } };var result = app().func(function (x) { return x * x },{from: 1, to: 50}, 2); result[2] = result[0] + result[1]; // modify array element var answer = result[2] * 2 + 2;console.log(answer);
the answer to life the universe and everything
Google: "the answer to life the universe and everything"
Or go to: http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker's_Guide_to_the_Galaxy#The_number_42
Or simply read:
thank you
Any questions?
eran [dot] medan [at] niceactimize.com
(I'll explain about spam bots in a later session)
introduction to javascript
By eranation
introduction to javascript
- 1,695