I constantly play with Javascript and time to time read other people’s code. Also checking new proposals here. When I read and code lots of different expressions arise and in Javascript, I believe I’ll always find interesting things. Here are some pieces of knowledge that I think you’ll find interesting.
For Await
Generators is an unintuitive topic for newcomers and maybe some seasoned developers too. Generators are basically functions which yield the next value at every iteration call which is generatorFunction.next(). Here is an example. Let’s write a very simple generator function.
function* myFirstGenerator(num) { yield 2 * num; yield 3 + num; }
There are two ways to extract values from it.
const result = myFirstGenerator(1) result.next() // returns {value: 2, done: false} result.next() // returns {value: 4, done: false} result.next() // returns {value: undefined, done: true}
Here we called the generator function into a variable. We provided a number as a parameter, in this case, it is 1. The function will yield us 1 * 2 and 3 + 1 respectively in each iteration. When the function finishes, it will return undefined. You may think it’s not a good idea to call the next function for each iteration, then you do this
// You can/should add const or let before result but I omitted you to understand the code better for (result of myFirstGenerator(1) { console.log(result); } // First prints: 2 // Then prints: 4
A for loop is possible for generators so you can have better expressions in your program. The very interesting is when you want some result from a generator function with fixed time intervals you have a different way of expressing that.
let i = 0; function* allNumbers() { while(true) { yield new Promise((resolve, reject) => { setTimeout(() => resolve(i++), 1000); }); } } for await(number of allNumbers()) { console.log(number); } // Prints: // 1 // 2 // 3 // 4 // 5 // . // . // .
You get the idea, it’s a mixture of for and await. Also, the trick we did in generator function is important. Let’s look at what it is.
BONUS: Promisifying
You probably heard or experienced callback hell. Or “then” chains of promises. ES7 introduced async/await for a better coding style and it did good. To avoid these hells, you should promisify your callback
const fs = require("fs"); function getRecords() { // Get records may not be a good name, you must find the fine line between being too verbose and losing the context return new Promise((resolve, reject) => { fs.readFile("records.txt", (err, data) => { // "err, data" order is a convention, you can use it at most of the places if(err) return reject(err); // We must stop execution of next line with return resolve(data); }); }) } (async function() { const records = await getRecords(); console.log(records); // Prints records.txt })();
This is called promisifying and as you can see in the main IIFE it gives us to the ability to write our code nicely instead of hells.
A Strange Expression Statement
I was reading lodash’s source code and saw something – at least for me – very strange.
function newStack(stack) { stack || stack = new Stack return stack; };
This is the main idea. There are many expression statements in Javascript, even the i++ you use every day is an expression statement. In this case, code sets the stack variable from parameter if the parameter is provided, if not, create a new “Stack” object and set it. Where are the parentheses of “new Stack” expression? They are not compulsory so you are free not to use them. If you are curious here are the occurrences of this type of code in the lodash library.
Another Way of IIFE
I’ll keep it short, you can immediately invoke a function with code like below
!function() { console.log("hey"); }() // prints "hey" and returns true
Private Variables of a Class
Do you remember from this article that putting an underscore doesn’t make a variable private in a class? Well, putting a hash sign does.
class SomeClass { #priv_var = 1 } // you can't react to priv_var
Tell Me the Truth
In a programming assessment, I saw an expression like this
!~-1 // returns true
I executed it and it returned true. Was curious how is that possible and then cracked it. “!” is a negation operator, which also makes everything following a boolean. “~” is a bitwise not operator and “-1” is a regular number. Bitwise not of “-1” is “0”, “0” is a falsy value in Javascript, if you negate 0 which is also false, you get “true”.
I continued to this series as I planned and more will come, hope you liked it. If you want to ask something or just say your good wishes, don’t forget to comment. You can share the post with others if you think they will benefit. Also, you can subscribe by clicking here for more well-thought and unique content. I wish you a good day.
Curiosity. I believe in the power knowledge gives, amplified by the interconnected net: the internet. Since my childhood, I am into programming and coding almost every day for 19 years. Complexity and the sophistication of the problems I would like to tackle only increased. I want to understand. I am a happy man when I understand the underlying mechanism of the Sha256 algorithm. I am a happy man when I invent and discover. Intellectuality and goodwill are my bedrock in my life.