top of page

Advanced JavaScript - Episode 5

There’s a saying: In the world, there are only things that many people curse at and things that no one bothers to use.

JavaScript is a prime example. It has some interesting features, but it can also give us headaches. The theory is easy to understand, but when it comes to practice, it’s a whole different story. So, let's dive into specific examples and analyze them to better understand JavaScript.

This series might be quite long—I don't know how many episodes there will be. However, for those who haven't read my previous articles on JS, I will explain everything again in this series. The theories in these articles may also be repeated multiple times (depending on my mood) so you can grasp them better. Okay, let’s dive in... GÉT GÔ 🚀

If you have any questions, don't hesitate to comment below. Or just leave a comment to say hi; it will motivate me to complete this series. Thank you very much. 🤗


JavaScript

1. The eval Function in JavaScript

What is the value of sum?

const sum = eval("10*10+5");

A: 105

B: "105"

C: TypeError

D: "10*10+5"

The answer is A.

Let's find out why this is the case ❓️

1.1. What is the eval function?

The eval function in JavaScript is a special function that allows us to execute a piece of JavaScript code represented as a string. It will evaluate and execute that code.

Example:

const result = eval("2 + 2");
console.log(result); // Output: 4

In the example above, the eval function will evaluate the expression "2 + 2" and return the result, which is 4.

1.2. Code Analysis

Going back to the original code:

const sum = eval("10*10+5");

Here, we pass a string containing a mathematical expression "10*10+5" into the eval function. The eval function will evaluate this expression and calculate the result.

The expression "10*10+5" is equivalent to the operation 10 times 10 plus 5, which results in 105.

Therefore, the value of the variable sum will be 105, matching answer A.

1.3. Caution When Using eval

Although the eval function can be useful in some cases, it also poses significant security risks. If we use eval with untrusted input (e.g., data from users), attackers can inject malicious code and execute it.

Therefore, it is best to avoid using eval if possible. Instead, try to find safer alternatives.

2. Storing Data with sessionStorage

How long will the cool_secret variable be accessible?

sessionStorage.setItem("cool_secret", 123);

A: Forever, the data will never be lost.B: When the user closes the tab.C: When the user not only closes the tab but also closes the browser.D: When the user shuts down the computer.

The answer is B.

Let's find out why this is the case ❓️

2.1. What is sessionStorage?

sessionStorage is an object in the Web Storage API of JavaScript. It allows us to store data as key-value pairs in the browser.

The characteristic of sessionStorage is that the data will exist within the user's session. When the user closes the tab or browser window, the data in sessionStorage will be deleted.

2.2. Code Analysis

In the above code, we use the setItem method of sessionStorage to store a key-value pair. The key is "cool_secret" and the value is 123.

sessionStorage.setItem("cool_secret", 123);

This means we are storing the value 123 with the key "cool_secret" in sessionStorage.

2.3. Data Lifetime in sessionStorage

As mentioned, data in sessionStorage will exist within the user's session. When the user closes the tab or browser window, the data will be deleted.

Therefore, the correct answer to this question is B: When the user closes the tab.

2.4. Comparison with localStorage

Besides sessionStorage, JavaScript also provides another object for storing data: localStorage. The main difference between sessionStorage and localStorage is:

  • Data in sessionStorage will be deleted when the tab or browser window is closed.

  • Data in localStorage will exist permanently until it is manually deleted or deleted by JavaScript.

If we want to store data for a long time, which does not get lost when the browser is closed, localStorage will be a more suitable choice.

3. Declaring Variables with var

What is the output?

var num = 8;
var num = 10;
console.log(num);

A: 8

B: 10

C: SyntaxError

D: ReferenceError

The answer is B.

Let's find out why this is the case ❓️

3.1. Declaring Variables with var

In JavaScript, the var keyword is used to declare variables. One characteristic of var is that it allows redeclaration of variables with the same name without causing errors.

When we redeclare a variable with var, the value of the variable will be updated to the most recent value.

3.2. Code Analysis

Consider the following code:

var num = 8;
var num = 10;
console.log(num);

Here, we declare the variable num twice with the var keyword.

  • The first time, num is assigned the value 8.

  • The second time, num is reassigned the value 10.

When we call console.log(num), the value of num will be the most recent value, which is 10.

Therefore, the output of the above code will be 10, matching answer B.

3.3. Comparison with let and const

Unlike var, the let and const keywords in JavaScript do not allow redeclaration of variables with the same name within the same scope (block scope).

If we try to redeclare a variable with let or const, it will cause a SyntaxError.

Example:

let count = 5;
let count = 10; // SyntaxError
const value = 3;
const value = 6; // SyntaxError

Therefore, when using let and const, we need to be careful not to redeclare variables with the same name within the same scope. However, the best practice is to avoid redeclaring variables with the same name even when using var. And most of you should stop using var and use let or const instead. Only use var when you fully understand it.

4. Checking for Key Existence in Objects and Sets

What is the output?

const obj = { 1: "a", 2: "b", 3: "c" };
const set = new Set([1, 2, 3, 4, 5]);
obj.hasOwnProperty("1");
obj.hasOwnProperty(1);
set.has("1");
set.has(1);

A: true false false trueB: false true true trueC: true true false trueD: true true true true

The answer is C.

Let's find out why this is the case ❓️

4.1. Code Analysis

First, we have an object obj with keys as numbers and values as strings. Although we didn't write the keys as strings, they will always be converted to strings under the hood.

Therefore, obj.hasOwnProperty('1') returns true. Similarly, obj.hasOwnProperty(1) also returns true, because the value 1 will be automatically converted to a string.

Next, we have a Set. Unlike objects, Set does not convert keys to strings. In our Set, there is no value '1', so set.has('1') returns false. However, the Set does contain the numeric value 1, so set.has(1) returns true.

4.2. Summary

When working with objects, remember that keys are always converted to strings (unless they are Symbols). But with Set, this does not happen. That's why obj.hasOwnProperty('1') returns true, but set.has('1') returns false.

Symbol is a new data type introduced in ES6 that creates an immutable and unique value used as the key for object properties. Example: const mySymbol = Symbol();. I'll introduce more details about Symbol in another article.

5. Overwriting Properties in Objects

What is the output?

const obj = { a: "one", b: "two", a: "three" };
console.log(obj);

A: { a: "one", b: "two" }

B: { b: "two", a: "three" }

C: { a: "three", b: "two" }

D: SyntaxError

The answer is C.


Comments


bottom of page