DEV Community

Cover image for Javascript the Confusing Parts: Part 1 Coercion, Let vs Const vs var
shahabbukhari
shahabbukhari

Posted on

Javascript the Confusing Parts: Part 1 Coercion, Let vs Const vs var

Javascript is one of the most popular languages on the internet. According to the StackOverflow, 2021 survey javascript is the most popular programming/scripting language in 2021.

Some People say javascript is a weird programming language sometimes it's true. In particular, because JavaScript has C/C++/Java-like syntax, which causes such developers to assume that it has similar semantics as well. When this turns out not to be the case, such developers often feel confused and frustrated. That said, for a person who is new to development, without prior experience in some other programming language, I don’t think JavaScript would seem stranger than most other languages that person might look at.

Untitled

In this series of articles, we will dive deep into the weird parts of javascript and try to understand how javascript actually works under the hood.

Javascript is not a terribly written language it just abstracts you away from how computer or browser that you will be using to run javascript. For this, we need to understand how these tools work. you may say you don’t need to understand these concepts for working with javascript but as we go along you will understand these fundamental concepts will help you have a concrete understanding of the concept and surely you will have some aha moments. and understanding these fundamental parts differentiate between good and average developers.

Coercion:

Starting from the meme. Coercion refers to the process of automatic or implicit conversion of values from one data type to another.

Untitled

How on earth 0 == "0" when 0 is an int and “0” is string. Welcome to the javascript world. In the world of javascript when you compare two values with == one value may go through coercion. JavaScript is a weakly-typed language, values can also be converted between different types automatically, and it is called implicit type coercion

Untitled

This just didn't stop here arrays(which is non-primitive in nature) also coerce into a string (primitive type). Since [] is an empty array hence it gets converted into an empty string.

Untitled

But But But if 0 == "0" is true and 0 == [] is true then why "0" == [] is false. thsi part will make sense if you understood the first two parts.
"0" is a string and [] is an object(that is another story why) then if your convert [] to string it will become "" an empty string. So "0" == "" is false.

2. Let Vs Const Vs Var:

With ES6 javascript surprise us with the new way to declaring variable in javascript with let and const in contrast to the old way of decllearing a variable with var.

Before starting a war between let, const and var first you need to understand two concpets Scope and Hoisting ?

Scope:

I would say that scope is the ‘environment’ in which a variable is accessible and visible and can be used. there are three type of scopes in javascript.

  1. Global Scope:

    When we declare a variable on our file, out of any function this is the global scope, so the variable is global, it is accessible and visible everywhere and it becomes property of the global object, e.g. window.

    var myVar = 'Hello World'
    
  2. Local Scope:

    Local variables are variables that are declared inside a function and they live and die when this function is executed.They are not available/accessible/visible outside of the function that it is created. For that reason, we can have many local variables with the same name without having any impact on the rest code.

    var name = "Shahab"
    console.log(name) // Shahab
    
    function myName() {
        var name = "Ali"
        console.log(name) // Ali
    }
    myName()
    console.log(name) // Shahab
    
  3. Block Scope:

    Local Variables are crreated inside function block level variables live and die inside a bock of code, like {}.

    Variables decleared with let and constare block scoped.

    function sayHello(flag){
      var name='shahab'; // local variable
      if(flag){
        const city = 'karachi'; // block scope variable, only accessible inside this if
        return `My name is ${name}, its cold in ${city}`;
      }
    
      return `My name is ${name}, its cold in ${city}`; // 
    }
    
    sayHello(true); // "My name is shahab, its cold in karachi"
    sayHello(false); // Uncaught ReferenceError: city is not defined
    

Hoisting:

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope within the scope regardless of where they are decleared, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.

Now back to the original disccussion of let vs const vs var. lets compare them one by one.

Var

Variables declared by var keyword are scoped to the immediate function body (hence the function/local scope) and the varibles decleared with var are hoisted top of the program and can be used before initalizing.

console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)
var num; // Declaration
num = 6; // Initialization
console.log(num); // Returns 6 after the line with initialization is executed.
Enter fullscreen mode Exit fullscreen mode

Let:

let variables are scoped to the immediate enclosing block denoted by {} (hence the block scope). Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

console.log(num); // Throws ReferenceError exception as the variable value is uninitialized
let num = 6; // Initialization
Enter fullscreen mode Exit fullscreen mode

Const:

constdeclarations share some similarities with letdeclarations. the only differnce is the value assigned with const remains same within its scope.

const name = "Shahab";
name = "Ali";// error: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

Every const declaration, therefore, must be initialized at the time of declaration.

Note: I said values assigned with const cannot be changed. in case of array and object(which are same we will learn in upcoming lectures) can be updated because object decleared with const does not store a values it stores a memory address(pointer) of those values any changes we make will on a memory address.

But why let and const existed...

The reason why let and const keyword was introduced to the language because of two main reason.

  1. Function/Local scope is confusing and was one of the main sources of bugs in JavaScript.
  2. Hoisting in JavaScript cause unexpected results.

Issue Caused by local scope:

for (var i = 0; i < 5; i++) { 
  for (var i = 0; i < 3; i++) { 
    console.log("hello world"); 
  } 
}
// hello world
// hello world
// hello world
// hello world
// hello world
// <repeats infinitely>
Enter fullscreen mode Exit fullscreen mode

you can solve this issue by just using let. which will convert iinto block scope and the refrence will be different in both for loops.

for (let i = 0; i < 5; i++) { 
  for (let i = 0; i < 3; i++) { 
    console.log("hello world"); 
  }
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
// hello world
Enter fullscreen mode Exit fullscreen mode

Unexpected Results Cause By Hoisting:

The tricky part is that only the declaration of the variable will be hoisted. If the variable is also initialized, the variable will be set to undefined when it is hoisted to the top. The variable value is changed from undefined to its initialized value when the execution reaches the variable.

var firstName = "Shahab";
console.log(firstName + ' ' + lastName);
var lastName = "Bukhari";

// Shahab Undefined
Enter fullscreen mode Exit fullscreen mode

This will not through an error but rendered it as default value of undefined that is even worse. to avoid this we use let or const.

let firstName = "Jennifer";
console.log(firstName + ' ' + lastName);
let lastName = "Bland";

//Cannot access 'lastName' before initialization
Enter fullscreen mode Exit fullscreen mode

This will help you to avoid errors before publishing your code publicaly.

Thanks of Reading:

If you read this so far surely you find this intresting and if you learn something consider following me. I will be continoning this series of Javacript the confusing parts follow me not to miss any future updates. Thanks

Top comments (0)