Web.simmons.edu



From Python to JavaScriptby Margaret Menzin, Simmons UniversityMany students learn Python as their first language, and then continue on to languages such as Java. But, JavaScript (JS) is frequently not studied, despite its enormous use and its essential monopoly of all web pages. Further, the transition from Python to JavaScript is quite easy, as we will see in this article. JavaScript's official name is ECMAScript. In 2015 many useful structures were added to JavaScript, resulting in ES6 or ESnext. We will not deal with those additions here, nor will we deal with the subtleties of closures or the differences in inheritance between Python and JavaScript. Part III of this paper will point you to sources on those matters. Part I is excerpted from material for students who need to use a little JavaScript inside MongoDB (e.g. for aggregation pipelines.) It is independent of the many uses of JavaScript to make web pages interactive. So, Part I focuses on basic JS for those who know basic Python.Part II summarizes Part I as a cheat sheet.Part III points you in the direction of learning more about JavaScript (e.g. for web pages) and especially ES6.Part I - Some few very basic facts about JavaScript - Or how to quickly turn your Python code into JavaScript codeJavaScript uses { } to enclose the body/scope of a loop, a function, or any code to execute in an if clause. Of course, Python uses indentation. In JavaScript it is best practice to end any statement with a semi-colon. This is also important in more advanced JS programming. Comments on a single line start with // and run to the end of the line. Longer comments may be enclosed between /* and */JavaScript is case sensitive. For instance, reserved words such as if, while, are written in lower case. Variable and function names are also case sensitive.JavaScript has constants true / false and all the data types and operators you use in Python.( +, - ,* , / etc.) Note that in JavaScript true and false are all lower case and that the logical operators use different symbols: &&, || , and ! in JS for Python's 'and', 'or' and 'not'. lists all these operators.JavaScript ignores extra blank spaces. JavaScript has a conditional: if statement.The condition you are testing for must be enclosed in parentheses.A nicely formatted statement looks like: if (condition) {? ? //? block of code to be executed if the condition is true } else { ? ?//? block of code to be executed if the condition is false }The else clause is optional. That is, you can just code: if (condition) {? ? //? block of code to be executed if the condition is true }The elif of Python becomes elseif in JavaScript.Examples using if_else can be found at JavaScript, like Python, is an interpreted language. They are both loosely typed, meaning that you may use a variable without first declaring it and specifying its type.Although you may use a variable without even declaring it at all, best practice is to declare it.For example: var myFav = 7; Any variable declared inside a function with the keyword var is local to that function. If , inside a function, you don't declare myFav with a var, then it will have global scope. If you want a block-scoped variable then you need to use let, in lieu of var; let is one of the features which ES6 introduced.JavaScript has three types of loops:- for( i = 0; i <= 7; i++) { do stuff } is exactly like the for loop in Python. while (some condition) { do stuff } // pre-test before entering loop; like Python's while loop do {do stuff } while (some condition) // post-test after the loop For examples, see Arrays in JavaScript, like lists in Python, are indexed starting from 0. In JS, the length of an array A is A.length That is, length is a property of an array or string, rather than a value found with a len() function.You may define an array with A = [1, 2, 3] or A = new Array(1, 2, 3);If A is an array of objects and A[i] is one member of that array, then the properties in A[i] are accessed using dot notation – e.g. A[i].age gives you the value of the A[i] property whose key is age, or if A[i] is an image tag then A[i].src gives you the src (source) property.Objects are written in JavaScript in the same way as dictionaries in Python.JavaScript has Math and Random objects which have the usual functionality analagous to that in Python . You don't need to import these objects/modules in JavaScript.JavaScript code may be stored in files with the extension js. To see your script run, however, you may also go to your browser, open up the console (ctl+shift+I or command+shift+I in either Firefox or Chrome) and paste your code in the console. The console.log() function will produce output.In JavaScript we start a function definition with the key word function (as opposed to Python's def). function cube(x) { return x*x*x; } How Python translates to JavaScript:PythonJavaScriptdef times10Absolute(x): if x < 0: x = -x return 10*xy = times10Absolute(-25)print(y) function times10Absolute(x) { if ( x < 0 ) { x = -x }; return 10*x; }y = times10Absolute(-25);console.log(y); o. The forEach method and anonymous functions:These features, which are not part of basic JS, are discussed here because they are useful in MongoDB.In JavaScript, people like to say "functions are first class objects", meaning that functions may be passed to other functions as parameters and may be returned by other functions. JavaScript arrays have a forEach() method, which will iterate through the array and apply a function to each element in the array. (Note that forEach can use each element of the array but it will not change the elements). The function to be applied by the forEach() method is provided to forEach as a parameter, and that function parameter will in turn have a parameter which refers to the entry in the array which you are indexing through. For example, in the code below showSq is the parameter to the forEach method, and in the showSq function its parameter, item, refers to the entry in the array: A= [1, 2, 3]; function showSq(item) {console.log(item*item)} A.forEach(showSq); //logs 1, 4, and then 9.If this is the only place in our code where we will use showSq, instead of writing the showSq function explicitly we may code it as an anonymous function – that is, put its definition inside the parentheses of forEach: A= [1, 2, 3]; A.forEach(function(item) {console.log(item*item)}); Anonymous functions are often used as callbacks: if a function foo executes some steps and then excutes a function bar, which is passed to foo as a parameter, then we say that bar is a callback function. Rather than passing in bar as a parameter we can define it anonymously inside foo as we did with forEach(): function foo(define bar here){ code for foo goes here}. You will also often see anonymous functions in event handlers: myVar.onclick = function() {do stuff} where myVar is some previously identified element on a web page.While the for loop is generally preferred in code for websites, the forEach method is useful in the MongoDB, when you want to apply a function to all the documents returned by a find() operation: db.someCollection.find().forEach( function(myDoc) { do some stuff); } )and here myDoc refers to the document which the cursor is pointing to as it iterates through the set that find() returned.Part II – The Cheat Sheet (R is included for data scientists)ConstructPythonJavaScriptRAssignment==<-Grouping statementsIndentation{ }{ }BooleansNo ( ) required, but : after condition( ) around condition( ) around conditionBoolean ConstantsTrue, Falsetrue, falseTRUE, FALSELogical and Arithmetic Operators==, != (or <> )<, <= etc.and, or, not+, -, *, / (use // for int. div)**, %==, !=<, <= etc.&&, ||, !+, -, *, / (gives floating div)**, %==, !=<. <=, etc.&, |, !+, -, *, /All above apply to vectors but use ^, % for numbers%/%, %% for vectorsIf - elseif condition: statementselse: other statementsif (condition) { statements } else { statements }Same as JavaScriptElse ifelifelseifNo shortened else-ifArrays and strings: Length of an array A or stringlen(A) Note:len is a function which may take an array or string as a parameter.A.length Note:length is a property of the array.length(A) Note:len is a function which may take an array as a parameter. Use nchar(s) for stringsComments#Comment-1 line<!—for html -->// for JS line/* longer JS */#Comment – 1 line<!—in R markdown -->if (FALSE) {“long comment”}What we call a 1-dimensional indexed list listarrayvector (or list)What we call a list of key:value pairsObject or associative arraydictionaryList or associative arrayPart III – What comes nextJavaScript in web pagesYou need to learn HTML and CSS to design a web page, and then you can use JavaScript to make the page interactive.Objects, functions, closuresIn JS almost everything – including functions - is an object. This means that functions can have their own properties and methods.We can write constructor functions, analagous to the _init_ method in Python classes, to create objects – and JavaScript offers many methods for creating objects which are based on other objects.Just as we had self in Python, we get this in JavaScript, which points to the object being created inside the constructor function, or to the object which called a function. Unlike Python, we don't need to name this explicitly when we write the constructor function – on the other hand, the use and value of this outside a constructor can be subtle and is a source of certain errors. It is a topic worth reading about.One of JavaScriptls most distinctive features is closures. Briefly, when a function outer() returns a function inner(), then the returned inner() has access to all of outer()'s local variables, even though outer() has finished executing. For example, in the code below, outer() has one parameter, x. Next outer() declares a local variable newSquare, which is x2, and then it defines a new function inner() which will multiply any value passed to inner () by newSquare. Then outer() returns this version of inner() and we assign it to foo. At that point outer() has finished executing, and we have a variable foo which holds the function which outer() has returnedNotice that inner() needs to know the value of newSquare, a local variable of outer(), in order to execute, and that when outer returns a function, which is assigned to foo, then foo also needs to know that value – even though outer() has finished executing. function outer(x) { var newSquare = x*x; //newSquare is a local variable in outer(), but //newSquare is also part of inner()'s context. function inner(y) { return y*newSquare; } // end of inner return inner; //outer is returning the function inner } foo = outer(10); //foo is now a function which multiplies its input by 102. console.log (foo(7)); // 700In fact, foo does have access to all the values which inner() had access to when it was being defined (aka the context of inner) , and this situation is called a closure. It is a very powerful feature of JavaScript and essential for how modules work in JS, ES6 and node.js.Protoypes and inheritanceIn JavaScript there is a hierarchy of objects (e.g. every Array is also an Object) and each object has a prototype (like a blueprint). You can add methods and properties to the prototype at the general level for the object (i.e. the class) and it will get added to all instances also. Inheritance in JavaScript is based on prototypes.Anonymous functions and callbacksAs discussed in paragraph o. of Part I,we can have anonymous functions, and callback functions. Callbacks are used extensively in more advanced JS coding, including in Ajax, event handling and node.jsModules and node.jsNode.js allows us to spin out servers and do back end programming in JavaScript. Various modules handle related tasks, such as fileIO, setting up a server, etc.Node.js uses ES6.ES6, and beyondPlain vanilla JavaScript has global variables, and variables which are local to a function, but nothing in between. ES6 (aka ES2015) introduced block-scope variables. It also introduced arrow functions, which are designed to avoid the complexities of this, and other ways to handle parameters, arrays, etc. Also, it added altermate syntax to allow us to write code which looks more like traditional OOP. Where to goThese days there is a plethora of free and excellent sites on these topics. The ACM Safari site has many excellent books, especially for the more advanced topics . For novices a good starting place is For a more sophisticated approach, start with the book by JD Isaacks or the one by Nikolas Zakas, and then move on to those by Douglas Crockford (for closures) and Kyle Simpson (for closures and ES6.) Finally, at you can find an extensive list of resources (including those mentioned here) from elementary to advanced by topic.ACKNOWLEDGEMENTS: The author gratefully acknowledges the comments of Dr. Ethel Schuster. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download