Hello everyone,
On this article I will describe some new functionalities that came to JS from the ES6 released (I know it is late). I was never really interested on that, even if I knew them, because they were widely not supported.
However, during the last year, most of the browsers have been updated and now support the last version of JavaScript.
You can see it here : https://kangax.github.io/compat-table/es6/
With end of life of Internet Explorer 10, most of the browser will support most of the ES6 syntax.
It is coming slowly that the old browsers will go out of commission or just stopped being supported by websites. So as a web analytics, you would need to know the latest techniques to track your different elements and being able to understand the new keywords or syntax that will populate your tracking files in the next years.
The new JavaScript keywords and functionalities are really close to “common” python syntax. Thus the pythonscript subtitle to this article. It is clear now that those 2 programming languages are coming closer together. They will always have basic differences, but where python is good for its simplicity, JavaScript is good for easy use of multi threading usability.
The fact that those 2 languages are merging is actually pretty cool as it will get easier and easier to integrate them together in your code.
Easy to get
I split the different part of new JavaScript functionalities into 2 different parts. The easy things to get for the new syntax. Things that are not new paradigms and will be easy to catch when you encounter them in the code.
The second part is more of structural changes into JavaScript. The arrow functions is quite important as more and more tutorials are using it and it is quite different from our old function declarations. I’ll let you see by yourself.
Default Value Parameters
This one is really a common one in Python,but not only Python, now you can define default value to parameters in a function. It means that if you don’t pass any value to the function, the default value will be used. Otherwise, the new value will overwrite the default value.
function MyNewFunction(x=0,y=0){
return x + y }
MyNewFunction() // returns 0
MyNewFunction(1) // returns 1
MyNewFunction(1,1) // returns 2
New Variables (let and const)
Finally, JavaScript decided to integrate a new way to scope the variable. Because let’s be honest here, the “var” thing was never a good idea. At least on its own. For a long time, users wanted to have something that would actually help them to better set the scope of their variables.
The let and const declaration keywords were introduced then.
The let keyword lets you give the variable the scope of the actual curly parenthesis.
The const keyword tells that the variable value should not move during the code run. So it helps to get the constants being constant.
for(i=0;i<10;i++){i+=1} //this will stop i at 10
/*new example*/
i = 0
for(let i=0;i<10;i++){i+=1} //this will keep i at 0
/*new example*/
const i = 0
for(i=0;i<10;i++){let i+=1} //this will throw an error at it tries to change a constant
Template string
The template string is a complete rip-off of the python functionality. OK not really a complete rip-off but it so much inspired that I have seen so many example of this explained with a print() function. 😀 😀
So let’s do the same and explain it with the same examples.
function print(arg1='something',arg2='interesting'){
console.log(`I am writing ${arg1} here, I hope it will be ${arg2} `)// using back quote here and the ${} for enveloping the variables.
}
print() // --> I am writing something here, I hope it will be interesting
The Sets
Yes, you are not dreaming, they basically imported the set data type into JavaScript. Do I really need to explain this one ?
I’ll do as this will add few keywords on my articles and improve my SEO ranking, probably… I mean, you never know… 😉
Sets are a way to find unique elements inside a list, the same way it is in Python. Set elements in JavaScript have also useful methods available.
myList = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9] // 18 elements
set = new Set(myList) // only 9 elements
/* Some methods : */
set.size // it is not length
set.has(1) // returns true
set.delete(1) // deletes the value in the set and returns true
set.has(1) // returns false
set.delete(1) // doesn't find it anymore so returns false
New For loop
I think you know where this is going 😉 . Staying within the Python rip-off, JavaScript introduce the for loop like python. I am actually not sure if this is a good idea. It will make it easier for newbies to do loop but at the same time, the old for(i;i<…) was pretty interesting to understand on how it actually works.
myList=['This','is','so','pythonic']
for (element of myList) {console.log(element)} /* note the "of" instead of "in" in python*/
Destructuring assignment
On this one, it is not quite like python but it still feels quite similar. The destructuring assignment enables you to unpack (python phrasing) the value of an iterable in a dynamic way.
Thanks to that, you don’t have to hard-code the value you want to retrieve.
myList = ['zero','one','two','three','four']
console.log(myList[0],' ... ',myList[2])
/*Thanks to dest.. assignment I am able to get a dynamic assignment of this list */
var [zero,,two,,] = ['zero','one','two','three','four']
console.log(zero,' ... ',two)
It works as well for dictionaries and the cool things is that you can pass these into functions.
myDict = {
'key1':'value1',
'key2':'value2',
'key3':'value3'
}
function advancedDestruct({key2,key3}){// here is the destructing taking place
console.log(`my function use the key2 here, with its value : ${key2}`)
console.log(`my function use the key3 somewhere else, with its value : ${key3}`)
}
/*be careful that the key are actually calling the values for the dict*/
Generators
Now we are going to a bit more complicated pythonic, euh… JavaScript things.
I would guess that not everyone has heard of generator when working with python, except for the range() function, maybe…
However, this functionality is quite useful on different level for more advanced scripts as they are yielding their value till you call for the next one, using… next()
Let’s do an example :
function* genx(){
yield 3
yield 2
yield 1
}
x = genx()
console.log(x) // no value --> generator expression waiting for a call
console.log(x.next()) //returns {value: 3, done: false}
console.log(x.next().value) //returns 2
console.log(x.next()) //returns {value: 1, done: false}
console.log(x.next()) //returns {value: undefined, done: true}
This is quite useful when you are using asynchronous tasks that need to have a certain state for an undefined amount of time.
Is it still JavaScript ?
Arrow Functions
The arrow functions is the most common thing that you will see in new tutorials on JS. It is a new way of defining functions, that for this part, is really not pythonic.
It adds a new layer of abstraction into functions that makes it harder for new comers to use/learn JavaScript. I am pretty sure it will freak up lots of new programmers when they start learning programming language with JS.
However it is quite useful when you want to concise your code and when you want to change some scope of the functions, without changing the logic of the function itself. Let’s look at 2 example on how one normal function becomes an arrow function.
function myFunc(param1,param2){
console.log(param1);
console.log(param2);
return param1
}
/*with arrow function*/
myFunc = (param1,param2)=>{console.log(param1);/* arrows & no need to use "function" keyword*/
console.log(param2); return param1}
Promise
Promises is one of the best feature that actually enters into the JS universe. This type of functions are quite useful when you are using asynchronous data but you want to wait for them to finish executing before doing something.
Thanks to the Promise, it is possible to build function or elements that work only when the asynchronous element has run, successfully or not.
In a promise, you define a function that actually takes 2 arguments :
- resolve : a function that returns an object when the promise successfully loads.
- reject : a function that returns an object when the promise fails.
Technically, the promise doesn’t return anything, that is what makes it quite hard to understand. It is passing the value inside the resolve and reject function to a “then” method.
This then method is using a function that use one argument, taking the object that has been passed on and using it, in the function. The then method takes the value pass in the resolve call. it is automatic, therefore the documentation about what type of object is return by the promise is very important.
For the reject, you can catch it by using the catch() method. Same methodology is working here.
Let’s do an example :
/*This is code preparation, it will only run when you will call the function with(out) then()*/
myPromise = (seconds) => new Promise(function(resolve, reject){
if(!isNaN(parseInt(seconds))){
setTimeout(function(){
resolve(seconds)},seconds*1000)
}
else{
setTimeout(function(){
reject(`After thinking about it.\n I think that "${seconds}" is not a number !`)},7000)
}
})
/*actual code running*/
myPromise(5).then((resolvedValue) => console.log(`I waited ${resolvedValue} seconds`)).catch((msg)=> console.error(msg))/*will return a console log*/
myPromise('a').then((resolvedValue) => console.log(`I waited ${resolvedValue} seconds`)).catch((msg)=> console.error(msg))
/*will return a console error*/
As you have seen, it can be quite useful to actually develop application that are waiting for some data.
As Web/Digital Analyst, I clearly see a big use case for us… the data layer !
/!\ IDEA /!\ : You could ask your IT to load a specific version of your tag manager or your tracking code when the data layer is loaded as expected and another version when there is an issue. Like a minimalist version of your code that doesn’t rely too much on the data layer.
Fetch
Fetch is actually a pretty neat application of the promises for retrieving libraries or data from another source, or another server. It makes the call for using API within your web pages pretty easy to handle.
When you use fetch , you can request for data through a call and use the response in the then function. The binding between those 2 is automatic, no need to worry about what the promise is supposed to return.
The response has a .json() methods that enables you to have a nice structure to manipulate.
fetch('http://my.awesome-api.com').then(/*do something with the response*/)
// a more advanced usage
fetch('http://my.awesome-api.com').then((response) => json= response.json()).then((json_res) => console.log(json_res))
/*Unfortunately, I don't have fake api to call yet, it exists and I will update this post when I find one that I like*/
There are still lots of new things that are available now in ES6 (symbols, setting your own iterator, async, await, class etc…) but I think that this covers the basic you need to know in order to understand the code and/or write your own code as technical web analyst.
I am interested in the async and await, as well as the class new functionalities, to see how much of python inspired these new things but as web analyst, I think I would never have to use it… except for node project, maybe…
Have fun coding !