# JavaScript Fundamentals That Finally Make Sense

## ***Template literals (Template strings)***

***Template literals*** are ***literals delimited*** *(determine the limit or boundary)* with ***back-ticks \`\`*** (`define string here`) characters for declaring ***strings***, allowing for ***multi-line strings***, ***string interpolation*** with ***embedded expressions.***

```javascript
let name = 'Ayan'; 
console.log(`Hello ${name}`); // Hello Ayan
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong><em>Embedding variables:</em></strong>&nbsp;<em>Template literals</em> like <code>Hello ${name}</code> insert <em>variable values</em> directly into <strong><em>strings</em></strong>, producing output such as <code>hello Ayan</code>.</div>
</div>

***Cleaner concatenation:*** They avoid using `+`, making ***string*** creation more readable and easier to write.

> **Template literals take all the** `number` **values and converts them into** `string`**.**

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/dfec36da-8315-4cb8-97eb-5ae9aa1de703.jpg align="center")

## `Truthy` ***and*** `Falsy` ***values***

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong><em>Those values can be called as </em></strong><code>true</code><strong><em> or </em></strong><code>false</code><strong><em> in </em></strong><code>Boolean</code><strong><em> context.</em></strong></div>
</div>

### ***falsy values***

A ***falsy*** value is a value that is considered `false` when encountered in a `Boolean` context.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong><em>falsy values</em></strong><em> are values that are not exactly </em><code>false</code><em>, but will become </em><code>false</code><em> when we try to convert them into a </em><code>boolean</code><em>.</em></div>
</div>

JavaScript uses ***type coversion*** (explicit conversion) to ***coerce*** (implicit convert) any value to a `Boolean` in contexts that require it, such as `conditional` and `loops`.

```javascript
false, undefined, NaN, null, "", 0, 0n, -0
```

### ***truthy values***

In JavaScript a **truthy** value is a value that is considered **true** when encountered in a **Boolean** context.

```javascript
true, 1, "Ayan"
```

> Except **falsy** all values are **truthy**.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/45723fbf-92da-4934-a37e-45027f29bf9d.jpg align="center")

### *Type coercion*

Type ***coercion*** is the ***automatic or implicit conversion*** of values from ***one*** data type to ***another*** (such as `strings` to `numbers`).

```javascript
const value1 = "5";
const value2 = 9;
let sum = value1 + value2;

console.log(sum); // 59
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><em>It happens whenever </em><strong><em>an operator</em></strong><em> is dealing with </em><strong><em>two values</em></strong><em> that have </em><strong><em>different type</em></strong><em>, behind the scene JavaScript </em><strong><em>convert one</em></strong><em> of the values to </em><strong><em>match</em></strong><em> the other value.</em></div>
</div>

***Explanation***

JavaScript has ***coerced*** the `9` from a `number` into a `string` and then ***concatenated*** the two values together, resulting in a `string` of `59`.

JavaScript had a choice between a `string` or a `number` and decided to use a `string`.

***Why?*** Because it’s defined in it’s `engine`.

*The compiler could have* ***coerced*** *the* `5` *into a* `number` *and returned a* ***sum*** *of* `14`*, but it did not.*

*To return this result, you'd have to* ***explicitly*** ***convert*** *the* `5` *to a* `number` *using the* [*Number()*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) *method:*

```javascript
console.log(Number("9" + 5); // 14
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/2f92b957-2f17-4f38-9342-fb28ba91d59f.jpg align="center")

### ***How Type Coercion Works?***

In JavaScript, ***type coercion*** mainly occurs in the ***three*** ways:

***String Coercion***

*It occurs when the* `string` *is combined with the* ***non-string*** *using* `(+)`*. JavaScript converts* `numbers` *and* `booleans` *into* `strings` *before concatenation.*

```javascript
console.log("5" + 2); //52
console.log("5" + true); //5true
```

*   *The number* `2` *is* ***coerced*** *to a* `string` *and then concatenated with the* `string "5"`*, resulting in* `"52"`*.*
    
*   *The* `boolean true` *is* ***coerced*** *into the* `string "true"`*, and the* ***two*** `strings` *are concatenated.*
    

***Number Coercion***

*In the* `number` ***coercion***\*, JavaScript converts the\* `string` *into a* `number` *before operating.*

```javascript
console.log("5" - 2); //3
console.log("5" * 2); //10
console.log("10" / "2"); //5
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><em>With </em><code>+</code><em> operator, JavaScript performs </em><strong><em>concatenation</em></strong><em>. Except </em><code>+</code><em> operator, JavaScript performs </em><strong><em>arithmetic operations</em></strong><em>.</em></div>
</div>

***Boolean Coercion***

*JavaScript treats the* `truthy / true` *value as* `1` *and the* `falsy / false` *value as* `0`*.*

```javascript
console.log(Boolean("hello")); //true
console.log(Boolean(0)); //false
console.log(Boolean([])); //true
```

> **Non-empty** `strings` are **coerced** to `true`, while `0` is **coerced** to `false`.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/9418b068-2d26-41e0-b365-749d77545d63.jpg align="center")

### ***Common Issues of Type Coercion***

***Comparing Different Data Types***

***Comparison Operator*** `(==)`*, allows* ***coercion*** *due to which the* ***unexpected conversions*** *occur. To avoid this, we should use the* ***strict equality*** `(===)` *operator.*

```javascript
console.log(0 == "0"); //true
console.log(0 == false); //true
console.log(" " + 0 == 0); //true
```

***Operations on null and undefined***

`Null` *and* `undefined` *behave unexpectedly.*

```javascript
console.log(null == undefined); //true
console.log(null === undefined); //false
console.log(null + 1); //1
```

`NaN` ***Comparisons***

`NaN` *is not equal to* ***itself***\*, so checking with\* `isNaN()` *is the best way to detect it.*

```javascript
console.log(NaN == NaN); //false
console.log(isNaN(NaN)); //true
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/64f412cb-9c0d-4fb6-a6dc-d450c2109a3e.jpg align="center")

### ***Best Practices to Avoid Type Coercion Issues***

***Use*** `===` ***Instead of*** `==`

*When we use* ***strict equality*** `(===)`*, instead of the* ***comparison operator / loose equality*** `(==)`*, it prevents unnecessary types of* ***coercion***\*.\*

```javascript
console.log(5 === "5"); //false
```

`===` *ensures no* ***implicit type conversion*** *occurs and both values must be of the* ***same*** *type.*

***Use Explicit Conversion***

***Explicit conversion*** *converts the value* ***manually*** *due to which there are fewer chances of errors in the code.*

```javascript
console.log(Number("123")); //123
```

*This ensures that you're working with the* ***correct type***\*, reducing the chance of errors during operations.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/ed028f20-e53b-4bb8-96eb-ec49b706fe2b.jpg align="center")

***Avoid False Value Confusion***

> Always check for `null`, `undefined`, or `“”` **empty strings** explicitly.

```javascript
if (value !== null && value !== undefined) {
    console.log("Value exists");
}
```

> This ensures that only **non-null** and **defined** values are considered valid.

***Use*** `parseInt()` ***and*** `parseFloat()` ***for*** `Number` ***Conversion***

```javascript
console.log(parseInt("42px")); //42
console.log(parseFloat("3.14abc")); //3.14
```

> This will parse the **number part of a string**, ensuring a **valid** numeric conversion.

***Handle*** `NaN` ***Properly***

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><em>Use </em><code>isNaN()</code><em> to check if a value is </em><code>NaN</code><em> instead of comparing it directly.</em></div>
</div>

```javascript
if (isNaN(value)) {
    console.log("Invalid number");
}
```

> This ensures you're correctly detecting **NaN** and handling it appropriately.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/0a984d83-f200-4334-9b7a-3a1375efb42b.jpg align="center")

### ***Type conversion***

***Manually*** or ***explicitly*** convert the ***type*** of a value from ***one data-type*** to ***another***.

***Original value doesn’t converted.***

*JavaScript can only convert to* ***three*** *types. we can convert to a* `number`*, to a* `string`*, or to a* `boolean`*.*

```javascript
const inputYear = "1996";
console.log(Number(inputYear), inputYear);
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/448df7c0-21e0-4347-81a3-cfaea3da2c9b.jpg align="center")

### ***Function***

The fundamental ***building block*** of real-world JavaScript applications are `functions`. It’s a reusable piece of code.

***function declaration***

```javascript
function logger() {//function-body
  console.log("My name is Ayan");
}
//calling or running or invoking function
logger();
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/da979edf-5cce-4955-ab7b-c456b2f99c99.jpg align="center")

We can **pass** data into a `function`. It can return data as well. We can pass `parameters` to the function, the parameters are like **variables** that are **specific** only to this function and they will get defined `once` we `call` the `function`.

These are like **placeholders** that actually replaced by `arguments` that passed to the function.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/6d839598-2577-4c17-8f29-d63ead73f1cc.jpg align="center")

```javascript
function calcAge1(birthYear) {
  return 2026 - birthYear;
}

const age = calcAge1(2015);
console.log("Ayan is", age, "years old.");
```

> ***This function is called function declaration.***

### *return* statement

*   The `return` ***statement*** is used to send a result back from a function.
    
*   When `return` executes, the function `stops` running at that point.
    
*   The `returned` value can be stored in a `variable` or used directly.
    

```javascript
function fruitProcessor(apples, oranges) {//(apples,oranges) are Parameters

  const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
  return juice;
}

const appleJuice = fruitProcessor(2, 0); //(2, 0)--> Arguments
console.log(appleJuice);

const applesOrangesJuice = fruitProcessor(3, 5);
console.log(applesOrangesJuice);
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/e52c6e8c-8701-4ba1-8dbc-af697029979d.jpg align="center")

### *Function expression & declaration*

In JavaScript there are different way of writing `functions` and each type of **function**, works in a slightly different way.

### ***function declaration / named function***

*A function that has its* `own` *name when declared. It’s easy to reuse and debug because the* `name` *shows up in* `error messages` *or* `stack traces`*.*

```javascript
function calcAge1(birthYear) {
  return 2026 - birthYear;
}

const age = calcAge1(2015);
console.log("Ayan is", age, "years old.");
```

### ***function expression* / *Anonymous function***

*An* `anonymous` *function is a function defined without an* `explicit name.` *It is commonly used as a* `callback` *or assigned to a* `variable`*. It can be* ***named*** *or* ***anonymous****.*

```javascript
const calcAge2 = function (birtYear) {
  //Anonymous function or function expression
  return 2026 - birtYear;
};
const ageAltamash = calcAge2(2005);
console.log("Altamash is", ageAltamash, "years old.");

/*
function (birtYear) {
  return 2026 - birtYear;
}; It's the expression and produces a vlue
*/
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/0824d7e3-275e-4aa5-9c45-a9200dc38481.jpg align="center")

### ***Hoisting***

*Functions in JavaScript just are actually* ***values****. function* `declarations` *can called before they defined in the code. Internally this happens because of the process* `hoisting`*.*

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/46c5cb56-0899-4e83-a067-37ae6f76bc44.jpg align="center")

### ***(=>) arrow function***

***An*** `arrow function` ***is simply a special form of function*** `expression` ***that is shorter and therefore faster to write. It was introduced in*** `ES6`***. They don’t their*** `this` ***binding.***

```javascript
const yearsUntilRetirement = (birtYear, firstName) => {
  const age = 2026 - birtYear;
  const retirement = 60 - age;
  return `${firstName} retires in ${retirement} years.`;
};

const retirementYears = yearsUntilRetirement(1980, "Jacob");
console.log(retirementYears);
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/001d69ca-1b08-40c3-9be7-56ea978d64a0.jpg align="center")

### ***this keyword***

`this` refers the **current context. It means the** `object` **is calling this function.**

### ***calling one function from inside another function***

```javascript
function fruitProcessor(apples, oranges) {
  const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
  return juice;
}
```

*This function is like a* `fruit processor` *which received a certain number of* `apples` *and a certain number of* `oranges`*. And then based on that it basically produced and returned juice to us. Simulate to calling one function from inside another function.*

`fruit processor` *can only make juice with smaller fruit pieces. And so before making the juice the fruit processor now needs another machine that first cuts the fruits that we give it into multiple smaller pieces.*

```javascript
function cutFruitPieces(fruit) {
  return fruit * 4;
}

function fruitProcessor(apples, oranges) {
  const applePieces = cutFruitPieces(apples);
  const orangePieces = cutFruitPieces(oranges);
  const juice = `Juice with ${applePieces} piece of apple and ${orangePieces} piece of orange.`;
  return juice;
}
console.log(fruitProcessor(2, 3));
```

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/d5cdb2bc-514e-43b4-a3cf-2be98662ec3c.jpg align="center")

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong><em>Which JavaScript concept do you find the most confusing? Share it in the comments, and let’s learn together.</em></strong></div>
</div>
