DEV Community

Whoissosick
Whoissosick

Posted on

Foundation JS

toString() Method

It's a method you can use for numbers, booleans, arrays, and objects.

const num = 10;
console.log(num.toString()); // "10"

const arr = [1, 2, 3];
console.log(arr.toString()); // "1,2,3"

const person = {
  name: "John",
  age: 30,
  isStudent: true
};

console.log(person.toString()); // "[object Object]"
Enter fullscreen mode Exit fullscreen mode

What Is the Number Constructor, and How Does It Work for Type Coercion?

The Number() constructor is used to create a number object. The number object contains a few helpful properties and methods like the isNaN and the toFixed method.

const myNum = new Number("34");
console.log(typeof myNum); // "object" 
Enter fullscreen mode Exit fullscreen mode

In this example we pass in a string literal to the Number() constructor and the return type is of type object instead of a string.

When the Number() constructor is called as a function without the new keyword, then the return value will be the primitive number type. Most of the time you will be using the Number() constructor to convert other data types to the number data type. Here's an example of converting a string to a number:

const myNum = Number("100");
console.log(myNum); // 100

console.log(typeof myNum); // number
Enter fullscreen mode Exit fullscreen mode

This is helpful when you are getting input from the user and you need to convert that string input to a number so you can perform mathematical calculations.

If you try to call the Number() constructor through an empty string then the result will be the number 0:

const num = Number("");
console.log(num); // 0

const num = Number("random");
console.log(num); // NaN

const boolTrue = Number(true);
const boolFalse = Number(false);
console.log(boolTrue); // 1
console.log(boolFalse); // 0

const undefinedNum = Number(undefined);
const nullNum = Number(null);
console.log(undefinedNum); // NaN
console.log(nullNum); // 0
Enter fullscreen mode Exit fullscreen mode

When working with arrays there are a few things to consider.

An empty array will return 0. An array with a single number will return that number. An array with multiple numbers returns NaN. And an array with string(s) will also return NaN.

const emptyArr = Number([]);
const arrOneNum = Number([7]);
const arrMultiNum = Number([7, 36, 12]);
const arrStr = Number(["str1"]);
const arrMultiStr = Number(["str1", "str2"]);

console.log(emptyArr); // 0
console.log(arrOneNum); // 7
console.log(arrMultiNum); // NaN
console.log(arrStr); // NaN
console.log(arrMultiStr); // NaN
Enter fullscreen mode Exit fullscreen mode

When working with objects, the result is always NaN.

Common Practices for Naming Variables and Functions?

For boolean variables, it's a common practice to use prefixes such as is, has, or can. This immediately tells the reader that the variable is a boolean:

let isLoading = true;
let hasPermission = false;
let canEdit = true;

function getUserData(){
  /* ... */
}

function isValidEmail(email) {
  /* For functions that return a boolean often called predicates */
}

function getProductDetails(productId) {
  /* retrieve data */
}

function handleClick(){
  /* For event handler functions */
}
Enter fullscreen mode Exit fullscreen mode

How Can You Create an Empty Array of Fixed Length?

Array() constructor & Array.from()

const emptyArray = new Array(5);
console.log(emptyArray.length); // 5
console.log(emptyArray); // [undefined, undefined, undefined, undefined, undefined]

const fixedLengthArray = Array.from({ length: 5 });
console.log(fixedLengthArray.length); // 5

// [undefined, undefined, undefined, undefined, undefined]
console.log(fixedLengthArray);
Enter fullscreen mode Exit fullscreen mode

If you want to create an array of specific length and fill it with a default value, you can use the Array.fill() method:

const filledArray = new Array(3).fill(0);
console.log(filledArray); // [0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

What Are Linters and Formatters, and How Can They Help You with Code Consistency?

Linters = A linter is a static code analysis tool that flags programming errors, bugs, stylistic errors, and suspicious constructs (ESLint).

Formatters = ensure a consistent code style across an entire project or team regardless of individual developer preferences (Prettier).

What Is Memory Management, and How Does It Work in JavaScript?

JavaScript however uses automatic memory management. This means that JavaScript (more specifically the JavaScript engine in your web browser) takes care of memory allocation and deallocation for you. You don't have to explicitly free memory in your code. This automatic process is often called garbage collection.

Closure = функция, которая "помнит" переменные из внешней области видимости
Управление памятью = garbage collector не может удалить то, на что ещё есть ссылки

What Are Closures, and How Do They Work?

Closure is a function that has access to variables in its outer enclosing lexical scope, even after the outer function has returned.

function outerFunction(x) {
    let y = 10;
    function innerFunction(){
        console.log(x + y);
    }
    return innerFunction;
}

let closure = outerFunction(5);
console.log(closure()); // 15
Enter fullscreen mode Exit fullscreen mode

In this example, outerFunction takes a parameter x and defines a local variable y. It then defines an innerFunction that uses both x and y. Finally it returns innerFunction. When we call outerFunction(5) it returns innerFunction which we assign to the variable closure. When we later call closure() it still has access to x and y from outerFunction even though outerFunction has already finished executing. This is the essence of a closure.

Closures are particularly useful for creating private variables and functions. Consider this example:

function createCounter() {
    let count = 0;
    return function () {
        count++;
        return count;
    };
}

let counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Enter fullscreen mode Exit fullscreen mode

In this case, createCounter returns a function that increments and returns a count variable. The count variable is not directly accessible from outside createCounter, but the returned function (our closure) has access to it. Each time we call counter(), it increments and returns the count.

Closures can also capture multiple variables from their outer scope. For example:

function multiply(x) {
    return function (y) {
        return x * y;
    };
}

let double = multiply(2);
console.log(double(5)); // 10
Enter fullscreen mode Exit fullscreen mode

One important thing to note about closures is that they capture variables, by reference not by value. This means if the value of a captured variable changes, the closure will see the new value. For example:

function createIncrementer() {
    let count = 0;
    return function () {
        count++;
        console.log(count);
    };
}

let increment = createIncrementer();
increment(); // 1
increment(); // 2
Enter fullscreen mode Exit fullscreen mode

Each time we call increment its working with the same count variable, not a copy of it's initial value.

Top comments (0)