So you think you know JavaScript? - DEV Community 👩‍💻👨‍💻

JavaScript is an interesting language and we all love it because of its nature. Browsers are the home for JavaScript and both work together at our service.
JS has a few concepts where people tend to take it lightly and sometime may tumble over. Concepts like prototyping, closures and event-loops are still one of those obscure areas where most of the JS developers take a detour. And as we know “little knowledge is a dangerous thing”, it may lead to making mistakes.

Let’s play a mini-game where I am going to ask you a few questions and you have to try answering all of them. Make a guess even if you don’t know the answer or if it’s out of your knowledge. Note down your answers and then check the corresponding answers below. Give yourself a score of 1 for each correct answer. Here we go.

Disclaimer: I’ve used ‘var’ purposely in some of the following code snippets so that you guys can copy paste them into your browser’s console without running into SyntaxError problem.
But I don’t condone the usage of ‘var’ declared variables. ‘let’ and ‘const’ declared variables make your code robust and less error-prone.


Question 1: What will be printed on the browser console?

var a = 10;
function foo() {
    console.log(a); // ??
    var a = 20;
}
foo();

Question 2: Will output be the same if we use let or const instead of var?

var a = 10;
function foo() {
    console.log(a); // ??
    let a = 20;
}
foo();

Question 3: What elements will be in the “newArray”?

var array = [];
for(var i = 0; i <3; i++) {
 array.push(() => i);
}
var newArray = array.map(el => el());
console.log(newArray); // ??

Question 4: If we run the ‘foo’ function in the browser console, will it cause a stack overflow error?

function foo() {
  setTimeout(foo, 0); // will there by any stack overflow error?
};

Question 5: Will the UI of the page (tab) remains responsive if we run the following function in the console?

function foo() {
  return Promise.resolve().then(foo);
};

Question 6: Can we somehow use the spread syntax for the following statement without causing a TypeError?

var obj = { x: 1, y: 2, z: 3 };
[...obj]; // TypeError

Question 7: What will be printed on the console when we run the following code snippet?

var obj = { a: 1, b: 2 };
Object.setPrototypeOf(obj, {c: 3});
Object.defineProperty(obj, 'd', { value: 4, enumerable: false });

// what properties will be printed when we run the for-in loop?
for(let prop in obj) {
    console.log(prop);
}

Question 8: What value xGetter() will print?


var x = 10;
var foo = {
  x: 90,
  getX: function() {
    return this.x;
  }
};
foo.getX(); // prints 90
var xGetter = foo.getX;
xGetter(); // prints ??

Answers

Now, let’s try to answer each question from top to bottom. I will give you a brief explanation while trying to demystify these behaviors along with some references.

Answer 1: undefined.
Explanation: The variables declared with var keywords are hoisted[1] in JavaScript and are assigned a value of undefined in the memory. But initialization happens exactly where you typed them in your code. Also, var-declared variables are function-scoped[2], whereas let and const have block-scoped. So, this is how the process will look like:

var a = 10; // global scope
function foo() {
// Declaration of var a will be hoisted to the top of function.
// Something like: var a;

console.log(a); // prints undefined

// actual initialisation of value 20 only happens here
   var a = 20; // local scope
}

Answer 2: ReferenceError: a is not defined.
Explanation: let and const allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. Unlike var, these variables are not hoisted and have a so-called temporal dead zone[3] (TDZ). Trying to access these variables in TDZ will throw a ReferenceError because they can only be accessed until execution reaches the declaration. Read more about lexical scoping[4] and Execution Context & Stack[5] in JavaScript.

var a = 10; // global scope
function foo() { // enter new scope, TDZ starts

// Uninitialised binding for 'a' is created
    console.log(a); // ReferenceError

// TDZ ends, 'a' is initialised with value of 20 here only
    let a = 20;
}

The following table outlines the hoisting behaviour and scoping associated with different keywords used in JavaScript (credit: Axel Rauschmayer's blog post[6][7]).


Answer 3: [3, 3, 3].
Explanation: Declaring a variable with var keyword in the head of for loop creates a single binding (storage space) for that variable. Read more about closures[8]. Let’s look at the for loop one more time.

// Misunderstanding scope:thinking that block-level scope exist here
var array = [];
for (var i = 0; i < 3; i++) {
  // Every 'i' in the bodies of the three arrow functions
  // referes to the same binding, which is why they all
  // return the same value of '3' at the end of the loop.
  array.push(() => i);
}
var newArray = array.map(el => el());
console.log(newArray); // [3, 3, 3]

If you let-declare a variable, which has a block-level scope, a new binding is created for each loop iteration.

// Using ES6 block-scoped binding
var array = [];
for (let i = 0; i < 3; i++) {
  // This time, each 'i' refers to the binding of one specific iteration
  // and preserves the value that was current at that time.
  // Therefore, each arrow function returns a different value.
  array.push(() => i);
}
var newArray = array.map(el => el());
console.log(newArray); // [0, 1, 2]

Another way of solving this quirk would be to use closures[9].

// After understanding static scoping and thus closures.
// Without static scoping, there's no concept of closures.
let array = [];
for (var i = 0; i < 3; i++) {
  // invoking the function to capture (closure) the variable's current value in the loop.
  array[i] = (function(x) {
    return function() {
      return x;
    };
  })(i);
}
const newArray = array.map(el => el());
console.log(newArray); // [0, 1, 2]

Answer 4: No.
Explanation: JavaScript concurrency model is based on an “event loop”. When I said “Browsers are the home for JS”, what I really meant was that browsers provide runtime environment to execute our JavaScript code. The main components of the browser include Call stack, Event loop, Task Queue and Web APIs. Globals functions like setTimeout, setInterval, and Promise are not the part of JavaScript but the Web APIs. The visual representation of the JavaScript environment can be something like as shown below:

alt text

JS call stack is Last In First Out (LIFO). The engine takes one function at a time from the stack and runs the code sequentially from top to bottom. Every time it encounters some asynchronous code, like setTimeout, it hands it over to the Web API (arrow 1). So, whenever an event is triggered, the callback gets sent to the Task Queue (arrow 2).

The Event loop is constantly monitoring the Task Queue and process one callback at a time in the order they were queued. Whenever the call stack is empty, the loop picks up the callback and put it into the stack (arrow 3) for processing. Keep in mind that if call stack is not empty, event loop won’t push any callbacks to the stack.

For a more detailed description of how Event loop works in JavaScript, I highly recommend watching this video[10] by Philip Roberts. Additionally, you can also visualise and understand the call stack via this awesome tool[11]. Go ahead and run the ‘foo’ function there and see what happens!

Now, armed with this knowledge, let’s try to answer the aforementioned question:

Steps

  1. Calling foo() will put the foo function into the call stack.
  2. While processing the code inside, JS engine encounters the setTimeout.
  3. It then hands over the foo callback to the WebAPIs (arrow 1) and returns from the function. The call stack is empty again.
  4. The timer is set to 0, so the foo will be sent to the Task Queue (arrow 2).
  5. As, our call stack was empty, the event loop will pick the foo callback and push it to the call stack for processing.
  6. The Process repeats again and stack doesn't overflow ever.

Answer 5: No.
Explanation: Most of the time, I have seen developers assuming that we have only one task queue in the event loop picture. But that’s not true. We can have multiple task queues. It’s up to the browser to pick up any queue and processes the callbacks inside.

On a high level, there are macrotasks and microtasks in JavaScript. The setTimeout callbacks are macrotasks whereas Promise callbacks are microtasks. The main difference is in their execution ceremony. Macrotasks are pushed into the stack one at a time in a single loop cycle, but the microtask queue is always emptied before execution returns to the event loop including any additionally queued items. So, if you were adding items to this queue as quickly you’re processing them, you are processing micro tasks forever. For a more in-depth explanation, watch this video[12] or article[13] by Jake Archibald[14].

Microtask queue is always emptied before execution returns to the event loop

Now, when you run the following code snippet in your console:

function foo() {
  return Promise.resolve().then(foo);
};

Every single invocation of ‘foo’ will continue to add another ‘foo’ callback on the microtask queue and thus the event loop can’t continue to process your other events (scroll, click etc) until that queue has completely emptied. Consequently, it blocks the rendering.


Answer 6: Yes, by making object iterables[15].
Explanation: The spread syntax[16] and for-of[17] statement iterates over data that iterable object defines to be iterated over. Array or Map are built-in iterables with default iteration behaviour. Objects are not iterables, but you can make them iterable by using iterable[18] and iterator[19] protocols.

In Mozilla documentation, an object is said to be iterable if it implements the @@iterator method, meaning that the object (or one of the objects up its prototype chain[20]) must have a property with a @@iterator key which is available via constant Symbol.iterator.

The aforesaid statement may seem a bit verbose, but the following example will make more sense:

var obj = { x: 1, y: 2, z: 3 };
obj[Symbol.iterator] = function() {
  // An iterator is an object which has a next method,
  // which also returns an object with atleast
  // one of two properties: value & done.

  // returning an iterator object
  return {
    next: function() {
      if (this._countDown === 3) {
        const lastValue = this._countDown;
        return { value: this._countDown, done: true };
      }
      this._countDown = this._countDown + 1;
      return { value: this._countDown, done: false };
    },
    _countDown: 0
  };
};
[...obj]; // will print [1, 2, 3]

You can also use a generator[21] function to customize iteration behaviour for the object:

var obj = { x: 1, y: 2, z: 3 };
obj[Symbol.iterator] = function*() {
  yield 1;
  yield 2;
  yield 3;
};
[...obj]; // print [1, 2, 3]

Answer 7: a, b, c.
Explanation: The for-in loop iterates over the enumerable properties[22] of an object itself and those the object inherits from its prototype. An enumerable property is one that can be included in and visited during for-in loops.

var obj = { a: 1, b: 2 };
var descriptor = Object.getOwnPropertyDescriptor(obj, "a");
console.log(descriptor.enumerable); // true
console.log(descriptor);
// { value: 1, writable: true, enumerable: true, configurable: true }

Now having this knowledge in your bag, it should be easy to understand why our code printed those specific properties:


var obj = { a: 1, b: 2 }; // a, b are both enumerables properties

// setting {c: 3} as the prototype of 'obj', and as we know
// for-in loop also iterates over the properties obj inherits
// from its prototype, 'c' will also be visited.
Object.setPrototypeOf(obj, { c: 3 });

// we are defining one more property 'd' into our 'obj', but
// we are setting the 'enumerable' to false. It means 'd' will be ignored.
Object.defineProperty(obj, "d", { value: 4, enumerable: false });

for (let prop in obj) {
  console.log(prop);
}
// it will print
// a
// b
// c

Answer 8: 10.
Explanation: When we initialised x into the global scope, it becomes the property of the window object (assuming that it’s a browser environment and not a strict[23] mode). Looking at the code below:

var x = 10; // global scope
var foo = {
  x: 90,
  getX: function() {
    return this.x;
  }
};
foo.getX(); // prints 90
let xGetter = foo.getX;
xGetter(); // prints 10

We can assert that:

this will always point to the object onto which the method was invoked. So, in the case of foo.getX(), this points to foo object returning us the value of 90. Whereas in the case of xGetter(), this points to the window object returning us the value of 10.

To retrieve the value of foo.x, we can create a new function by binding the value of this to the foo object using Function.prototype.bind[24].

let getFooX = foo.getX.bind(foo);
getFooX(); // prints 90

That’s all! Well done if you’ve got all of your answers correct. We all learn by making mistakes. It’s all about knowing the ‘why’ behind it. Know your tools and know them better. If you liked the article, a few ❤️ will definitely make me smile 😀.

What was your score anyway 😃?

References

  1. ^ hoisted (developer.mozilla.org)
  2. ^ function-scoped (2ality.com)
  3. ^ temporal dead zone (exploringjs.com)
  4. ^ lexical scoping (2ality.com)
  5. ^ Execution Context & Stack (davidshariff.com)
  6. ^ Axel Rauschmayer (twitter.com)
  7. ^ post (exploringjs.com)
  8. ^ closures (dmitrysoshnikov.com)
  9. ^ closures (dmitrysoshnikov.com)
  10. ^ video (www.youtube.com)
  11. ^ tool (latentflip.com)
  12. ^ video (www.youtube.com)
  13. ^ article (jakearchibald.com)
  14. ^ Jake Archibald (twitter.com)
  15. ^ iterables (developer.mozilla.org)
  16. ^ spread syntax (developer.mozilla.org)
  17. ^ for-of (developer.mozilla.org)
  18. ^ iterable (developer.mozilla.org)
  19. ^ iterator (developer.mozilla.org)
  20. ^ prototype chain (developer.mozilla.org)
  21. ^ generator (developer.mozilla.org)
  22. ^ enumerable properties (developer.mozilla.org)
  23. ^ strict (developer.mozilla.org)
  24. ^ Function.prototype.bind (developer.mozilla.org)
keywords software development, inclusive, community,engineering,javascript, closures, eventloop, webdev

No Items Found.

Add Comment
Type in a Nick Name here
 
Other Items in webdev
Font Awesome Icons [ Icons ] - CSS Bundle Daily Dev Tips CSS Background Patterns by MagicPattern GitHub - ganlanyuan/tiny-slider: Vanilla javascript slider for all purposes. GitHub - jonasstrehle/supercookie: ⚠️ Browser fingerprinting via favicon! URL-encoder for SVG Bootstrap Icons · Official open source SVG icon library for Bootstrap GitHub - kognise/water.css: A drop-in collection of CSS styles to make simple websites just a little nicer Toggle light and dark themes in Bootstrap - DEV Deploy your Publish website for free on GitHub Pages - DEV Bootstrap · The most popular HTML, CSS, and JS library in the world. GitHub - diegocard/awesome-html5: A curated list of awesome HTML5 resources Fixing PHP SQLite database is locked warning - Unable to execute statement: database is locked [ php ] - KruXoR openstreetmap.org 50 Developer tools to make your life a little easier https://www.mrlacey.com/2020/07/youve-only-added-two-lines-why-did-that.html?m=1 GitHub - ForEvolve/bootstrap-dark: Bootstrap 4 dark theme that supports togging dark/light themes as well. There is no fluff, it changes the color of Bootstrap and that's it, no new thing to learn or unlearn, just Bootstrap, but Dark! Responsive Web Design Online Testing - isResponsive Trianglify.io · Low Poly Pattern Generator Grid.js - Advanced table plugin HEAD - A free guide to <head> elements Roots | Modern WordPress Development Tools A Local Dev Tool For Every Project | Lando new.css Synchronized responsive testing, development, inspection | Vanamco Gold Price Charts Widgets | GoldBroker.com Trianglify.io · Low Poly Pattern Generator Special tags that Google understands - Search Console Help 404 Error Page Codepen ScrollMagic ♥ Demo AOS - Animate on scroll library Font Awesome v4.7.0 - Icon Search Tool Carbon Offers — LowEndTalk Featherlight – The ultra slim jQuery lightbox. Tailwind CSS - A Utility-First CSS Framework for Rapidly Building Custom Designs HEAD - A free guide to <head> elements API Blueprint | API Blueprint Filtering Data Client-Side: Comparing CSS, jQuery, and React | CSS-Tricks CSS Quickies: CSS Variables - Or how you create a 🌞white/🌑dark theme easily - DEV Community 👩‍💻👨‍💻 Responsive Slider Timeline Colormind - the AI powered color palette generator Get Waves – Create SVG waves for your next design Nuxt.js - The Vue.js Framework CodeSandbox: Online Code Editor Tailored for Web Application Development Hover.css - A collection of CSS3 powered hover effects Live.js - One script closer to Designing in the Browser Color this sofa! – SVG + Blend Mode trick You Might Not Need jQuery CSS Wave Animation with a .png
Search Linx
Search Linx by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code here, mostly for my reference. Also if i find a good link, i usually add it here and then forget about it. more...

Subscribe to weekly updates about things i have added to the site or thought interesting during the last week.

You could also follow me on twitter or not... does anyone even use twitter anymore?

If you found something useful or like my work, you can buy me a coffee here. Mmm Coffee. ☕

❤️👩‍💻🎮

🪦 2000 - 16 Oct 2022 - Boots
Random Quote
Treasure every moment that you have and treasure it more because you shared it with someone special, special enough to spend your time...and remember that time waits for no one.
Unknown
Random CSS Property

:playing

Experimental: This is an experimental technologyCheck the Browser compatibility table carefully before using this in production.
:playing css reference