Posts

Showing posts with the label JS

JavaScript functions

Functions are famously called first-class citizens of the JavaScript world. Functions can smoothly be treated as a variable,  For example, if we execute this in a browser: function myFunction(a, b) {   return a * b; } var x = myFunction; console.log(x(3,4)); It will log 12. The declaration of myFunction makes it a 'value', which is assigned to a variable 'x'. Notice that there are no parenthesis in that assignment. Next, we have a log that invokes myFunction by applying the parenthesis () operator on the variable. The log statement logs the return value of myFunction, which is the product of 3 and 4. Let's say we forget the parenthesis: console.log(x); This will log the function itself! Try it out in your browser by enabling the console display via the 'developer tools' option. Of course, this will just call the function normally: var x = myFunction(3,4); It's just the application of the () operator to call a...

JavaScript data-types

JavaScript is a versatile language that's used in programming everything from web pages to servers and desktop applications. We will use this interactive tutorial  as a reference in our journey. JavaScript is different from the other languages we've seen here (C++, C#, Java), in that it doesn't have a compiler. The code is interpreted while running it. This brings us to a distinction in data-types as well. JavaScript doesn't fix the type of its variables. For example, this is a valid sequence for the interpreter: var x;           // x is undefined to start with x = 15;          // After this assignment, x is a Number x = "Phil";      // Here x becomes a String Many other fun things can happen with JavaScript data, as you can see here . What could be the use of such flexibility? Tell us what you feel below. Hint: Think of real-life arrays - like array of vehicles, array of chat messages...