Friday 29 December 2023

Understanding Rest & Spread operator in Javascript

 Background

In JavaScript, we tend to use rest & spread operators to keep code simple and easy to read. Both use three dots "..." but the use cases are different. In this post, we will see what these operations are and how to use them.


Before we proceed to looking into individual aspects just remember rest is for collecting elements and spread is for spreading elements. 

Rest operator

Let's try to see the rest operators 1st. The rest operator is used to collect the remaining elements in an array. The rest syntax works in both function arguments and arrays. Let's look at an example below



As you can see whatever number of arguments you pass to add function is going to capture 1st two in a & b respectively (in this case 1 & 2) and the remaining ones (values - [3, 4]) will be captured in an argument called rest which is an array.

The rest operator is also used for destructuring arrays like below

Spread operator

The Spread operator introduced in ES6 as the name suggests is used to spread the elements.
For eg, in the above code, you can see how "123" was split automatically into 1,2 & 3 by the spread operator.

We can also use this operator to easily create copies of arrays and objects. For eg.,



 NOTE: Spread operator helps maintain immutability requirements. This is helpful when you need data that should not mutate (Eg. Redux state).

As I mentioned before rest and spread operators are used commonly in javascript and we will see more usages and examples in upcoming posts.

Related Links




Closures in Javascript

 Background

In one of the earlier posts, we saw how to use Javascript (JS) closures to hide variables from the console with a counter-example. In this post, I will explain JS closures in more detail.

Closures in Javascript

Quoting closures from MDN web docs:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

It's important to note that it is not just a function but a combination of function + referenced to its lexical environment.  

Let's take a simple example:

(() => {
    var name = "Aniket";
    const displayName = () => {
        console.log(name);
    }
    displayName();
})()

The (()=>{})() is a self-executing function. Inside it, you can see an anonymous function defined using the arrow operator. Inside this function, we have defined a variable called name and again an anonymous function called displayName which prints the name variable in the console. 

What is interesting to note here is that even though the variable name is local to the outermost anonymous function we can still access it inside the displayName method, this is possible due to closures. When we created an anonymous function & assigned it to the displayName const variable it actually created a closure that comprised of the function itself + the reference to the lexical environment which includes the name variable defined in the outer scope.

NOTE: Nested functions have access to variables declared in their outer scope.

Understanding scopes

In the above examples, the variable name was defined in a function and had functional scope. It was accessible in that function + the methods nested inside it. It will not be accessible in the global scope. 

Before ES6 there were just two scopes, function scope and global scope. variables defined inside a function had function scope where whereas those defined outside had global scopes. This came with its own challenges as now if you define variables inside if else block braces then it creates a global scope because blocks with curly braces do not create scopes.

Eg. see below

Here check variable even though was defined inside the if block has become a global scoped variable (Unlike other languages like Java where it would have created a local scoped variable). 

To handle this ES6 introduced two new declarations
  • let - defines a variable local to the scope
  • const - defines a constant variable again local to the scope.
See below for example:





NOTE: Closure gives the function access to its outer function but the outer function can also be a nested function inside another outer function. In such cases, the innermost function will have access to all the outer nested functions via the closure chain. See eg below



Interesting examples

Now let's see some interesting examples before we wind this up.

See the below examples & predict the output

const myName = ["Aniket", "Abhijit", "Awantika"];
for(var i; i<myName.length;i++)
{
	setTimeout(function(){
    	console.log('Name: ' + myName[i] + 'at index:' + i);
    },3000)
}

The output is


It prints undefined as Name & index as 3 all the three times the loop executes. Let's try to understand why this happened: When we pass a custom function inside setTimeout it creates a closure of the function bundled with the captured environment from the out functions scope. Three closures are created by the loop but each shares the same lexical environment which has the variable "i" with changing values. This is because the "i" variable is defined as var and has a global scope. The value of "i" in the passed function is determined when it is actually executed after the timeout completes (when it comes from the event loop). Since the loop has already been completed by the time these closures from the event loop are executed "i" points to 3 and there is no such index in that array as the size is 3 and the index range from 0 to 2. Hence it prints "i" as 3 and the name as "undefined" three times - one for each closure created in the loop.

You can fix this by using a wrapper function to be passed inside setTimeout API argument which will create its own closure with the actual local value of "i" and pass it to the event table instead of just the original closure which is pointing to global scoped "I". Eg see below where I have given two ways one using function keyword and one using anonymous function



Or you could simply change var to let in the for loop which will create a block-scoped variable instead of a global scope and changes will still work fine.



Related Links

Sunday 2 October 2022

How to fix Apostrophes and double quotes not showing up in Windows

 Background

Recently I started using Windows 11 and realized Apostrophes (Single quotes) and double quotes not showing up until I type in the next letter. This behavior is really annoying, especially for me (I am from India/Asia) if you are wondering 😄 . This is most probably because you are using a US-international keyboard. In this post, I will show you how to fix this behavior.


Fixing "Apostrophes and double quotes not showing up in Windows"

As I mentioned before the issue is with you using the US-international keyboard. So you need to fix that.

I am using "Windows 11" so the below steps are keeping that in mind, but you would have similar steps in another version of Windows.


  1. Select Start > Settings > Time & language > Language & region.
  2. Under Preferred languages, select the options from 1st language you are using and click on "Language Options".




  3. Next, go under "Keyboards", here you will see the "US-International" keyboard installed. We need to remove this.
  4. Let's add the Keyboard we intend to use 1st. I am adding English (India) but you can choose the keyboard you want (Let's say English (United Kingdom)).
  5. Now select "US-International" keyboard from the list.


  6. Changes should immediately take effect.

Related Links

How to move TaskBar to the top or side in Windows 11

 Background

I recently started using Windows 11 and noticed there is no way to move windows TaskBar around. It is permanently fixed toward the bottom of the screen. I personally need the TaskBar towards the left or right of the screen and here's why - Our screen (Desktop or Laptop has more horizontal space than vertical space, hence it's only logical to keep TaskBar on the left or right of the screen so that it takes only horizontal space). Though there is no good way to move the TaskBar around there is a registry edit hack that does the trick. 

NOTE: If you are a normal windows user (Have not worked on programming and Windows internals before), I would recommend not to do the below but just live with TaskBar being on the bottom. Follow the below steps only if you know what you are doing and your own risk.

How to move TaskBar to the top or side in Windows 11

  1. Open "Windows Start" and search for "regedit" OR
  2. Go to "Run" (using ⊞ Win+R) and type "regedit" and press enter.




  3. You will get a prompt asking if you want to let the current user make changes to "Registry Editor". Press Ok.
  4. Next from the left hierarchy panel, you need to go to the following entry:
    HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3
    
  5. Double-click the Settings binary key.

  6. Under "Value data" section click on the entry with the 2nd row and the 6th column (The default value would be 03). 




  7. Press the delete key and replace it with the 01 value to move the taskbar to the top. Press ok.


  8. You can replace them with the following values as you desire
    • 00: Move the Taskbar to the left
    • 01: Move the Taskbar to the top
    • 02: Move the Taskbar to the right
    • 03: Move the Taskbar to the bottom
  9. For changes to take effect you need to restart the "Windows Explorer" process.
    1. You can go to "Task Manager" and restart the "Windows explorer" process. OR
    2. Do it via "Command prompt" via the following commands.
      1. Open the command prompt from the start menu or from the run menu(⊞ Win+R) and "cmd" command.
      2. "taskkill /f /im explorer.exe"
      3. "start explorer.exe"

You will then see Taskbar move to the top of the screen.



NOTE: With the above steps, you can move the TaskBar to the right or left as well, but it's useless (It does not work as expected). Hopefully, Windows 11 team fixes this sooner but we have to live with it for now. I personally am not happy with the above as I really want my TaskBar on the right due to the reasons mentioned in the "Background section" at the top.



Thursday 29 April 2021

How to fix issue of not able to click anything on Windows 10

 Background

Recently I came across an issue in Windows 10 where I was not able to click on icons. This was a relatively weird issue. What was happening is - I could click either on icons on the taskbar or icons on the desktop but not both. Also, cancel, minimize buttons won't work. This happened when I switched my mouse from USB to wireless. Anyways there are few ways we can fix this which I have listed below.

  1. Restart PC
  2. Restart File Explorer
  3. Use sfc (system file scanner)

Restart PC

Well, why not? This fixed the problem. There is not a lot of problems that restarting cant fix. But this is associated with system reboot time which I hate. I tried this for few times but quickly got tired of it. Restart every time I switch my mouse? Bad idea.


Restart File Explorer

If the issue was with explorer we could quickly try to kill File explorer and restart it. Go to Task Manager by
  • Ctrl + Alt + Delete
  • Ctrl + Shift + Escape
Find Windows Explorer and kill it



You can select the process and click delete. Or right-click and end process. To start it back in the same task manager go to File -> Run New Task (You can Also to Alt+F to open the file menu and then click and then click 'n' for new task)

Once you open a new task window - enter explorer in it and press enter.
Your windows explorer will start again.


Use Systems file checker (SFC)

This is what I use nowadays to fix this issue. My guess is some files get corrupted when I switch mouse or maybe the driver is buggy .. who knows! But running the following command fixes all.

Make sure you run the below command as administrator from the command prompt.
  • sfc /scanall


And the best part - No reboot required. This does take a couple of mins. But you can try browsing or something else at that time :)



t> UA-39527780-1 back to top