javascript for python programmers

overview


This guides highlights the basic parts of javascript that can be used in davinci blog to add dynamic features or powerful analytics.
computer program
A computer program is a collection of instructions designed to tell the computer how to perform a particular task. A program is a linear structure, where the instructions are listed and executed in a specific order.

The following is a sample program that prints the message "hello world" to the console.



  print('hello world');
				
Try it!

Declaring Variables

One of the first steps to writing a program, is to understand how to declare and manipulate variable. A variable is a name that is given to a piece of data. The following shows two simple examples.


let age = 12;
let name = "steven"
            
Variable Types
Varaibles can hold different types of data. In the examples above, the variable age is assigned a numeric value, while the name variable is given a piece of text. The kind of data that a variable holds is referred to as its type. The type of data determines what you can do with the data. For instance, you can subtract numeric types, whereas, its not clear what subtracting two pieces of text would be.

Javascript is a simplified language in that you only really need to know a limited number of types.

  • number
  • text
  • date
  • array
  • dictionary (or object)
  • function




For a more detailed information about javascript data types, please see:

data types

expressions


An expression is piece of text within a program that (possibly) evaluates to some other value. For instance, the text "2+2" evaluates to the number "4". Technically, when we assign a value to a variable, you assign an expression to the variable name, and the expression is evaluated prior to the assignment. The following code demonstrates assigning the value of 2+2 to the variable "value".


let value = 2+2;
            


In this case, the expression "2+2" is evaluated to 4 before assigned to the variable "value".

Functions

A function is an algorithm that takes a set of inputs, and returns a single output. As an example, we talk about the addition function, that is, an algorithm that takes two numbers as inputs, and returns a single number as the output. If we have a function, such as the add function, we get an expression that represents its output as the name of the function, with the list of its inputs within parentheses, separated by commas.

The following shows calling the add function, and then assigning its output the the variable named "sum".


let sum = add(2,3);
            


The javascript language comes with a number of predefined functions, however, in general it is up to the programmer to define the functions they need to use. To define a function, you write the word "function" followed by the name of the function, followed by parentheses with the list of inputs within the parentheses. Following the parentheses is an open curly braces followed by a closed curly brace.


function add(a, b){
						
						
}
            


This function does not do anything. The code for the algorithm that the function executes will be placed within the curly braces. The following puts an algorithm within the braces that executes the function.


function add(a, b){
  let answer = a+b;			
  return answer;	
}
            
Try it!



There are other ways to declare a function. A function can be declared in a similar way to the variable declarations given above.


let sum = function(a, b){
  let answer = a+b;			
  return answer;	
}
            
Try it!



Javascript also gives you a shortened method of declaring the function by getting rid of the key word "function". In this case, it is replaced by an "arrow". You enter the parameters of the functon, followed by the arrow, followed by the function block.


let sum = (a, b) => {
  let answer = a+b;			
  return answer;						
						
}
            
Try it!



When there is only one argument, the function can be shortened further. You dont need the parentheses. If the function block can be written as a single line, you can remove the curly braces and the return keyword.


let double = a => {
  return 2*a;										
}

let double2 = a=>2*a;
            

Functions on Objects




let obj = {
  add:function(a,b){
    return a+b;				
  }					
};

let sum = obj.add(1,3);
            
Try it!

Method Chaining

The ability to put functions on objects creates a nice way execute multiple functions within a single line. Consider the following object.


let obj = {
  test:function(a,b){
    return {
	  test2:function(){
		return 'hello'			
	  }				
	};				
  }					
};
            


The object has a function set on it name "test". This function returns a different object, also with a function on it, this time named "test2". Now, consider the following code:


let text = obj.test().test2();


let text2 = obj
              .test()
              .test2();

            
Try it!

This code calls the method "test" on obj. However, it then calls "test2" on the object that is returned. That is, the code is evaluated by replacing the expression "obj.test()" with the object that it resolves to, and then the function test2 is called. The second line of code shows a common way to format these chained calls. Because Javascript ignores the white space, these two function calls are the same.

Control Flow

Control flow is a set of language constructs that tell a program which pieces of code to execute. The simplest example of control is the the if statement. consider the following code:


let age = 12;
if(age-10 > 0){
  print("greater than");					
}
else{
  print("less than");
}
            
Try it!

The if statement is structured like the following:



if(expression){
  code to execute if true					
}
else{
  code to execute if false
}
            


The if statement takes an expression, evaluates the expression. If the expression equals true, then the first block of code is executed, otherwise the second block is executed.

For Control Flow

A very important control flow statement is the for statement. It is used to iterate over all the elements of an array. Consider the following

let data = [1,2,3,4,5];

for(let item of data){
  print(item);					
}
            
Try it!

Functions as arguments to functions

Specify the Name and Input dataset
Functions can be used like any other piece of data or variable. For example, a function can be passed to another function, as a parameter. This may seem like a fairly obscure fact that is not that useful, but it turns out to be incredibly useful in data querying and transformations.


let data = [1,2,3,4,5];
let answer = [];

for(let number of data){
  if(number>3) answer.push(number);					
}

            
Try it!

This code effectively filters the list of numbers for numbers that are greater than 3.

Lets imagine that we put the filter condition in a function as follows.


let data = [1,2,3,4,5];
let answer = [];
let condition = function(number){ 
  if(number>3) return true;
  else return false;
}

for(let number of data){
  if(condition(number)) answer.push(number);					
}

            
Try it!

let data = [1,2,3,4,5];
let answer = [];
let condition = function(number){ 
  if(number>3) return true;
  else return false;
}

let filter = function(data, condition){
  let answer = [];
  for(let item of data){
    if(condition(item)) answer.push(item);					
  }
  return answer;
}

let filtered = filter(data, condition);

            
Try it!

Once we have a filter function defined as above, we can now filter an array very simply.


let filtered = filter([1,2,3,4,5], p=>p>3);
            
Try it!

As an additional simplification, the filter function is defined on the array object, so that we can do the following.


let filtered = [1,2,3,4,5].filter(p=>p>3);
            
Try it!

Modules


A module is a library of Javascript code that is published on the network somewhere that you can load and use in your Javascript code. That is, it is a page of code that defines a bunch of functions (and possibly other variables) that are available for use, after you load the code. The following shows how to load a module at the URL "http://server/utilities.js".


let utils = await import('http://server/utilities.js');
            


Notice in this code, you assign a name to the imported module. The name can be any name you wish.

Once a module has been loaded, you have access to the functions defined therein. The following code demonstrates how you would call a function called test on the imported module.


let utils = await import('http://server/utilities.js');

let answer = utils.test();
            


Contents